1. 程式人生 > 實用技巧 >11mybatis對映檔案

11mybatis對映檔案

對映檔案

對映檔案主要寫主要寫增刪改查操作,將sql語句和JavaBean類關聯在一起。

配置檔案為:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="userMapper">
    <!--各種操作--->
</mapper>

查詢

對映檔案

  • resultType指定返回值型別
<select id="findAll" resultType="com.domain.User">
	select * from user
</select>

測試程式碼

List<User> userList = sqlSession.selectList("userMapper.findAll");
System.out.println(userList);

插入

對映檔案

  • parameterType指定引數型別
  • #{}中的引數是User中的屬性
<insert id="insert" parameterType="com.domain.User">
    insert into user values(#{id},#{username},#{password})
</insert>

測試程式碼

插入操作在mybatis中需要用到事務,mybatis插入更新操作預設不提交事務,需要手動寫提交程式碼。

User user = new User();
user.setUsername("John");
user.setPassword("John");
sqlSession.insert("userMapper.insert", user);
sqlSession.commit(); // 提交事務

List<User> userList = sqlSession.selectList("userMapper.findAll");
System.out.println(userList);

修改

對映檔案

<update id="update" parameterType="com.domain.User">
    update user set username=#{username}, password=#{password} where id=#{id}
</update>

測試程式碼

插入修改等操作在mybatis中需要用到事務,mybatis插入更新操作預設不提交事務,需要手動寫提交程式碼

User user = new User();
user.setUsername("John Snow");
user.setPassword("123456");
user.setId(3);
sqlSession.update("userMapper.update", user);
sqlSession.commit();

刪除

對映檔案

<delete id="delete" parameterType="java.lang.Integer">
    delete from user where id=#{id}
</delete>

測試程式碼

插入修改等操作在mybatis中需要用到事務,mybatis插入更新操作預設不提交事務,需要手動寫提交程式碼

sqlSession.delete("userMapper.delete", 3);
sqlSession.commit();