SpringBoot整合mybatis的两种方法
1.全注解方式
1.1添加依赖
在pom.xml中添加如下依赖:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
1.2配置数据源
在application.yml中添加数据源啊:
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/samp_db?useUnicode=true&characterEncoding=utf8
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
1.3添加实体类
package com.dylan.springdemo.entity;
/**
* Created with IDEA
* User: wangcheng
* Date:2019/6/26
* Time:下午3:34
*/
public class Student {
/**
* 姓名
*/
private String name;
/**
* 学号
*/
private String id;
/**
* 分数
*/
private String score;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String age) {
this.id = id;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
}
1.4创建映射类
使用mapper注解
/**
* Created with IDEA
* User: wangcheng
* Date:2019/6/26
* Time:下午3:37
*/
@Mapper
public interface UserInfo {
@Select("select * from t_usr_pinf where id='2' ")
Student query();
}
1.5使用
@Autowired
private UserInfo userInfo;
@RequestMapping("/ParkingSet")
private ParkingSetRspBO getParkingSet(@RequestBody ParkingSetReqBO parkingSetReqBO) {
Student student=userInfo.query();
System.out.println(student.getName());
}
2使用DAO+mapper
2.1 添加依赖
#指定mybatis映射文件的地址
mybatis:
mapper-locations: classpath:mapper/*.xml
2.2 dao
package com.dylan.springdemo.dao;
import com.dylan.springdemo.entity.Student;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
/**
* Created with IDEA
* User: wangcheng
* Date:2019/6/26
* Time:下午3:37
*/
@Mapper
public interface UserInfo1 {
Student query();
}
2.3 mapper
在resource下创建mapper目录,创建mapper(与DAO同名):
<?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.dylan.springdemo.dao.UserInfo1"><select id="query" resultType="com.dylan.springdemo.entity.Student" >
select * from t_usr_pinf where id='2'
</select>
</mapper>
3. 使用@MapperScan
相比于@mapper需要在每个mapper类添加注解,使用@MapperScan可以指定要扫描的mapper类所在包路径:
package com.dylan.springdemo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@MapperScan(basePackages="com.dylan.springdemo.dao")
public class SpringdemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringdemoApplication.class, args);
}
@Bean
RestTemplate restTemplate(){
return new RestTemplate();
}
}