亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

使用Mybatis如何實現對數據庫進行增刪改查操作

發布時間:2020-11-19 15:56:23 來源:億速云 閱讀:303 作者:Leah 欄目:編程語言

本篇文章為大家展示了使用Mybatis如何實現對數據庫進行增刪改查操作,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。

什么是 MyBatis?

MyBatis 是支持普通 SQL 查詢,存儲過程和高級映射的優秀持久層框架。 MyBatis 消除了幾乎所有的 JDBC 代碼和參數的手工設置以及對結果集的檢索。MyBatis 可以使用簡單的XML 或注解用于配置和原始映射,將接口和 Java 的 POJO(Plain Old Java Objects,普通的Java對象)映射成數據庫中的記錄。

Mybatis實例

對一個User表的CRUD操作:

User表:

-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `userName` varchar(50) DEFAULT NULL,
 `userAge` int(11) DEFAULT NULL,
 `userAddress` varchar(200) DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'summer', '30', 'shanghai');
INSERT INTO `user` VALUES ('2', 'test2', '22', 'suzhou');
INSERT INTO `user` VALUES ('3', 'test1', '29', 'some place');
INSERT INTO `user` VALUES ('4', 'lu', '28', 'some place');
INSERT INTO `user` VALUES ('5', 'xiaoxun', '27', 'nanjing');

在Src目錄下建一個mybatis的xml配置文件Configuration.xml

<&#63;xml version="1.0" encoding="UTF-8" &#63;>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <!-- mybatis別名定義 -->
  <typeAliases> 
    <typeAlias alias="User" type="com.mybatis.test.User"/> 
  </typeAliases> 

  <environments default="development">
    <environment id="development">
    <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
      <property name="driver" value="com.mysql.jdbc.Driver"/>
      <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis" />
      <property name="username" value="root"/>
      <property name="password" value="admin"/>
      </dataSource>
    </environment>
  </environments>
  
  <!-- mybatis的mapper文件,每個xml配置文件對應一個接口 -->
  <mappers>
    <mapper resource="com/mybatis/test/User.xml"/>
  </mappers>
</configuration>

定義User mappers的User.xml配置文件

