根据id查询用户

参数占位符:

  • {}:先使用?占位,执行SQL时将具体值赋值给?

  • ${}:拼SQL,会存在SQL注入问题

    parameterType:

  • 用于设置参数类型,该参数可以省略

    SQL语句中特殊字符处理:

  • 转义字符
  • <![CDATA[ 内容 ]]> : CD提示
  1. public class TestMybatis {
  2. public static SqlSession sqlSession;
  3. @BeforeClass
  4. public static void demo() throws IOException {
  5. String resource = "mybatis-config.xml";
  6. InputStream inputStream = Resources.getResourceAsStream(resource);
  7. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  8. sqlSession = sqlSessionFactory.openSession(true);//自动提交事务
  9. }
  10. @Test
  11. public void test01() {
  12. UserMapper mapper = sqlSession.getMapper(UserMapper.class);
  13. User user = mapper.selectById(3);
  14. System.out.println(user);
  15. sqlSession.close();
  16. }
  17. }
  18. public interface UserMapper {
  19. User selectById(int uid);
  20. }
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.gdkm.mapper.UserMapper">
  6. <!--根据id查询用户-->
  7. <select id="selectById" resultType="com.gdkm.pojo.User">
  8. <!--#{参数名} : 先使用?占位,把参数值赋值给?
  9. ${参数名} : 字符串拼接,可以有SQL注入 不建议使用-->
  10. SELECT * FROM USER WHERE id = ${uid};
  11. </select>
  12. </mapper>

根据id删除用户

事务的处理

  • Java程序代码执行成功,但是数据库中并没有删除记录。
  • 原因是没有提交事务,数据库的增、删、改要求提交事务。

    方式一:手动提交事务

  • sqlSession.commit();

    方式二:自动提交事务

  • sqlSession = factory.openSession(true);
  1. public class TestMybatis {
  2. public static SqlSession sqlSession;
  3. @BeforeClass
  4. public static void demo() throws IOException {
  5. String resource = "mybatis-config.xml";
  6. InputStream inputStream = Resources.getResourceAsStream(resource);
  7. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  8. sqlSession = sqlSessionFactory.openSession(true);//自动提交事务
  9. }
  10. @Test
  11. public void test02() {
  12. UserMapper mapper = sqlSession.getMapper(UserMapper.class);
  13. mapper.deleteById(1);
  14. //注意:mybatis增删改需要提交事务
  15. //sqlSession.commit(); //手动提交事务
  16. sqlSession.close();
  17. }
  18. }
  19. public interface UserMapper {
  20. void deleteById(int uid);
  21. }
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.gdkm.mapper.UserMapper">
  6. <!--根据id删除用户-->
  7. <delete id="deleteById">
  8. DELETE FROM USER WHERE id = #{uid};
  9. </delete>
  10. </mapper>

根据id修改用户

  1. public class TestMybatis {
  2. public static SqlSession sqlSession;
  3. @BeforeClass
  4. public static void demo() throws IOException {
  5. String resource = "mybatis-config.xml";
  6. InputStream inputStream = Resources.getResourceAsStream(resource);
  7. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  8. sqlSession = sqlSessionFactory.openSession(true);//自动提交事务
  9. }
  10. @Test
  11. public void test03() {
  12. UserMapper mapper = sqlSession.getMapper(UserMapper.class);
  13. User user = new User(4, "蛤蟆吉", Date.valueOf("1249-07-02"), "男", "木叶村妙木山");
  14. int row = mapper.updateId(user);
  15. System.out.println("影响行数" + row);
  16. //注意:mybatis增删改需要提交事务
  17. //sqlSession.commit(); //手动提交事务
  18. sqlSession.close();
  19. }
  20. }
  21. public interface UserMapper {
  22. int updateId(User user);
  23. }
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.gdkm.mapper.UserMapper">
  6. <!--根据id修改用户-->
  7. <update id="updateId">
  8. UPDATE USER SET username = #{username}, birthday= #{birthday}, sex = #{sex}, address = #{address} WHERE id = #{id};
  9. </update>
  10. </mapper>

