Table of contents
(1) Create a persistence layer interface and define a Sql statement on the interface method
2. Annotation realizes adding, deleting, checking and modifying
3. Annotation realizes dynamic sql
(1) Use script tags to implement dynamic Sql
(2) Build dynamic Sql in the method
Related reading
Mybatis column:
1. Environment construction
MyBatis can use annotations instead of mapping files. The function of the mapping file is to define the Sql statement, which can be used on the persistence layer interface
@Select/@Delete/@Insert/@Update defines Sql statements, so that there is no need to use mapping files.
1
Create a maven project and introduce dependencies (you can directly copy the pom.xml file of the previous maven project)
2
Create the mybatis core configuration file SqlMapConfig.xml
3
Put the log4j.properties file into resources and let the console print SQL statements.
4
Create an entity class (just let the previous entity class cv come over)
(1) Create a persistence layer interface and define a Sql statement on the interface method
package com.example.mapper;
import com.example.pojo.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface UserMapper {
// 查询所有用户
@Select("select * from user")
List<User> findAll();
}
Since the annotation is above the method, and there are parameter types and return value types in the method, development using annotations does not need to define parameter types and return value types
Register the persistence layer interface in the core configuration file. Since there is no mapping file, you can only use the method of registering the interface or registering the package. (shown in the code snippet below)
<mappers>
<package name="com.example.mapper"/>
</mappers>
(2) Test method
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.InputStream;
import java.util.List;
public class testUserMapper {
InputStream is = null;
SqlSession session = null;
UserMapper userMapper = null;
@Before
public void before() throws Exception{
is = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(is);
session = factory.openSession();
userMapper = session.getMapper(UserMapper.class);
}
@After
public void after() throws Exception{
session.close();
is.close();
}
@Test
public void testFindAll(){
List<User> all = userMapper.findAll();
all.forEach(System.out::println);
}
}
(3) Running results
The effect achieved is the same as using a mapping file.
2. Annotation realizes adding, deleting, checking and modifying
(1) Add users
Add methods and corresponding annotations
// 添加用户
@SelectKey(keyColumn = "id",keyProperty = "id",resultType = int.class,before = false,statement = "SELECT LAST_INSERT_ID()")
@Insert("insert into user(username,sex,address) values(#{username},#{sex},#{address})")
void add(User user);
In fact, the primary key backfill function has been used here, and there is no need to set the user id when adding a new user
Test Methods
// 测试增删查改方法
@Test
public void testADSU(){
// 新增一个用户
User user = new User("凉哥","男","北京");
userMapper.add(user);
session.commit();
}
operation result
OK, observe that we have indeed added Brother Liang
(2) Delete user
Add methods and corresponding annotations
// 删除用户
@Delete("delete from user where id = #{id}")
void delete(int id);
Test Methods
@Test
public void testADSU(){
/*// 新增一个用户
User user = new User("凉哥","男","北京");
userMapper.add(user);
session.commit();*/
// 删除用户
userMapper.delete(27);
session.commit();
}
operation result
OK, after observing the running results, we also know that Brother Liang was indeed deleted
(3) Fuzzy query users
Add methods and corresponding annotations
// 根据用户名模糊查询
@Select("select * from user where username like #{username}")
List<User> findByUsernameLike(String username);
Test Methods
Let's check the names with man
// 测试增删查改方法
@Test
public void testADSU(){
/*// 新增一个用户
User user = new User("凉哥","男","北京");
userMapper.add(user);
session.commit();
// 删除用户
userMapper.delete(27);
session.commit();*/
// 根据用户名模糊查询
List<User> users = userMapper.findByUsernameLike("%man%");
users.forEach(System.out::println);
}
operation result
OK, by comparing with the database table, it is indeed the query
(4) Update user information
Add methods and corresponding annotations
// 更新用户
@Update("update user set username = #{username},sex=#{sex},address=#{address} where id = #{id}")
void update(User user);
Test Methods
// 测试增删查改方法
@Test
public void testADSU(){
/*// 新增一个用户
User user = new User("凉哥","男","北京");
userMapper.add(user);
session.commit();
// 删除用户
userMapper.delete(27);
session.commit();*/
// 根据用户名模糊查询
/*List<User> users = userMapper.findByUsernameLike("%man%");
users.forEach(System.out::println);*/
// 更新用户
User user1 = new User(24,"哈士奇","女","上海外滩");
userMapper.update(user1);
session.commit();
}
Let's modify Ha Ge's data to see if it can be modified successfully
operation result
OK, the modification was indeed successful
3. Annotation realizes dynamic sql
Preface, but one thing to say, this annotation is more difficult to develop dynamic Sql implementation than mapping files, and the symbols must be found correctly.
There are two ways to build dynamic Sql in MyBatis annotation development :
(1) Use script tags to implement dynamic Sql
Nest Sql within <script> to use dynamic Sql tags:
New annotation method
// 根据任意条件查询--使用脚本标签
@Select("<script>"+
"select * from user \n" +
" <where>\n"+
" <if test=\"" +
" username != null and username.length() !=0 \">\n" +
" username like '%${username}%'\n" +
" </if>\n" +
" <if test=\"sex != null and sex.length() != 0\">\n" +
" and sex = #{sex}\n" +
" </if>\n" +
" <if test=\"address != null and address.length() != 0\">\n" +
" and address = #{address}\n" +
" </if>\n" +
" </where>" +
"</script>")
List<User> findByCondition(User user);
This is to realize fuzzy query of user name, precise query of gender and address
New test method
// 测试任意条件查询--使用脚本标签
@Test
public void testFindByCondition(){
User user = new User("an","man","Beijing");
List<User> all = userMapper.findByCondition(user);
all.forEach(System.out::println);
}
Query users with an in the name, man in the gender, and Beijing in the address.
operation result
OK, indeed all users who meet the requirements have been queried
(2) Build dynamic Sql in the method
In MyBatis there are @SelectProvider , @UpdateProvider , @DeleteProvider ,
@InsertProvider annotation. When using these annotations, you will not directly write SQL in the annotations , but call a method of a certain class to generate SQL .
New annotation method
// 根据任意条件查询--在方法中构建动态sql
@SelectProvider
default String findByConditionSql(User user){
StringBuffer sb = new StringBuffer("select * from user where 1 = 1");
if(user.getUsername()!=null && user.getUsername().length()!=0){
sb.append("and username like '%${username}%'");
}
if(user.getSex()!=null && user.getSex().length()!=0){
sb.append("and sex = #{sex}");
}
if(user.getAddress()!=null && user.getAddress().length()!=0){
sb.append("and address = #{address}");
}
return sb.toString();
}
New test method
// 测试任意条件查询--方法标签动态生成Sql
@Test
public void testFindByConditionSql(){
User user = new User("an","man","Beijing");
List<User> all = userMapper.findByCondition(user);
all.forEach(System.out::println);
}
operation result
OK, indeed the same query came out.