<&#63;xml version="1.0" encoding="UTF-8" &#63;>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.mybatis.test.IUserOperation">

  <!-- select語句 -->
  <select id="selectUserByID" parameterType="int" resultType="User">
    select * from `user` where user.id = #{id}
  </select>
  
  <!-- 定義的resultMap,可以解決類的屬性名和數據庫列名不一致的問題-->
  <!-- <resultMap type="User" id="userResultMap">
    <id property="id" column="user_id" />
    <result property="userName" column="user_userName" />
    <result property="userAge" column="user_userAge" />
    <result property="userAddress" column="user_userAddress" />
  </resultMap> -->
  
  <!-- 返回list的select語句,注意 resultMap的值是指向前面定義好的 -->
  <!-- <select id="selectUsersByName" parameterType="string" resultMap="userResultMap">
    select * from user where user.userName = #{userName}
  </select> -->
  
  <select id="selectUsersByName" parameterType="string" resultType="User">
    select * from user where user.userName = #{userName}
  </select>
  
  <!--執行增加操作的SQL語句。id和parameterType分別與IUserOperation接口中的addUser方法的名字和參數類型一致。
  useGeneratedKeys設置為"true"表明要MyBatis獲取由數據庫自動生成的主鍵;keyProperty="id"指定把獲取到的主鍵值注入到User的id屬性--> 
  <insert id="addUser" parameterType="User" 
    useGeneratedKeys="true" keyProperty="id"> 
    insert into user(userName,userAge,userAddress) 
       values(#{userName},#{userAge},#{userAddress}) 
  </insert>
  
  <update id="updateUser" parameterType="User" >
    update user set userName=#{userName},userAge=#{userAge},userAddress=#{userAddress} where id=#{id}
  </update>
  
  <delete id="deleteUser" parameterType="int">
    delete from user where id=#{id}
  </delete>
  
</mapper>

配置文件實現了接口和SQL語句的映射關系。selectUsersByName采用了2種方式實現,注釋掉的也是一種實現,采用resultMap可以把屬性和數據庫列名映射關系定義好,property為類的屬性,column是表的列名,也可以是表列名的別名!

User類的定義:

package com.mybatis.test;

public class User {
  
  private int id;
  private String userName;
  private int userAge;
  private String userAddress;
  
  public int getId() {
    return id;
  }
  
  public void setId(int id) {
    this.id = id;
  }
  
  public String getUserName() {
    return userName;
  }
  
  public void setUserName(String userName) {
    this.userName = userName;
  }
  
  public int getUserAge() {
    return userAge;
  }
  
  public void setUserAge(int userAge) {
    this.userAge = userAge;
  }
  
  public String getUserAddress() {
    return userAddress;
  }
  
  public void setUserAddress(String userAddress) {
    this.userAddress = userAddress;
  }
  
  @Override
  public String toString(){
    return this.userName+" "+this.userAge+" "+this.userAddress;
  }

}

IUserOperaton定義:

package com.mybatis.test;

import java.util.List;

public interface IUserOperation {
  
  public User selectUserByID(int id);
  
  public List<User> selectUsersByName(String userName);
  
  public void addUser(User user);
  
  public void updateUser(User user);
  
  public void deleteUser(int id);
  
}

IUserOperation為操作接口,函數名和mybatis的xml配置文件中的操作id名對應。

測試類Test:

package com.mybatis.test;

import java.io.Reader;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class Test {

  private static SqlSessionFactory sqlSessionFactory;
  private static Reader reader;

  static {
    try {
      reader = Resources.getResourceAsReader("Configuration.xml");
      sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static SqlSessionFactory getSession() {
    return sqlSessionFactory;
  }

  public void getUserByID(int userID) {
    SqlSession session = sqlSessionFactory.openSession();
    try {
      IUserOperation userOperation = session
          .getMapper(IUserOperation.class);
      User user = userOperation.selectUserByID(userID);
      if (user != null) {
        System.out.println(user.getId() + ":" + user.getUserName()
            + ":" + user.getUserAddress());
      }

    } finally {
      session.close();
    }
  }

  public void getUserList(String userName) {
    SqlSession session = sqlSessionFactory.openSession();
    try {
      IUserOperation userOperation = session
          .getMapper(IUserOperation.class);
      List<User> users = userOperation.selectUsersByName(userName);
      for (User user : users) {
        System.out.println(user.getId() + ":" + user.getUserName()
            + ":" + user.getUserAddress());
      }

    } finally {
      session.close();
    }
  }

  /**
   * 增加后要commit
   */
  public void addUser() {
    User user = new User();
    user.setUserAddress("place");
    user.setUserName("test_add");
    user.setUserAge(30);
    SqlSession session = sqlSessionFactory.openSession();
    try {
      IUserOperation userOperation = session
          .getMapper(IUserOperation.class);
      userOperation.addUser(user);
      session.commit();
      System.out.println("新增用戶ID:" + user.getId());
    } finally {
      session.close();
    }
  }

  /**
   * 修改后要commit
   */
  public void updateUser() {
    SqlSession session = sqlSessionFactory.openSession();
    try {
      IUserOperation userOperation = session
          .getMapper(IUserOperation.class);
      User user = userOperation.selectUserByID(1);
      if (user != null) {
        user.setUserAddress("A new place");
        userOperation.updateUser(user);
        session.commit();
      }
    } finally {
      session.close();
    }
  }

  /**
   * 刪除后要commit.
   * 
   * @param id
   */
  public void deleteUser(int id) {
    SqlSession session = sqlSessionFactory.openSession();
    try {
      IUserOperation userOperation = session
          .getMapper(IUserOperation.class);
      userOperation.deleteUser(id);
      session.commit();
    } finally {
      session.close();
    }
  }

  public static void main(String[] args) {
    try {
      Test test = new Test();
      // test.getUserByID(1);
      // test.getUserList("test1");
      // test.addUser();
      // test.updateUser();
      // test.deleteUser(6);

    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }

}

上述內容就是使用Mybatis如何實現對數據庫進行增刪改查操作,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

炉霍县| 海晏县| 晋宁县| 五常市| 和林格尔县| 寿阳县| 当雄县| 夏津县| 喀喇| 柘荣县| 壶关县| 乐业县| 沂南县| 白沙| 浮山县| 杂多县| 万安县| 台前县| 麦盖提县| 陈巴尔虎旗| 和平县| 房山区| 永年县| 交口县| 根河市| 彰化县| 津南区| 天水市| 广灵县| 岚皋县| 会同县| 丹阳市| 宁河县| 黔江区| 图们市| 特克斯县| 呈贡县| 桦甸市| 龙门县| 公主岭市| 彭山县|