MyBatis通过id查询,like查询,总记录数【详解like查询】

根据id查询


  1. 在dao接口中创建方法
public interface userDao{
    
    
	//通过id查询用户的方法
	User findOne(Integer id);
}
  1. 在映射配置文件中写SQL
	<?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="com.yixuexi.dao.UserDao">
  <select id="findOne" resultType="com.yixuexi.entity.User">
    select id,name,age from user where id = #{id}
  </select>
</mapper>
  1. 在主配置文件中注册该mapper
  2. 测试即可

Like查询


1.在接口中定义一个抽象方法

public interface UserDao{
    
    
	List<User> findLike(String name);
}
  1. 在映射文件中写SQL
	<?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="com.yixuexi.dao.UserDao">
  <select id="findLike" resultType="String" parameterType="com.yixuexi.entity.User">
    select id,name,age from user where name like #{name};
  </select>
</mapper>

这里的取值两种写法 一种是#{name} 一种是’ %${value}%"
% :占位符,在测试类就不需要提供了

#{name} :

		- 使用的是预编译的数据库操作对象,更加安全,不会有SQL注入
		- 常用但是不能进行排序查询
		- PrepatedStatement
		- 在测试类中传参的时候 需要提供 % _ 占位符

${name} :

		- 使用的是普通的数据库操作队形,不安全,有SQL注入问题
		- 可以进行排序查询
		- 不管传进来啥 都是 ${value}  value是固定的
		- statement
  1. 注册Mapper 【已经注册过就不需要注册了】
  2. 执行测试方法

查询总记录行数


1.在UserDao中添加方法

public interface UserDao{
    
    
	Integer countAll();
}

2.在Mapper中写SQL

<select id="countAll" resultType="Integer">
	select count(*) from user
</select>
  1. 注册Mapper
  2. 编写测试方法

下一篇更新:resultMap 解决实体类属性和数据库字段不一致问题

猜你喜欢

转载自blog.csdn.net/m0_46409345/article/details/108623971