在上一篇的内容中,我对JPA的使用进行了介绍,JPA非常的简单易用,开发速度也非常的快。但是在使用到JPA之前,我一直使用的Mybatis,所以就学习了怎么在SpringBoot中使用Mybatis。在SpringBoot中有两种方式,一种是无配置注解版,一种是极简XML版。下面会将两个版本放出。
一丶无配置注解版
1.pom.xml
<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
上面是要导入的Maven依赖
2.配置application.yml
server:
port: 8081 //端口号
spring:
datasource: //数据库连接配置
url: jdbc:mysql://localhost:3306/girl
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
mybatis:
type-aliases-package: com.springboot.study.entity //实体类所在的位置
springboot会自动加载spring.datasource.*相关配置,数据源就会自动注入到sqlSessionFactory中,sqlSessionFactory会自动注入到Mapper中,对了你一切都不用管了,直接拿起来使用就行了。
3.在启动类中添加对mapper包扫描@MapperScan
package com.springboot.study;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.springboot.study.mapper")
public class SpringBootMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootMybatisApplication.class, args);
}
}
4.编写mapper
GirlMapper.java
package com.springboot.study.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.springboot.study.entity.Girl;
public interface GirlMapper {
@Select("select * from girl") //@Select 查询的关键字
@Results({//结果集与返回的实体类对应
@Result(property="id",column="id"),
@Result(property="age",column="age"),
@Result(property="cupSize",column="cup_size"),
})
public List<Girl> findAllGirls();
@Select("select * from girl where id=#{id}")
@Results({
@Result(property="id",column="id"),
@Result(property="age",column="age"),
@Result(property="cupSize",column="cup_size")
})
public Girl findById(Integer id);
//使用增删改的时候,方法返回int就会自动返回受影响的行数
@Insert("insert into girl values(#{id},#{age},#{cupSize})")//@Insert插入的注解public int addGirl(Girl girl);@Delete("delete from girl where id=#{id}")//@Delete删除的注解public int deleteGirl(Integer id);@Update("update girl set age=#{age},cup_size=#{cupSize} where id=#{id}")//@Update更新的注解public int updateGirl(Girl girl);}
在注入参数的时候可以使用#和$,这两个符号的作用是不同的,具体的表现形式如下:
// #会按照参数去注入 select * from teacher where name = ?;
@Select("Select * from teacher where name = #{name}")
Teacher selectTeachForGivenName(@Param("name") String name);
// $会加上引号 select * from teacher where name = 'someName';
@Select("Select * from teacher where name = '${name}'")
Teacher selectTeachForGivenName(@Param("name") String name);
然后在Controller中调用访问就行了
GirlController.java
package com.springboot.study.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.springboot.study.entity.Girl;
import com.springboot.study.mapper.GirlMapper;
@RestController
public class GirlController {
@Autowired
GirlMapper girlMapper;
@RequestMapping("/girls")
public List<Girl> getAll(){
return girlMapper.findAllGirls();
}
@RequestMapping("/girl")
public Girl findGirls(Integer id){
return girlMapper.findById(id);
}
@RequestMapping("/addGirl")
public int addGirl(){
return girlMapper.addGirl(new Girl(0,15,"a"));
}
@RequestMapping("/delGirl")
public int deleteGirl(Integer id){
return girlMapper.deleteGirl(id);
}
@RequestMapping("/uptGirl")
public int uptGirl(Integer id,Integer age,String cupSize){
return girlMapper.updateGirl(new Girl(id,age,cupSize));
}
}
现在就可以按照Controller的需求去访问了!
二、极简XML版
1.配置
pom文件和上个版本的一样,需要在application.yml中增添以下配置:
mybatis:
config-location: classpath:mybatis-config.xml
mapper-locations: classpath:mappers/*.xml
type-aliases-package: com.springboot.study.entity
指定了mybatis基础配置文件的位置,和实体类映射文件的地址
mybatis-config.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>
<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>
这里也可以添加一些mybatis基础的配置。
2.添加Girl的映射文件
Girl.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.springboot.study.dao.GirlMapper">
<select id="findAll" resultType="girl">
select id,age,cup_size cupSize from girl
</select>
<select id="findGirlById" parameterType="int" resultType="girl">
select * from girl where id=#{id}
</select>
<insert id="addGirl" parameterType="girl" >
insert into girl values(#{id},#{age},#{cupSize})
</insert>
<update id="uptGirl" parameterType="girl">
update girl set age=#{age},cup_size=#{cupSize} where id=#{id}
</update>
<delete id="delGirl" parameterType="int">
delete from girl where id=#{id}
</delete>
</mapper>
3.编写Dao层的代码
GirlMapper.java
package com.springboot.study.dao;
import java.util.List;
import com.springboot.study.entity.Girl;
public interface GirlMapper {
public List<Girl> findAll();
public Girl findGirlById(Integer id);
public int addGirl(Girl girl);
public int uptGirl(Girl girl);
public int delGirl(Integer id);
}
在使用上,基本上就和上个版本一样,只不过在Dao层只有接口方法了。
三、如何选择这两个版本
1.注解版适合简单快速的模式,现在流行的微服务模式一般是一个微服务对应一个自己的数据库,到时候多表查询的需求就会变少,这种模式会越来越吃香。
2.XML模式比较适合传统大项目,可以灵活动态的生成SQL,SQL的使用会更方便。