Mybatis 的注解开发-CRUD
# 200.Mybatis 的注解开发-CRUD
之前我们都是使用 XML 配置文件的方式来开发,虽然之前简单讲解过一点注解的开发,但是不多;本文就来将我们之前用的 XML 配置文件,全部替换成注解。 注意:注解 和 XML 不能混用,有注解就不能用 XML,会报错。
# 环境搭建
我们将除了 pom.xml 文件之外的文件都删掉,重新来搭建一次环境:
# 新增 User 类
public class User implements Serializable {
private Integer id;
private String username;
private String address;
private String sex;
private Date birthday;
}
1
2
3
4
5
6
7
2
3
4
5
6
7
请读者自行生成 getter 和 setter
# 新建 Dao 接口
package com.peterjxl.dao;
import com.peterjxl.domain.User;
import java.util.List;
public interface IUserDao {
List<User> findAll();
}
1
2
3
4
5
6
7
2
3
4
5
6
7
# 新增主配置文件 SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="jdbcConfig.properties"/>
<typeAliases>
<package name="com.peterjxl.domain"/>
</typeAliases>
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.peterjxl.dao"/>
</mappers>
</configuration>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 新建 log4j.properties
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 新建 jdbcConfig.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql:///LearnMybatis
jdbc.username=LearnMybatisUser
jdbc.password=LearnMybatisUserPassword
1
2
3
4
2
3
4
# 单表 CRUD 操作(代理 Dao 方式)
# 新增 select 注解
package com.peterjxl.dao;
import com.peterjxl.domain.User;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface IUserDao {
@Select("select * from user")
List<User> findAll();
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 新增测试类
package com.peterjxl;
import com.peterjxl.dao.IUserDao;
import com.peterjxl.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MybatisAnnoTest {
private InputStream in;
private SqlSessionFactoryBuilder builder;
private SqlSessionFactory factory;
private SqlSession session;
private IUserDao userDao;
@Before
public void init() throws IOException {
in = Resources.getResourceAsStream("SqlMapConfig.xml");
builder = new SqlSessionFactoryBuilder();
factory = builder.build(in);
session = factory.openSession();
userDao = session.getMapper(IUserDao.class);
}
@After
public void destroy() throws IOException {
session.commit();
session.close();
in.close();
}
@Test
public void testFindAll(){
List<User> users = userDao.findAll();
for(User user : users){
System.out.println(user);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# 新增 Insert 注解
在接口新建方法
@Insert("insert into user(username, address, sex, birthday) values (#{username}, #{address}, #{sex}, #{birthday})")
void saveUser(User user);
1
2
2
新建测试方法:
@Test
public void testSaveUser(){
User user = new User();
user.setUsername("mybatis anno save user");
user.setAddress("广州市番禺区");
user.setSex("男");
user.setBirthday(new Date());
userDao.saveUser(user);
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 新增 Update 注解
@Update("update user set username=#{username}, address=#{address}, sex=#{sex}, birthday=#{birthday} where id=#{id}")
void updateUser(User user);
1
2
2
测试方法:
@Test
public void testUpdate(){
User user = new User();
user.setId(41);
user.setUsername("mybatis anno update user");
user.setAddress("广州市番禺区");
user.setSex("男");
user.setBirthday(new Date());
userDao.updateUser(user);
session.commit();
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 新增 Delete 注解
@Delete("delete from user where id=#{id}")
void deleteUser(Integer userId);
1
2
2
@Test
public void testDelete(){
userDao.deleteUser(56);
}
1
2
3
4
2
3
4
# 查询一个
@Select("select * from user where id=#{id}")
User findById(Integer id);
1
2
2
@Test
public void testFindOne(){
User user = userDao.findById(41);
System.out.println(user);
}
1
2
3
4
5
2
3
4
5
# 模糊查询
写法一:注意这里没写百分号,所以传入的参数要带百分号
@Select("select * from user where username like #{username}")
List<User> findUserByName(String username);
1
2
2
测试方法:
@Test
public void testFindByName(){
List<User> users = userDao.findUserByName("mybatis%");
for(User user : users){
System.out.println(user);
}
}
1
2
3
4
5
6
7
2
3
4
5
6
7
写法二:
@Select("select * from user where username like '%${value}%'")
List<User> findUserByName(String username);
1
2
2
此时传参就不用百分号了:
@Test
public void testFindByName(){
// List<User> users = userDao.findUserByName("mybatis%");
List<User> users = userDao.findUserByName("mybatis");
for(User user : users){
System.out.println(user);
}
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 查询总数
@Select("select count(*) from user")
int findTotalUser();
1
2
2
@Test
public void testFindTotal(){
int total = userDao.findTotalUser();
System.out.println("total: " + total);
}
1
2
3
4
5
2
3
4
5
# 源码
所有代码已上传到了 GitHub (opens new window) 和 Gitee (opens new window) 上,并且创建了分支 demo19,读者可以通过切换分支来查看本文的示例代码。
上次更新: 2024/10/1 21:14:36