Spring Boot integration Mybatis (annotation mode and XML mode)

In fact, for me personally it was not familiar with JPA, hibernate, so that these two frameworks to use good trouble ah.

Mybatis has been used as a persistence framework,

JPA (Hibernate) advocated that all SQL generates Java code,

And even more Mybatis advocate the use of native SQL.

ready

# Import dependence

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>

Configuration parameters

Modify application.yml:

the Spring: 
the DataSource:
url: jdbc: MySQL: // localhost: 3306 / database_name characterEncoding = utf-8 // when some computers need to add parameters zone area or will be error?
username: root
password: root
Driver-class-name: COM. mysql.cj.jdbc.Driver

Initialize the database

-- create database springboot_mybatis charset utf8;

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
`username` varchar(255) DEFAULT NULL COMMENT '用户名',
`password` varchar(255) DEFAULT NULL COMMENT '密码',
`create_time` datetime DEFAULT NULL COMMENT '创建日期',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

Notes version

Mybatis provides some quick notes CRUD, such as: @Select, @Update, @Insert,@Delete

I believe you are reading this before you have used the Mybatis (such as the SSM before development),

So, using XML annotation mode in accordance with the wording of the way like SQL.

EDITORIAL before the SSM development time,

It will be in MapperScannerConfigurerthe configuration:

<property name="basePackage" value="xxx.mapper"/>Interface agent for use Mybatis development model (and XML interfaces and require the same name).

Then SpringBoot integration in Mybatis also have corresponding configurations:

One way: before each interface Mapper Add @Mappercomment

Second way: in Application.javaadded before the start of class @MapperScan("mapper所在的包名")notes

 

CRUD follows:

Creating Entity /entity/User.java

@Data 
@ToString
public class the User the implements Serializable { Private Long the above mentioned id; Private String username; Private String password; Private createTime a Date; // getter and setter notes do not have to write plug-ins with lombok } created interface 






/mapper/UserMapperAno.java
public interface UserMapperAno {

@Select("select * from user")
@Results({
@Result(property = "createTime", column = "create_time")
})
List<User> findAll();

@Select("select * from user where id = #{id}")
@Results({
@Result(property = "createTime", column = "create_time")
})
User findById(Long id);

@Insert("insert into user(username,password,create_time) values(#{username},#{password},#{createTime})")
void save(User user);

@Update("update user set username=#{username},password=#{password} where id=#{id}")
void update(User user);

@Delete("delete from user where id=#{id}")
void delete(Long id);
}

Wherein the @Resultannotation for modifying returns the result set, and if the Entity Data Field can be inconsistent modifications thereof

test

Create a test class /mapper/UserMapperAnoTest.java

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
@SpringBootTest
@RunWith(SpringRunner.class)
public class UserMapperAnoTest {
private Logger logger = LoggerFactory.getLogger(this.getClass());

@Autowired
private UserMapper userMapper;

@Test
public void testFindAll() {
List<User> list = userMapper.findAll();
list.forEach(user -> {
logger.info("user={}", user);
});
}

@Test
public void testFindById(){
logger.info("user={}", userMapper.findById(1L));
}

@Test
public void testSave(){
User user = new User();
user.setUsername("测试");
user.setPassword("123");
user.setCreateTime(new Date());
userMapper.save(user);
testFindAll();
}

@Test
public void testUpdate() {
User user = new User();
user.setId(4L);
user.setUsername("测试呀");
userMapper.update(user);
testFindAll();
}

@Test
public void delete() {
userMapper.delete(3L);
testFindAll();
}
}

summary

以上是常用CRUD操作的Mybatis注解版实现,对于基本的操作,使用注解确实比传统的XML简单好多,虽然也是SQL写在注解中,但是感觉比JPA的方式要简便一些(个人理解)。

XML版

使用Mybatis的XML开发方式应该是我们比较熟悉的,和注解版最大的不同就是Dao层,XML版会自动根据Dao层接口的方法名自动映射到XML中同名id对应的SQL。

修改application.yml

添加如下Mybatis配置属性

1
2
3
4
5
6
7
8
9
#mybatis配置
mybatis:
mapper-locations: classpath:mapper/**/*.xml
type-aliases-package: cn.tycoding.entity
configuration:
# 使用jdbc的getGeneratedKeys 可以获取数据库自增主键值
use-generated-keys: true
# 开启驼峰命名转换,如:Table(create_time) -> Entity(createTime)。不需要我们关心怎么进行字段匹配,mybatis会自动识别`大写字母与下划线`
map-underscore-to-camel-case: true

CRUD

创建interface UserMapperXML.java

1
2
3
4
5
6
7
8
9
10
11
12
public interface UserMapperXML {

List<User> findAll();

User findById(Long id);

void save(User user);

void update(User user);

void delete(Long id);
}

resources/下创建/mapper/UserMapperXML.xml

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
<?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="cn.tycoding.mapper.UserMapperXML">

<select id="findAll" resultType="cn.tycoding.entity.User">
select * from user
</select>

<select id="findById" resultType="cn.tycoding.entity.User">
select * from user where id = #{id}
</select>

<insert id="save" parameterType="cn.tycoding.entity.User">
insert into user(username,password,create_time) values(#{username},#{password},#{createTime}
</insert>

<update id="update" parameterType="cn.tycoding.entity.User">
update user set username=#{username},password=#{password} where id=#{id}
</update>

<delete id="delete" parameterType="long">
delete from user where id=#{id}
</delete>

</mapper>

测试

创建测试类UserMapperXMLTest.java

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
@SpringBootTest
@RunWith(SpringRunner.class)
public class UserMapperXMLTest {
private Logger logger = LoggerFactory.getLogger(this.getClass());

@Autowired
private UserMapperXML userMapperXML;

@Test
public void testFindAll() {
List<User> list = userMapperXML.findAll();
list.forEach(user -> {
logger.info("user={}", user);
});
}

@Test
public void testFindById(){
logger.info("user={}", userMapperXML.findById(1L));
}

@Test
public void testSave(){
User user = new User();
user.setUsername("测试");
user.setPassword("123");
user.setCreateTime(new Date());
userMapperXML.save(user);
testFindAll();
}

@Test
public void testUpdate() {
User user = new User();
user.setId(4L);
user.setUsername("测试呀");
userMapperXML.update(user);
testFindAll();
}

@Test
public void delete() {
userMapperXML.delete(3L);
testFindAll();
}
}

小结

练习了Mybatis注解版和XML版开发模式,更觉得两者配合使用最好,

简单的CRUD操作使用注解完全可以实现;

复杂的查询,比如Mybatis的动态SQL特性在注解中应该很难体现,而在XML中就很容易实现了。

Guess you like

Origin www.cnblogs.com/zfyer/p/12341268.html