MyBatis系列之模糊查询(注解方式+映射文件方式)

举报
yd_273762914 发表于 2020/12/03 01:16:14 2020/12/03
【摘要】   本博客以一个demo的形式说明模糊查询实现的两种方法: 项目结构如图:   ConditionUser.java: package com.mybatis.entity; public class ConditionUser { private String name; private int minAge; private int...

 

本博客以一个demo的形式说明模糊查询实现的两种方法:

项目结构如图:

 

ConditionUser.java:


  
  1. package com.mybatis.entity;
  2. public class ConditionUser {
  3. private String name;
  4. private int minAge;
  5. private int maxAge;
  6. public ConditionUser(String name,int minAge,int maxAge){
  7. this.name= name;
  8. this.minAge = minAge;
  9. this.maxAge = maxAge;
  10. }
  11. public String getName() {
  12. return name;
  13. }
  14. public void setName(String name) {
  15. this.name = name;
  16. }
  17. public int getMinAge() {
  18. return minAge;
  19. }
  20. public void setMinAge(int minAge) {
  21. this.minAge = minAge;
  22. }
  23. public int getMaxAge() {
  24. return maxAge;
  25. }
  26. public void setMaxAge(int maxAge) {
  27. this.maxAge = maxAge;
  28. }
  29. }

 

User.java:


  
  1. package com.mybatis.entity;
  2. public class User {
  3. /*
  4. * ID
  5. */
  6. private int id;
  7. /*
  8. * 用户姓名
  9. */
  10. private String name;
  11. /*
  12. * age
  13. */
  14. private int age;
  15. public int getId() {
  16. return id;
  17. }
  18. public void setId(int id) {
  19. this.id = id;
  20. }
  21. public String getName() {
  22. return name;
  23. }
  24. public void setName(String name) {
  25. this.name = name;
  26. }
  27. public int getAge() {
  28. return age;
  29. }
  30. public void setAge(int age) {
  31. this.age = age;
  32. }
  33. @Override
  34. public String toString() {
  35. return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
  36. }
  37. }

我们先以注解方式实现:


  
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  4. <configuration>
  5. <!-- 数据库配置文件 -->
  6. <properties resource="db.properties" />
  7. <!-- 实体类,简称 -设置别名 -->
  8. <typeAliases>
  9. <typeAlias alias="User" type="com.mybatis.entity.User" />
  10. </typeAliases>
  11. <!-- 读取db.properties里的数据,进行数据库配置 -->
  12. <environments default="development">
  13. <environment id="development">
  14. <transactionManager type="JDBC" />
  15. <dataSource type="POOLED">
  16. <property name="driver" value="${driver}"/>
  17. <property name="url" value="${url}" />
  18. <property name="username" value="${username}"/>
  19. <property name="password" value="${password}"/>
  20. </dataSource>
  21. </environment>
  22. </environments>
  23. <!--
  24. 注册userMapper.xml文件
  25. <mappers>
  26. <mapper resource="com/mybatis/mapper/userMapper.xml"/>
  27. </mappers>
  28. -->
  29. <mappers>
  30. <mapper class="com.mybatis.mapper.UserMapper"/>
  31. </mappers>
  32. </configuration>


db.properties:

 


  
  1. driver=com.mysql.jdbc.Driver
  2. url=jdbc\:mysql\://localhost\:3306/db_mysql?useUnicode\=true&characterEncoding\=utf-8
  3. username=root
  4. password=111

 

 

 

 

 

UserMapper.java:

 


  
  1. package com.mybatis.mapper;
  2. import java.util.List;
  3. import org.apache.ibatis.annotations.Delete;
  4. import org.apache.ibatis.annotations.Insert;
  5. import org.apache.ibatis.annotations.Select;
  6. import org.apache.ibatis.annotations.Update;
  7. import com.mybatis.entity.ConditionUser;
  8. import com.mybatis.entity.User;
  9. public interface UserMapper {
  10. @Insert("insert into users(name,age) values(#{name},#{age})")
  11. public void save(User user);
  12. @Update("update users set name=#{name},age=#{age} where id=#{id}")
  13. public boolean update(User user);
  14. @Delete("delete from users where id=#{id}")
  15. public boolean delete(int id);
  16. @Select("select * from users where id=#{id}")
  17. public User findById(int id);
  18. @Select("select * from users where name like #{name} and age >= #{minAge}")
  19. public List<User> findAll(ConditionUser u);
  20. }

 

 

 

测试:


  
  1. String resource = "mybatis-config.xml";
  2. try{
  3. //加载Mybatis的配置文件
  4. Reader reader = Resources.getResourceAsReader(resource);
  5. //构建sqlSession的工厂
  6. SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
  7. //创建可以执行sql的SqlSession
  8. SqlSession session = sessionFactory.openSession();
  9. // List<User> list = session.selectList("com.mybatis.mapper.userMapper.findById",new ConditionUser("%a%",0, 1));
  10. // System.out.println(list);
  11. UserMapper mapper = session.getMapper(UserMapper.class);
  12. List<User> list = mapper.findAll(new ConditionUser("%a%", 0, 1));
  13. System.out.println(list);
  14. Classes c = session.selectOne("com.mybatis.mapper.classesMapper.findById4",1);
  15. System.out.println(c);
  16. }catch (Exception e) {
  17. e.printStackTrace();
  18. }
  19. }

 

 

