目錄
一:ORM 操作 MySQL?
1. 創(chuàng)建 Spring Boot 項目
2. @MapperScan
3. mapper文件和java代碼分開管理
4. 事務支持
一:ORM 操作 MySQL?
使用MyBatis框架操作數(shù)據(jù), 在SpringBoot框架集成MyBatis,使用步驟:
(1)mybatis起步依賴 : 完成mybatis對象自動配置, 對象放在容器中
(2)pom.xml 指定把src/main/java目錄中的xml文件包含到classpath中
(3)創(chuàng)建實體類Student
(4)創(chuàng)建Dao接口 StudentDao , 創(chuàng)建一個查詢學生的方法
(5)創(chuàng)建Dao接口對應的Mapper文件, xml文件, 寫sql語句
(6)創(chuàng)建Service層對象, 創(chuàng)建StudentService接口和它的實現(xiàn)類。 去dao對象的方法,完成數(shù)據(jù)庫的操作
(7)創(chuàng)建Controller對象,訪問Service。
(8)寫application.properties文件,配置數(shù)據(jù)庫的連接信息。
1. 創(chuàng)建 Spring Boot 項目
(1)準備數(shù)據(jù)庫表
字段及其類型
?插入數(shù)據(jù)
?(2)創(chuàng)建一個SpringBoot項目
選擇Spring Web依賴
MybatisFramework依賴、MySQL Driver依賴
(3)生成的pom.xml配置和手動添加的resource插件配置
注:resource插件配置是表示將src/java/main下的或者說子包下的*.xml配置文件最終加載到target/classes目錄下。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.9</version>
<relativePath/>
</parent>
<groupId>com.zl</groupId>
<artifactId>study-springboot-mysql</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--web的起步依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mybatis的起步依賴-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.0</version>
</dependency>
<!--mysql驅動依賴-->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<!--測試-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<!--手動添加resources插件-->
<resources>
<resource>
<!--指定目錄-->
<directory>src/main/java</directory>
<!--指定目錄下的文件-->
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
<!--plugins插件-->
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
(4)實體類
準備一個實體類,類的屬性名與數(shù)據(jù)庫中的字段名保持一致。
package com.zl.pojo;
public class Student {
private Integer id;
private String name;
private Integer age;
public Student() {
}
public Student(Integer id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
(5)創(chuàng)建Dao接口
需要在類上加@Mapper注解:告訴MyBatis這是一個dao接口,創(chuàng)建此接口的代理對象。
package com.zl.dao;
import com.zl.pojo.Student;
import org.apache.ibatis.annotations.Mapper;
@Mapper //用來創(chuàng)建代理對象的
public interface StudentDao {
// 根據(jù)id進行查詢
Student selectById(@Param("stuId") Integer id);
}
(6)在Dao接口下創(chuàng)建一個同名的StudentDao.xml文件
注:前面我們配置的resource配置就是為這個StudentDao.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.zl.dao.StudentDao">
<!--編寫sql語句,id是這條sql語句的唯一表示-->
<select id="selectById" resultType="com.zl.pojo.Student">
select id,name,age from t_student where id = #{stuId}
</select>
</mapper>
(7)編寫Service接口和對應的實現(xiàn)類
StudentService接口
package com.zl.service;
import com.zl.pojo.Student;
public interface StudentService {
// 方法調用
Student queryStudent(Integer id);
}
StudentService接口實現(xiàn)類,編寫業(yè)務邏輯
package com.zl.service.impl;
import com.zl.dao.StudentDao;
import com.zl.pojo.Student;
import com.zl.service.StudentService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service // 交給Spring容器管理
public class StudentServiceImpl implements StudentService {
// 調用Dao
@Resource // 給屬性賦值
private StudentDao studentDao;
@Override
public Student queryStudent(Integer id) {
Student student = studentDao.selectById(id);
return student;
}
}
(8)創(chuàng)建controller去調用service
package com.zl.controller;
import com.zl.pojo.Student;
import com.zl.service.StudentService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
@Controller
public class StudentController {
@Resource
public StudentService studentService;
@RequestMapping("/student/query")
@ResponseBody
public String queryStudent(Integer id){
Student student = studentService.queryStudent(id);
return student.toString();
}
}
(9)連接數(shù)據(jù)庫,需要application.properties配置
useUnicode使用unicode編碼,characterEncoding字符集是utf-8,serverTimezone時區(qū)。
server.port=9090
server.servlet.context-path=/orm
#連接數(shù)據(jù)庫的配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123
(10)執(zhí)行結果
2. @MapperScan
如果有多個Dao接口,那么需要在每個Dao接口上都加入@Mapper注解,比較麻煩!
StudentDao接口
package com.zl.dao;
import com.zl.pojo.Student;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface StudentDao {
// 根據(jù)id進行查詢
Student selectById(Integer id);
}
UserDao接口
package com.zl.dao;
import com.zl.pojo.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserDao {
// 根據(jù)id進行查詢
SUser selectById(Integer id);
}
也可以在主類上(啟動類上)添加注解包掃@MapperScan("com.zl.dao")
注:basePackages是一個String數(shù)組,可以寫多個要掃描的包。
package com.zl;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(basePackages = "com.zl.dao")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
細節(jié):
如果我們導入一個項目,對于IDEA是不能識別resources的,圖標如下:
右擊鼠標----》Mark Directory as-----》?Resources Root即可
此時的圖標如下:?
3. mapper文件和java代碼分開管理
現(xiàn)在的xml文件和java代碼是放在同一個包下管理的!
?也可以分開存儲,把xml文件放到resources目錄下!在resources下創(chuàng)建一個mapper目錄,把所有的*.xml全都放進去;但是此時就找不到了,需要我們去配置指定。
?此時需要在application.properties文件里指定:
#指定mapper文件的位置
mybatis.mapper-locations=classpath:mapper/*.xml
注:此時低版本的Springboot可能出現(xiàn)application.properties文件沒有編譯到target/classes目錄的情況下,此時就需要修改resources插件配置:
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
要想看到SQL語句的信息,需要在application.properties中添加日志框架
#指定mybatis的日志,使用StdOutImpl輸出到控制臺
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
此時就可以看到SQL語句的日志信息
4. 事務支持
Spring框架中的事務:
(1)使用管理事務的對象: 事務管理器(接口, 接口有很多的實現(xiàn)類)
例:使用Jdbc或mybatis訪問數(shù)據(jù)庫,使用的事務管理器:DataSourceTransactionManager
(2)聲明式事務: 在xml配置文件或者使用注解說明事務控制的內容
控制事務: 隔離級別,傳播行為, 超時時間等
(3)事務處理方式:
①Spring框架中的@Transactional;
②aspectj框架可以在xml配置文件中,聲明事務控制的內容;
SpringBoot使用事務非常簡單,底層依然采用的是 Spring 本身提供的事務管理
①在業(yè)務方法的上面加入@Transactional , 加入注解后,方法有事務功能了。
②在主啟動類的上面 ,加入@EnableTransactionManager,開啟事務支持。
注:只加上@Transactional也能完成事務的功能,對于@EnableTransactionManager建議也加上。
第一步:創(chuàng)建一個SpringBoot項目,引入:Spring Web、MybatisFramework、MySQL Driver
第二步:使用mybatis逆向工程插件生成個pojo類、dao接口
①添加Mybatis逆向工程的插件
注:這個插件是需要MySQL驅動依賴的,如果這里沒有引入MySQL驅動的依賴,那么下面的generatorConfig.xml配置中就需要<classPathEntry>標簽去指定連接數(shù)據(jù)庫的JDBC驅動包所在位置,指定到你本機的完整路徑 ,例如:<classPathEntry location="E:\mysql-connector-java-5.1.38.jar"/>。
<!--mybatis逆向?程插件-->
<plugin>
<!--插件的GAV坐標-->
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.4.1</version>
<configuration>
<!--配置文件的位置,放在項目根目錄下必須指定一下-->
<!--<configurationFile>GeneratorMapper.xml</configurationFile>-->
<!--允許覆蓋-->
<overwrite>true</overwrite>
</configuration>
<!--插件的依賴-->
<dependencies>
<!--mysql驅動依賴-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.23</version>
</dependency>
</dependencies>
</plugin>
②編寫generatorConfig.xml配置文件
注:如果下面的generatorConfig.xml配置文件放到src的resources目錄下,那么配置文件的名字必須是generatorConfig.xml(不區(qū)分大小寫),并且不需要上面的<configurationFile>標簽去指定。
注:如果我們把generatorConfig.xml配置文件直接放到項目的根目錄下(和src同級目錄),那么此時generatorConfig.xml配置文件的名字隨意,但是必須使用上面的<configurationFile>標簽去指定一下(兩者保持一致即可)。
注:當然也可以不直接放到項目的根目錄下,例如:放到src/main目錄下,那么對于<configurationFile>標簽就需要指定src/main/generatorConfig.xml(兩者也要保持一致)
注:對于高版本的MySQL驅動,對于URL后面必須跟上時區(qū),但是在xml中是無法識別&,所以需要使用&去替換,例如:
connectionURL="jdbc:mysql://localhost:3306/springdb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8"
最終會生成*.xml配置,要想讓它最終編譯后放到target/classes中,就需要配置處理資源目錄
<!--處理資源目錄-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
?generatorConfig.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 指定連接數(shù)據(jù)庫的JDBC驅動包所在位置,如果前面插件中指定了,這里就不要指定了 -->
<!--<classPathEntry location="E:\mysql-connector-java-5.1.38.jar"/>-->
<!--
targetRuntime有兩個值:
MyBatis3Simple:生成的是基礎版,只有基本的增刪改查。
MyBatis3:生成的是增強版,除了基本的增刪改查之外還有復雜的增刪改查。
-->
<context id="DB2Tables" targetRuntime="MyBatis3Simple">
<!--防止生成重復代碼-->
<plugin type="org.mybatis.generator.plugins.UnmergeableXmlMappersPlugin"/>
<commentGenerator>
<!--是否去掉生成日期-->
<property name="suppressDate" value="true"/>
<!--是否去除注釋-->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--連接數(shù)據(jù)庫信息-->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/springboot"
userId="root"
password="123">
</jdbcConnection>
<!-- 生成pojo包名和位置 -->
<javaModelGenerator targetPackage="com.zl.pojo" targetProject="src/main/java">
<!--是否開啟子包-->
<property name="enableSubPackages" value="true"/>
<!--是否去除字段名的前后空白-->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成SQL映射文件的包名和位置 -->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
<!--是否開啟子包-->
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成Mapper接口的包名和位置 -->
<javaClientGenerator
type="xmlMapper"
targetPackage="com.zl.mapper"
targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 表名和對應的實體類名-->
<table tableName="t_Student" domainObjectName="Student"/>
</context>
</generatorConfiguration>
雙擊插件,執(zhí)行結果如下:
第三步:編寫application.properties配置
注:如果StudentMapper.xml的目錄與StudentMapper目錄保持一致,就不需要以下這個配置mybatis.mapper-locations=classpath:mapper/*.xml;這里我們是自己定義的mapper目錄,把mapper.xml文件放進去了,所以需要我們指定出來它的位置!
#設置端口
server.port=8082
#配置項目根路徑context-path
server.servlet.context-path=/myboot
#配置數(shù)據(jù)庫
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123
#配置mybatis
mybatis.mapper-locations=classpath:mapper/*.xml
#配置日志
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
第四步:編寫service接口和實現(xiàn)類
StudentService接口
package com.zl.service;
import com.zl.pojo.Student;
public interface StudentService {
int addStudent(Student student);
}
StudentService接口的實現(xiàn)類StudentServiceImpl
package com.zl.service.impl;
import com.zl.mapper.StudentMapper;
import com.zl.pojo.Student;
import com.zl.service.StudentService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
@Service // 交給Spring容器管理
public class StudentServiceImpl implements StudentService {
@Resource // 屬性賦值
private StudentMapper studentDao;
@Transactional // 事務控制
@Override
public int addStudent(Student student) {
System.out.println("準備執(zhí)行sql語句");
int count = studentDao.insert(student);
System.out.println("已完成sql語句的執(zhí)行");
// 模擬異常,回滾事務
int sum = 10 / 0;
return count;
}
}
第五步:編寫controller類去調用service
package com.zl.controller;
import com.zl.pojo.Student;
import com.zl.service.StudentService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
@Controller
public class StudentController {
@Resource
private StudentService studentService;
@RequestMapping("/addStudent")
@ResponseBody
public String addStudent(String name,Integer age){
Student s = new Student();
s.setName(name);
s.setAge(age);
int count = studentService.addStudent(s);
return "添加的Student個數(shù)是:"+count;
}
}
第六步:在啟動類上面加上包掃描注解和啟動事務管理器注解
package com.zl;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication
@MapperScan(basePackages = "com.zl.mapper") // 添加包掃描
@EnableTransactionManagement // 啟動事務管理器
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
第七步:進行測試
有異常發(fā)生,會回滾事務,無法插入數(shù)據(jù)
?無異常發(fā)生,正常插入數(shù)據(jù)文章來源:http://www.zghlxwxcb.cn/news/detail-634821.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-634821.html
到了這里,關于【SpringBoot】| ORM 操作 MySQL(集成MyBatis)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!