添加用户

通过属性useGeneratedKeys得到新增记录的主键值

useGeneratedKeys true,使用mysql生成的主键 keyProperty 实体类中对应的属性

  1. public class TestMybatis {
  2. public static SqlSession sqlSession;
  3. @BeforeClass
  4. public static void demo() throws IOException {
  5. String resource = "mybatis-config.xml";
  6. InputStream inputStream = Resources.getResourceAsStream(resource);
  7. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  8. sqlSession = sqlSessionFactory.openSession(true);//自动提交事务
  9. }
  10. @Test
  11. public void test04() {
  12. UserMapper mapper = sqlSession.getMapper(UserMapper.class);
  13. User user = new User(0, "盘丝大仙", Date.valueOf("1923-02-03"), "女", "水帘洞前址");
  14. int row = mapper.addId(user);
  15. System.out.println("影响行数" + row);
  16. //注意:mybatis增删改需要提交事务
  17. //sqlSession.commit(); //手动提交事务
  18. sqlSession.close();
  19. }
  20. }
  21. public interface UserMapper {
  22. int addId(User user);
  23. }
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.gdkm.mapper.UserMapper">
  6. <!--添加用户-->
  7. <insert id="addId" useGeneratedKeys="true" keyProperty="id">
  8. INSERT INTO user VALUES (NULL, #{username}, #{birthday}, #{sex}, #{address});
  9. </insert>
  10. </mapper>

多参数处理

多条件查询, 参数接收

  • 散装参数: 如果方法中有多个参数,需要使用@Param(“SQL参数占位符名称”)
  • 对象参数: 对象的属性名称要和参数占位符名称一致
  • Map集合参数: Map的键要和占位符名称一致
  1. public class TestMybatis {
  2. public static SqlSession sqlSession;
  3. @BeforeClass
  4. public static void demo() throws IOException {
  5. String resource = "mybatis-config.xml";
  6. InputStream inputStream = Resources.getResourceAsStream(resource);
  7. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  8. sqlSession = sqlSessionFactory.openSession(true);//自动提交事务
  9. }
  10. @Test
  11. public void test05() {
  12. UserMapper mapper = sqlSession.getMapper(UserMapper.class);
  13. // 调用接口中的方法
  14. // MyBatis多参数方案1
  15. // List<User> userList = mapper.selectByCondition("%精%", "男");
  16. // MyBatis多参数方案2
  17. /*User user = new User();
  18. user.setUsername("%精%");
  19. user.setSex("男");
  20. List<User> userList = mapper.selectByCondition(user);*/
  21. // MyBatis多参数方案3: 传入Map
  22. Map<String, String> map = new HashMap<>();
  23. map.put("username", "%精%");
  24. map.put("sex", "男");
  25. List<User> userList = mapper.selectByCondition(map);
  26. userList.forEach(System.out::println);
  27. sqlSession.close();
  28. }
  29. }
  30. public interface UserMapper {
  31. //mybatis多参数处理,使用用户名及性别模糊查询
  32. //mybatis多参数方案1,每个参数添加@Param注解
  33. //List<User>selectByCondition(@Param("username") String username, @Param("sex") String sex);
  34. //mybatis多参数方案2,传入自定义类
  35. //List<User>selectByCondition(User user);
  36. //mybatis多参数方案3,传入map
  37. List<User>selectByCondition(Map<String,String> map);
  38. }
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.gdkm.mapper.UserMapper">
  6. <!--模糊查询-->
  7. <select id="selectByCondition" resultType="com.gdkm.pojo.User">
  8. SELECT * FROM user WHERE username LIKE #{username} AND sex = #{sex};
  9. </select>
  10. </mapper>

动态SQL 多添加查询 if where标签

多条件查询:if标签

if标签的格式
  1. SQL片段

  2. 作用
  • if标签的作用当条件为true就拼接SQL片段

多条件查询:where标签

作用
  • 自动补全where这个关键字
  • 去掉多余的and和or关键字
  1. public class TestMybatis {
  2. public static SqlSession sqlSession;
  3. @BeforeClass
  4. public static void demo() throws IOException {
  5. String resource = "mybatis-config.xml";
  6. InputStream inputStream = Resources.getResourceAsStream(resource);
  7. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  8. sqlSession = sqlSessionFactory.openSession(true);//自动提交事务
  9. }
  10. @Test
  11. public void test05() {
  12. UserMapper mapper = sqlSession.getMapper(UserMapper.class);
  13. List<User> userList = mapper.selectByCondition(null, "男");
  14. userList.forEach(System.out::println);
  15. sqlSession.close();
  16. }
  17. public interface UserMapper {
  18. //mybatis多参数处理,使用用户名及性别模糊查询
  19. //mybatis多参数方案1,每个参数添加@Param注解
  20. List<User>selectByCondition(
  21. @Param("username") String username, @Param("sex") String sex
  22. );
  23. }
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.gdkm.mapper.UserMapper">
  6. <!--模糊查询-->
  7. <select id="selectByCondition" resultType="com.gdkm.pojo.User">
  8. SELECT * FROM user
  9. <where>
  10. <if test="username != null and username != ''">
  11. username LIKE #{username}
  12. </if>
  13. <if test="sex != null and sex != ''">
  14. AND sex = #{sex};
  15. </if>
  16. </where>
  17. </select>
  18. </mapper>

动态SQL 修改部分字段 set标签

set标签作用

  • 用在update语句中,相当于set关键字
  • 去掉SQL代码片段中后面多余的逗号
  1. public class TestMybatis {
  2. public static SqlSession sqlSession;
  3. @BeforeClass
  4. public static void demo() throws IOException {
  5. String resource = "mybatis-config.xml";
  6. InputStream inputStream = Resources.getResourceAsStream(resource);
  7. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  8. sqlSession = sqlSessionFactory.openSession(true);//自动提交事务
  9. }
  10. @Test
  11. public void test03() {
  12. UserMapper mapper = sqlSession.getMapper(UserMapper.class);
  13. User user = new User();
  14. user.setId(4);
  15. user.setBirthday(Date.valueOf("1950-05-09"));
  16. int row = mapper.updateId(user);
  17. System.out.println("影响行数" + row);
  18. //注意:mybatis增删改需要提交事务
  19. //sqlSession.commit(); //手动提交事务
  20. sqlSession.close();
  21. }
  22. public interface UserMapper {
  23. //根据id修改用户
  24. int updateId(User user);
  25. }
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.gdkm.mapper.UserMapper">
  6. <!--根据id修改用户-->
  7. <update id="updateId">
  8. UPDATE USER
  9. <set>
  10. <if test="username != null and username != ''">
  11. username = #{username},
  12. </if>
  13. <if test="birthday != null">
  14. birthday= #{birthday},
  15. </if>
  16. <if test="sex != null and sex != ''">
  17. sex = #{sex},
  18. </if>
  19. <if test="address != null and address != ''">
  20. address = #{address}
  21. </if>
  22. </set>
  23. WHERE id = #{id};
  24. </update>
  25. </mapper>

动态SQL 批量删除用户 foreach标签

foreach标签

foreach标签的属性
  • collection 参数名
  • item 设置变量名,代表每个遍历的元素
  • separator 遍历一个元素添加的内容
  • {变量名} 先使用?占位, 后面给?赋值

  • open 在遍历前添加一次字符
  • close 在遍历后添加一次字符
  1. public class TestMybatis {
  2. public static SqlSession sqlSession;
  3. @BeforeClass
  4. public static void demo() throws IOException {
  5. String resource = "mybatis-config.xml";
  6. InputStream inputStream = Resources.getResourceAsStream(resource);
  7. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  8. sqlSession = sqlSessionFactory.openSession(true);//自动提交事务
  9. }
  10. @Test
  11. public void test06() {
  12. UserMapper mapper = sqlSession.getMapper(UserMapper.class);
  13. int[] uid = new int[]{10, 11, 12};
  14. mapper.deleteByIds(uid);
  15. //注意:mybatis增删改需要提交事务
  16. sqlSession.commit(); //手动提交事务
  17. sqlSession.close();
  18. }
  19. public interface UserMapper {
  20. //批量删除用户
  21. int deleteByIds(@Param("uid") int[] uid);
  22. }
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.gdkm.mapper.UserMapper">
  6. <!--通过批量删除用户-->
  7. <delete id="deleteByIds">
  8. DELETE FROM user WHERE id IN
  9. <foreach collection="uid" item="id" open="(" separator="," close=");">
  10. #{id}
  11. </foreach>
  12. </delete>
  13. </mapper>

接口映射文件:resultMap输出映射

概述

  • MyBatis可以把查询的结果自动封装为对象
  • 但是有要求:查询结果的字段名称要与对象的成员变量名一致
  • 当查询结果的字段名称和类的成员变量名不一致,名称不一致的成员变量没有数据

解决方式

  • SQL语句使用AS将名字改为与类变量一致
  • 使用resultMap解决:resultMap可以建立查询的列与对象属性的对应关系
  • 在核心配置文件中使用settings设置mapUnderscoreToCamelCase为true将映射下划线为驼峰命名法
  1. public class Test02Mybatis {
  2. public static SqlSession sqlSession;
  3. @BeforeClass
  4. public static void demo() throws IOException {
  5. String resource = "mybatis-config.xml";
  6. InputStream inputStream = Resources.getResourceAsStream(resource);
  7. SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  8. sqlSession = sqlSessionFactory.openSession(true);//自动提交事务
  9. }
  10. @Test
  11. public void test01() {
  12. OrderMapper mapper = sqlSession.getMapper(OrderMapper.class);
  13. List<Order> orderList = mapper.findAllOrder();
  14. orderList.forEach(System.out::println);
  15. sqlSession.close();
  16. }
  17. }
  18. public interface OrderMapper {
  19. //查询所有商品信息
  20. List<Order>findAllOrder();
  21. }

使用SQL语句AS重命名解决

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.gdkm.mapper.OrderMapper">
  6. <select id="findAllOrder" resultType="com.gdkm.pojo.Order">
  7. <!--order在SQL是关键字,需要使用票符号-->
  8. SELECT
  9. o_id AS oId,
  10. user_id AS userId,
  11. number,
  12. create_time AS createTime,
  13. note
  14. FROM
  15. `order`;
  16. </select>
  17. </mapper>

在配置文件中使用settings设置mapUnderscoreToCamelCase解决

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. <settings>
  7. <!--在控制台显示SQL语句-->
  8. <setting name="logImpl" value="STDOUT_LOGGING"/>
  9. <!--开启驼峰命名自动映射数据库的_命名-->
  10. <setting name="mapUnderscoreToCamelCase" value="true"/>
  11. </settings>
  12. </configuration>

使用resultMap解决

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.gdkm.mapper.OrderMapper">
  6. <!--
  7. resultMap标签: 手动指定表中的字段名对应类中哪个成员变量
  8. id属性: 取个名字
  9. type属性: 查询的数据要封装的类型
  10. id子标签: 指定主键的对应关系
  11. result子标签: 指定普通字段的对应关系
  12. column属性: 表中的字段名
  13. property属性: 类中的成员变量名
  14. -->
  15. <resultMap id="OrderMapper" type="Order">
  16. <id column="o_id" property="oId"/>(oId出现爆红没影响,MyBatisX插件的问题)
  17. <result column="user_id" property="userId"/>
  18. <result column="create_time" property="createTime"/>
  19. </resultMap>
  20. <!--
  21. resultType属性:
  22. 表中字段名和类中成员变量相同使用resultType自动处理查询结果封装到对象中
  23. resultMap属性:
  24. 表中字段名和类中成员变量不相同使用, resultMap手动处理查询结果封装到对象中
  25. -->
  26. <select id="findAllOrder" resultMap="OrderMapper">
  27. <!--order在SQL是关键字,需要使用票符号-->
  28. SELECT * FROM `order`;
  29. </select>
  30. </mapper>