然后以映射文件的方式实现:

注意注解方式和映射文件方式是会冲突的,所以要先删了注解的接口类

然后,在新建userMapper.xml:


  
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <!--
  5. 为这个mapper指定一个唯一的namespace,namespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的
  6. -->
  7. <mapper namespace="com.mybatis.mapper.userMapper">
  8. <!--
  9. 在select标签中编写查询的SQL语句, 设置select标签的id属性为findById,id属性值必须是唯一的,不能够重复
  10. parameterType可以在MyBatis的配置文件里设置,也可以直接用包名+类名
  11. -->
  12. <insert id="save" parameterType="User">
  13. insert into users(id,name,age) value(#{name},#{age})
  14. </insert>
  15. <update id="update" parameterType="User">
  16. update users set name=#{name},age=#{age} where id=#{id}
  17. </update>
  18. <delete id="delete" parameterType="int">
  19. delete from users where id=#{id}
  20. </delete>
  21. <select id="findById" parameterType="com.mybatis.entity.ConditionUser" resultType="User">
  22. select * from users where age>=#{minAge}
  23. <if test='name!="%null%"'>and name like #{name}</if>
  24. </select>
  25. <select id="findAll" resultType="User">
  26. select * from users
  27. </select>
  28. </mapper>

 

修改mybatis配置文件:

 


  
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  4. <configuration>
  5. <!-- 数据库配置文件 -->
  6. <properties resource="db.properties" />
  7. <!-- 实体类,简称 -设置别名 -->
  8. <typeAliases>
  9. <typeAlias alias="User" type="com.mybatis.entity.User" />
  10. </typeAliases>
  11. <!-- 读取db.properties里的数据,进行数据库配置 -->
  12. <environments default="development">
  13. <environment id="development">
  14. <transactionManager type="JDBC" />
  15. <dataSource type="POOLED">
  16. <property name="driver" value="${driver}"/>
  17. <property name="url" value="${url}" />
  18. <property name="username" value="${username}"/>
  19. <property name="password" value="${password}"/>
  20. </dataSource>
  21. </environment>
  22. </environments>
  23. <!--
  24. 注册userMapper.xml文件
  25. <mappers>
  26. <mapper resource="com/mybatis/mapper/userMapper.xml"/>
  27. </mappers>
  28. -->
  29. <mappers>
  30. <mapper resource="com/mybatis/mapper/userMapper.xml"/>
  31. </mappers>
  32. </configuration>

 

 

 

 

测试:

 


  
  1. String resource = "mybatis-config.xml";
  2. try{
  3. //加载Mybatis的配置文件
  4. Reader reader = Resources.getResourceAsReader(resource);
  5. //构建sqlSession的工厂
  6. SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
  7. //创建可以执行sql的SqlSession
  8. SqlSession session = sessionFactory.openSession();
  9. List<User> list = session.selectList("com.mybatis.mapper.userMapper.findById",new ConditionUser("%a%",0, 1));
  10. System.out.println(list);
  11. // UserMapper mapper = session.getMapper(UserMapper.class);
  12. // List<User> list = mapper.findAll(new ConditionUser("%a%", 0, 1));
  13. // System.out.println(list);
  14. Classes c = session.selectOne("com.mybatis.mapper.classesMapper.findById4",1);
  15. System.out.println(c);
  16. }catch (Exception e) {
  17. e.printStackTrace();
  18. }

 

 

 

 

 

 


 

文章来源: smilenicky.blog.csdn.net,作者:smileNicky,版权归原作者所有,如需转载,请联系作者。

原文链接:smilenicky.blog.csdn.net/article/details/51292469

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。