MyBatis query by id, like query, total number of records [detailed like query]

Query by id


  1. Create method in dao interface
public interface userDao{
    
    
	//通过id查询用户的方法
	User findOne(Integer id);
}
  1. Write SQL in the mapping configuration file
	<?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. Register the mapper in the main configuration file
  2. Just test

Like query


1. Define an abstract method in the interface

public interface UserDao{
    
    
	List<User> findLike(String name);
}
  1. Write SQL in the mapping file
	<?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>

There are two ways to write the value here, one is #{name} and the other is' %${value}%"
%: placeholder, it is not necessary to provide it in the test class

#{name} :

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

${name} :

		- 使用的是普通的数据库操作队形,不安全,有SQL注入问题
		- 可以进行排序查询
		- 不管传进来啥 都是 ${value}  value是固定的
		- statement
  1. Register Mapper [Registration is not necessary if you have already registered]
  2. Execution test method

Query the total number of records


1. Add a method in UserDao

public interface UserDao{
    
    
	Integer countAll();
}

2. Write SQL in Mapper

<select id="countAll" resultType="Integer">
	select count(*) from user
</select>
  1. Register Mapper
  2. Writing test methods

Next article update: resultMap solves the inconsistency between entity class attributes and database fields

Guess you like

Origin blog.csdn.net/m0_46409345/article/details/108623971