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 MapperScannerConfigurer
the 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 @Mapper
comment
Second way: in Application.java
added before the start of class @MapperScan("mapper所在的包名")
notes
CRUD follows:
Creating Entity /entity/User.java
public interface UserMapperAno { |
Wherein the @Result
annotation 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 |
|
summary
以上是常用CRUD操作的Mybatis注解版实现,对于基本的操作,使用注解确实比传统的XML简单好多,虽然也是SQL写在注解中,但是感觉比JPA的方式要简便一些(个人理解)。
XML版
使用Mybatis的XML开发方式应该是我们比较熟悉的,和注解版最大的不同就是Dao层,XML版会自动根据Dao层接口的方法名自动映射到XML中同名id
对应的SQL。
修改application.yml
添加如下Mybatis配置属性
1 |
#mybatis配置 |
CRUD
创建interface UserMapperXML.java
1 |
public interface UserMapperXML { |
在resources/
下创建/mapper/UserMapperXML.xml
1 |
|
测试
创建测试类UserMapperXMLTest.java
1 |
|
小结
练习了Mybatis注解版和XML版开发模式,更觉得两者配合使用最好,
简单的CRUD操作使用注解完全可以实现;
复杂的查询,比如Mybatis的动态SQL特性在注解中应该很难体现,而在XML中就很容易实现了。