Query by id
- Create method in dao interface
public interface userDao{
//通过id查询用户的方法
User findOne(Integer id);
}
- 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>
- Register the mapper in the main configuration file
- Just test
Like query
1. Define an abstract method in the interface
public interface UserDao{
List<User> findLike(String name);
}
- 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
- Register Mapper [Registration is not necessary if you have already registered]
- 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>
- Register Mapper
- Writing test methods
Next article update: resultMap solves the inconsistency between entity class attributes and database fields