1、前言
Orm 框架的本质是简化编程中操作数据库的编码,发展到现在基本上就剩两家了,一个是宣称可以不用写一句 Sql 的 Hibernate,一个是可以灵活调试动态 Sql 的 Mybatis ,两者各有特点,在企业级系统开发中可以根据需求灵活使用。发现一个有趣的现象:传统企业大都喜欢使用 Hibernate ,互联网行业通常使用 Mybatis 。
Hibernate: 特点就是所有的 Sql 都用 Java 代码来生成,不用跳出程序去写(看) Sql ,有着编程的完整性,发展到最顶端就是 Spring Data Jpa 这种模式了
Mybatis: 初期使用比较麻烦,需要各种配置文件、实体类、Dao 层映射关联、还有一大推其它配置。当然 Mybatis 也发现了这种弊端,初期开发了generator可以根据表结果自动生产实体类、配置文件和 Dao 层代码,可以减轻一部分开发量;后期也进行了大量的优化可以使用注解了,自动管理 Dao 层和配置文件等,发展到最顶端就是今天要讲的这种模式了,mybatis-spring-boot-starter 就是 Spring Boot+ Mybatis 可以完全注解不用配置文件,也可以简单配置轻松上手。
官网链接:
http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/index.html
2、注解方式
Mybatis 看 Spring Boot 这么火热也开发出一套解决方案来凑凑热闹,但这一凑确实解决了很多问题,使用起来确实顺畅了许多。mybatis-spring-boot-starter主要有两种解决方案,一种是使用注解解决一切问题,一种是简化后的老传统。
当然任何模式都需要首先引入mybatis-spring-boot-starter的 Pom 文件,现在最新版本是 2.2.2
2.1 添加相关 Maven 文件依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
2.2 编写application.yml文件
mybatis:
type-aliases-package: com.ncl.test.entity
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
password: 123456
username: root
driver-class-name: com.mysql.cj.jdbc.Driver
Spring Boot 会自动加载 spring.datasource.* 相关配置,数据源就会自动注入到 sqlSessionFactory 中,sqlSessionFactory 会自动注入到 Mapper 中,对了,你一切都不用管了,直接拿起来使用就行了。在启动类中添加对 mapper 包扫描@MapperScan
2.3 启动类 TestApplication 文件
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.ncl.test.mapper")
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
2.4 实体类编写
这是我的数据库表结构:
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserEntity {
private Long id;
private Long age;
private String username;
private String password;
private String sex;
}
2.5 Mapper映射文件的编写
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface UserMapper {
@Select("SELECT * FROM user")
@Results({
@Result(property = "sex", column = "sex"),
@Result(property = "id", column = "id"),
@Result(property = "age", column = "age"),
@Result(property = "username", column = "username"),
@Result(property = "password", column = "password")
})
List<UserEntity> getAll();
@Select("SELECT * FROM user WHERE id = #{id}")
@Results({
@Result(property = "sex", column = "sex"),
@Result(property = "id", column = "id"),
@Result(property = "age", column = "age"),
@Result(property = "username", column = "username"),
@Result(property = "password", column = "password")
})
UserEntity getOne(Long id);
@Insert("INSERT INTO user(age,username,password) VALUES(#{age}, #{username}, #{password})")
void insert(UserEntity user);
@Update("UPDATE user SET age=#{age},username=#{username},password=#{password} WHERE id =#{id}")
void update(UserEntity user);
@Delete("DELETE FROM user WHERE id =#{id}")
void delete(Long id);
}
- @Select 是查询类的注解,所有的查询均使用这个
- @Result 修饰返回的结果集,关联实体类属性和数据库字段一一对应,如果实体类属性和数据库属性名保持一致,就不需要这个属性来修饰。
- @Insert 插入数据库使用,直接传入实体类会自动解析属性到对应的值
- @Update 负责修改,也可以直接传入对象
- @delete 负责删除
更多注解:https://mybatis.org/mybatis-3/zh/java-api.html
2.6 Controller文件的编写(省略了Service层)
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/{id}")
public UserEntity getUserById(@PathVariable("id")Long id){
UserEntity user = userMapper.getOne(id);
return user;
}
@GetMapping("")
public List<UserEntity> getAll(){
List<UserEntity> userEntities = userMapper.getAll();
return userEntities;
}
}
2.7 启动测试
启动TestApplication类,打开浏览器,在地址栏输入http://localhost:8080/user
在地址栏输入http://localhost:8080/user/1
3、极简 xml 版本
3.1 配置
pom 文件和上个版本一样,只是application.yml 变成了以下配置
mybatis:
type-aliases-package: com.ncl.test.entity
config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
password: 123456
username: root
driver-class-name: com.mysql.cj.jdbc.Driver
指定了 Mybatis 基础配置文件和实体类映射文件的地址
mybatis-config.xml 配置
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias alias="Integer" type="java.lang.Integer" />
<typeAlias alias="Long" type="java.lang.Long" />
<typeAlias alias="HashMap" type="java.util.HashMap" />
<typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
<typeAlias alias="ArrayList" type="java.util.ArrayList" />
<typeAlias alias="LinkedList" type="java.util.LinkedList" />
</typeAliases>
</configuration>
UserMapper.xml 配置
<?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.ncl.test.mapper.UserXMapper" >
<resultMap id="BaseResultMap" type="com.ncl.test.entity.UserEntity" >
<id column="id" property="id" jdbcType="BIGINT" />
<result column="username" property="username" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
<result column="sex" property="sex" jdbcType="VARCHAR"/>
<result column="age" property="age" jdbcType="VARCHAR" />
</resultMap>
<sql id="Base_Column_List" >
id, username, password, sex, age
</sql>
<select id="getAll" resultMap="BaseResultMap" >
SELECT
<include refid="Base_Column_List" />
FROM user
</select>
<select id="getOne" parameterType="java.lang.Long" resultMap="BaseResultMap" >
SELECT
<include refid="Base_Column_List" />
FROM user
WHERE id = #{id}
</select>
<insert id="insert" parameterType="com.ncl.test.entity.UserEntity" >
INSERT INTO
user
(username,password,sex)
VALUES
(#{username}, #{password}, #{sex})
</insert>
<update id="update" parameterType="com.ncl.test.entity.UserEntity" >
UPDATE
user
SET
<if test="username != null">username = #{username},</if>
<if test="password != null">password = #{password},</if>
<if test="age != null">age = #{age},</if>
sex = #{sex}
WHERE
id = #{id}
</update>
<delete id="delete" parameterType="java.lang.Long" >
DELETE FROM
user
WHERE
id =#{id}
</delete>
</mapper>
3.2 编写 Mapper 层的代码
package com.ncl.test.mapper;
import com.ncl.test.entity.UserEntity;
import java.util.List;
public interface UserMapperx {
List<UserEntity> getAll();
UserEntity getOne(Long id);
void insert(UserEntity user);
void update(UserEntity user);
void delete(Long id);
}
3.3 测试使用
类似与上面
4、总结
遗留问题:
- 笔者在编写application.properties 的时候会出现报错,但是更改成application.yml文件后就不报错了。
- 关于递归查询,一对一一对多查询等笔者害没完全摸透
欢迎感兴趣的朋友给笔者留言,评论,私信