手把手教你SpringBoot整合Mybatis
Mybatis的簡(jiǎn)單介紹
? MyBatis 本是apache的一個(gè)開(kāi)源項(xiàng)目iBatis, 2010年這個(gè)項(xiàng)目由apache software foundation 遷移到了google code,并且改名為MyBatis 。2013年11月遷移到Github。
? iBATIS一詞來(lái)源于“internet”和“abatis”的組合,是一個(gè)基于Java的持久層框架。iBATIS提供的持久層框架包括SQL Maps和Data Access Objects(DAOs)
? MyBatis 是一款優(yōu)秀的持久層框架,它支持定制化 SQL、存儲(chǔ)過(guò)程以及高級(jí)映射。MyBatis 避免了幾乎所有的 JDBC 代碼和手動(dòng)設(shè)置參數(shù)以及獲取結(jié)果集。MyBatis 可以使用簡(jiǎn)單的 XML 或注解來(lái)配置和映射原生信息,將接口和 Java 的 POJOs(Plain Ordinary Java Object,普通的 Java對(duì)象)映射成數(shù)據(jù)庫(kù)中的記錄。
? 思想:ORM:Object Relational Mapping
? Mybatis基本框架:

1 環(huán)境搭建
新建Spring Boot項(xiàng)目,引入依賴
pom.xml
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!--Druid數(shù)據(jù)源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
<!--測(cè)試-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
DB-sql
CREATE TABLE `student` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, `age` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;
項(xiàng)目結(jié)構(gòu)

2 整合方式一:注解版
2.1 配置
server:
port: 8081
spring:
datasource: # 配置數(shù)據(jù)庫(kù)
username: root
password: 12345
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test #數(shù)據(jù)庫(kù)名
type: com.alibaba.druid.pool.DruidDataSource
2.2 編碼
/**
* 注解版
*/
@Mapper
@Repository
public interface JavaStudentMapper {
/**
* 添加一個(gè)學(xué)生
*
* @param student
* @return
*/
@Insert("insert into student(name, age) " +
"values (#{name}, #{age})")
public int saveStudent(Student student);
/**
* 根據(jù)ID查看一名學(xué)生
*
* @param id
* @return
*/
@Select("select * " +
"from student " +
"where id = #{id}")
public Student findStudentById(Integer id);
/**
* 查詢?nèi)繉W(xué)生
*
* @return
*/
@Select("select * " +
"from student")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "name", column = "name"),
@Result(property = "age", column = "age")
})
public List<Student> findAllStudent();
/**
* 根據(jù)ID刪除一個(gè)
*
* @param id
* @return
*/
@Delete("delete " +
"from student " +
"where id = #{id}")
public int removeStudentById(Integer id);
/**
* 根據(jù)ID修改
*
* @param student
* @return
*/
@Update("update set name=#{name},age=#{age} " +
"where id=#{id}")
public int updateStudentById(Student student);
}
2.3 測(cè)試
@Autowired
private JavaStudentMapper studentMapper;
@Test
void testJavaMapperInsert() {
Student student = new Student("張三", 22);
System.out.println(studentMapper.saveStudent(student));
}
@Test
void testJavaMapperFind() {
System.out.println(studentMapper.findStudentById(2));
}
@Test
void testJavaMapperFindAll() {
System.out.println(studentMapper.findAllStudent());
}
@Test
void testJavaMapperUpdate() {
Student student = new Student(2, "張三", 22);
System.out.println(studentMapper.updateStudentById(student));
}
@Test
void testJavaMapperDelete() {
System.out.println(studentMapper.removeStudentById(2));
}
3 整合方式二:XML版
3.1 配置
server:
port: 8081
spring:
application:
name: hospitalManager #項(xiàng)目名
datasource: # 配置數(shù)據(jù)庫(kù)
username: root
password: 12345
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test #數(shù)據(jù)庫(kù)名
type: com.alibaba.druid.pool.DruidDataSource
mybatis:
mapper-locations: classpath:mapper/*Mapper.xml #掃描resources下的mapper文件夾下的xml文件
type-aliases-package: org.ymx.sp_mybatis.pojo #實(shí)體類所在包,定義別名
主啟動(dòng)類:
@SpringBootApplication
@MapperScan("org.ymx.sp_mybatis.xmlMapper") //掃描的mapper
public class SpMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpMybatisApplication.class, args);
}
}
3.2 編碼
/**
* xml版
*/
@Mapper
@Repository
public interface XmlStudentMapper {
/**
* 添加一個(gè)學(xué)生
*
* @param student
* @return
*/
public int saveStudent(Student student);
/**
* 根據(jù)ID查看一名學(xué)生
*
* @param id
* @return
*/
public Student findStudentById(Integer id);
/**
* 查詢?nèi)繉W(xué)生
*
* @return
*/
public List<Student> findAllStudent();
/**
* 根據(jù)ID刪除一個(gè)
*
* @param id
* @return
*/
public int removeStudentById(Integer id);
/**
* 根據(jù)ID修改
*
* @param student
* @return
*/
public int updateStudentById(Student student);
}
xml文件(StudentMapper.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="org.ymx.sp_mybatis.dao.xmlMapper.XmlStudentMapper">
<!-- 添加學(xué)生-->
<insert id="saveStudent" parameterType="org.ymx.sp_mybatis.pojo.Student" useGeneratedKeys="true"
keyProperty="id">
insert into student(name, age)
values (#{name}, #{age})
</insert>
<!--查看學(xué)生根據(jù)ID-->
<select id="findStudentById" parameterType="integer" resultType="org.ymx.sp_mybatis.pojo.Student">
select *
from student
where id = #{id}
</select>
<!--查看全部學(xué)生-->
<select id="findAllStudent" resultMap="studentResult">
select *
from student
</select>
<!--刪除學(xué)生根據(jù)ID-->
<delete id="removeStudentById" parameterType="integer">
delete
from student
where id = #{id}
</delete>
<!--修改學(xué)生根據(jù)ID-->
<update id="updateStudentById" parameterType="org.ymx.sp_mybatis.pojo.Student">
update student
set name=#{name},
age=#{age}
where id = #{id}
</update>
<!--查詢結(jié)果集-->
<resultMap id="studentResult" type="org.ymx.sp_mybatis.pojo.Student">
<result column="id" javaType="INTEGER" jdbcType="INTEGER" property="id"/>
<result column="name" javaType="STRING" jdbcType="VARCHAR" property="name"/>
<result column="age" javaType="INTEGER" jdbcType="INTEGER" property="age"/>
</resultMap>
</mapper>
3.3 測(cè)試
@Autowired
private XmlStudentMapper studentMapper;
@Test
void testJavaMapperInsert() {
Student student = new Student("張三", 22);
System.out.println(studentMapper.saveStudent(student));
}
@Test
void testJavaMapperFind() {
System.out.println(studentMapper.findStudentById(2));
}
@Test
void testJavaMapperFindAll() {
System.out.println(studentMapper.findAllStudent());
}
@Test
void testJavaMapperUpdate() {
Student student = new Student(2, "張三", 22);
System.out.println(studentMapper.updateStudentById(student));
}
@Test
void testJavaMapperDelete() {
System.out.println(studentMapper.removeStudentById(2));
}
4 總結(jié)
基本步驟:

注意事項(xiàng):
(1)相比注解方式,更推薦使用xml方式,因?yàn)樽⒔夥绞綄QL語(yǔ)句嵌套到Java代碼中,一旦需要修改則需要重新編譯項(xiàng)目,而xml方式則不需要重新編譯項(xiàng)目
(2)xml方式需要在主啟動(dòng)函數(shù)或配置類中配置接口的掃描路徑
到此這篇關(guān)于手把手教你SpringBoot整合Mybatis的文章就介紹到這了,更多相關(guān)SpringBoot整合Mybatis內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
IDEA中WebService生成Java代碼并調(diào)用外部接口實(shí)現(xiàn)代碼
這篇文章主要介紹了IDEA中WebService生成Java代碼并調(diào)用外部接口實(shí)現(xiàn),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-05-05
Spring?Data?JPA框架快速入門(mén)之自定義Repository接口
Spring?Data?JPA是Spring基于JPA規(guī)范的基礎(chǔ)上封裝的?套?JPA?應(yīng)?框架,可使開(kāi)發(fā)者?極簡(jiǎn)的代碼即可實(shí)現(xiàn)對(duì)數(shù)據(jù)庫(kù)的訪問(wèn)和操作,本篇我們來(lái)了解Spring?Data?JPA框架的自定義Repository接口2022-04-04
Spring?Boot集成etcd的詳細(xì)過(guò)程
etcd是一個(gè)分布式鍵值存儲(chǔ)數(shù)據(jù)庫(kù),用于共享配置和服務(wù)發(fā)現(xiàn),etcd采用Go語(yǔ)言編寫(xiě),具有出色的跨平臺(tái)支持,很小的二進(jìn)制文件和強(qiáng)大的社區(qū),這篇文章主要介紹了SpringBoot集成etcd,需要的朋友可以參考下2023-08-08
SpringBoot?自定義注解實(shí)現(xiàn)涉密字段脫敏
關(guān)于數(shù)據(jù)脫敏,網(wǎng)上的文章都是硬編碼規(guī)則,比如對(duì)身份證,手機(jī)號(hào),郵件地址等固定寫(xiě)法脫敏。本文在此基礎(chǔ)上,拓展動(dòng)態(tài)從數(shù)據(jù)庫(kù)查出涉密關(guān)鍵字執(zhí)行脫敏操作。感興趣的同學(xué)可以參考閱讀2023-03-03
java中Spring Security的實(shí)例詳解
這篇文章主要介紹了java中Spring Security的實(shí)例詳解的相關(guān)資料,spring security是一個(gè)多方面的安全認(rèn)證框架,提供了基于JavaEE規(guī)范的完整的安全認(rèn)證解決方案,需要的朋友可以參考下2017-09-09
基于spring boot實(shí)現(xiàn)一個(gè)全局異常處理器
在項(xiàng)目開(kāi)發(fā)中,我們可以基于spring boot提供的切面特性,來(lái)很輕松的實(shí)現(xiàn)全局異常的處理,所以本文主要為大家介紹了如何基于spring boot實(shí)現(xiàn)一個(gè)全局異常處理器,有需要的可以參考下2023-09-09
淺談springboot項(xiàng)目中定時(shí)任務(wù)如何優(yōu)雅退出
這篇文章主要介紹了淺談springboot項(xiàng)目中定時(shí)任務(wù)如何優(yōu)雅退出?具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-09-09

