springboot使用Mybatis(xml和注解)過(guò)程全解析
剛畢業(yè)的第一份工作是 java 開(kāi)發(fā),項(xiàng)目中需要用到 mybatis,特此記錄學(xué)習(xí)過(guò)程,這只是一個(gè)簡(jiǎn)單 demo,mybatis 用法很多不可能全部寫(xiě)出來(lái),有更復(fù)雜的需求建議查看 mybatis 的官方中文文檔,點(diǎn)擊跳轉(zhuǎn)。下面時(shí)項(xiàng)目環(huán)境/版本。
•開(kāi)發(fā)工具:IDEA
•jdk 版本:1.8
•springboot 版本:2.03
其他依賴版本見(jiàn)下面 pom.xml:
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>mybatis-test</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>mybatis-test</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <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> <!--mybatis依賴 --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <!--alibaba連接池依賴--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.9</version> </dependency> <!--分頁(yè)依賴--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.5</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
1.創(chuàng)建項(xiàng)目
使用 idea 中的 spring initializr 生成 maven 項(xiàng)目,項(xiàng)目命令為 mybatis-test,選擇 web,mysql,mybatis 依賴,即可成功。(詳細(xì)過(guò)程不贅述,如有需要學(xué)習(xí) springboot 創(chuàng)建過(guò)程,可參考這篇文章。
然后依照上面的 pom 文件,補(bǔ)齊缺少的依賴。接著創(chuàng)建包 entity,service 和 mybatis 映射文件夾 mapper,創(chuàng)建。為了方便配置將 application.properties 改成 application.yml。由于我們時(shí) REST 接口,故不需要 static 和 templates 目錄。修改完畢后的項(xiàng)目結(jié)構(gòu)如下:
項(xiàng)目結(jié)構(gòu)
修改啟動(dòng)類(lèi),增加@MapperScan("com.example.mybatistest.dao"),以自動(dòng)掃描 dao 目錄,避免每個(gè) dao 都手動(dòng)加@Mapper注解。代碼如下:
@SpringBootApplication @MapperScan("com.example.mybatistest.dao") public class MybatisTestApplication { public static void main(String[] args) { SpringApplication.run(MybatisTestApplication.class, args); } }
修改 application.yml,配置項(xiàng)目,代碼如下:
mybatis: #對(duì)應(yīng)實(shí)體類(lèi)路徑 type-aliases-package: com.example.mybatistest.entity #對(duì)應(yīng)mapper映射文件路徑 mapper-locations: classpath:mapper/*.xml #pagehelper物理分頁(yè)配置 pagehelper: helper-dialect: mysql reasonable: true support-methods-arguments: true params: count=countSql returnPageInfo: check server: port: 8081 spring: datasource: name: mysqlTest type: com.alibaba.druid.pool.DruidDataSource #druid連接池相關(guān)配置 druid: #監(jiān)控?cái)r截統(tǒng)計(jì)的filters filters: stat driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true username: root password: 123456 #配置初始化大小,最小,最大 initial-size: 1 min-idle: 1 max-active: 20 #獲取連接等待超時(shí)時(shí)間 max-wait: 6000 #間隔多久檢測(cè)一次需要關(guān)閉的空閑連接 time-between-eviction-runs-millis: 60000 #一個(gè)連接在池中的最小生存時(shí)間 min-evictable-idle-time-millis: 300000 #打開(kāi)PSCache,并指定每個(gè)連接上PSCache的大小。oracle設(shè)置為true,mysql設(shè)置為false。分庫(kù)分表設(shè)置較多推薦設(shè)置 pool-prepared-statements: false max-pool-prepared-statement-per-connection-size: 20 http: encoding: charset: utf-8 enabled: true
2.編寫(xiě)代碼
首先創(chuàng)建數(shù)據(jù)表,sql 語(yǔ)句如下:
CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `age` tinyint(4) NOT NULL DEFAULT '0', `password` varchar(255) NOT NULL DEFAULT '123456', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
然后在 entity 包中創(chuàng)建實(shí)體類(lèi) User.java
public class User { private int id; private String name; private int age; private String password; public User(int id, String name, int age, String password) { this.id = id; this.name = name; this.age = age; this.password = password; } public User(){} //getter setter自行添加 }
在 dao 包下創(chuàng)建 UserDao.java
public interface UserDao { //插入用戶 int insert(User user); //根據(jù)id查詢 User selectById(String id); //查詢所有 List<User> selectAll(); }
在 mapper 文件夾下創(chuàng)建 UserMapper.xml,具體的 xml 編寫(xiě)方法查看文首的官方文檔。
<?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.example.mybatistest.dao.UserDao"> <sql id="BASE_TABLE"> user </sql> <sql id="BASE_COLUMN"> id,name,age,password </sql> <insert id="insert" parameterType="com.example.mybatistest.entity.User" useGeneratedKeys="true" keyProperty="id"> INSERT INTO <include refid="BASE_TABLE"/> <trim prefix="(" suffix=")" suffixOverrides=","> name,password, <if test="age!=null"> age </if> </trim> <trim prefix=" VALUE(" suffix=")" suffixOverrides=","> #{name,jdbcType=VARCHAR},#{password}, <if test="age!=null"> #{age} </if> </trim> </insert> <select id="selectById" resultType="com.example.mybatistest.entity.User"> select <include refid="BASE_COLUMN"/> from <include refid="BASE_TABLE"/> where id=#{id} </select> <select id="selectAll" resultType="com.example.mybatistest.entity.User"> select <include refid="BASE_COLUMN"/> from <include refid="BASE_TABLE"/> </select> </mapper>
至此使用 mybatis 的代碼編寫(xiě)完了,之后要用時(shí)調(diào)用 dao 接口中的方法即可。
3.測(cè)試
我們通過(guò)編寫(xiě) service,controller 然后使用 postman 進(jìn)行測(cè)試。
首先編寫(xiě) UserService.java,代碼如下:
@Component public class UserService { @Autowired private UserDao userDao; public User getByUserId(String id){ return userDao.selectById(id); } //獲取全部用戶 public List<User> getAll(){ return userDao.selectAll(); } //測(cè)試分頁(yè) public PageInfo<User> getAll(int pageNum,int pageSize){ PageHelper.startPage(pageNum,pageSize); List<User> users = userDao.selectAll(); System.out.println(users.size()); PageInfo<User> result = new PageInfo<>(users); return result; } public int insert(User user){ return userDao.insert(user); } }
編寫(xiě) UserController.java
@RestController public class UserController { @Autowired private UserService userService; @GetMapping("/user/{userId}") public User getUser(@PathVariable String userId){ return userService.getByUserId(userId); } @GetMapping("/user") public List<User> getAll(){ return userService.getAll(); } @GetMapping("/user/page/{pageNum}") public Object getPage(@PathVariable int pageNum, @RequestParam(name = "pageSize",required = false,defaultValue = "10") int pageSize){ return userService.getAll(pageNum,pageSize); } @PostMapping("/user") public Object addOne(User user){ userService.insert(user); return user; } }
啟動(dòng)項(xiàng)目,通過(guò) postman 進(jìn)行請(qǐng)求測(cè)試,測(cè)試結(jié)果如下:
•插入數(shù)據(jù):
•查詢數(shù)據(jù)
•分頁(yè)查詢
4.注解編寫(xiě) sql
上面使用的是 xml 方式編寫(xiě) sql 代碼,其實(shí) mybatis 也支持在注解中編寫(xiě) sql,這樣可以避免編寫(xiě)復(fù)雜的 xml 查詢文件,但同時(shí)也將 sql 語(yǔ)句耦合到了代碼中,也不易實(shí)現(xiàn)復(fù)雜查詢,因此多用于簡(jiǎn)單 sql 語(yǔ)句的編寫(xiě)。
要使用注解首先將 applicaton.yml 配置文件中的mapper-locations: classpath:mapper/*.xml注釋掉。然后在 UserDao.java 中加入 sql 注解,代碼如下:
public interface UserDao { //插入用戶 @Insert("insert into user(name,age,password) value(#{name},#{age},#{password})") @Options(useGeneratedKeys=true,keyColumn="id",keyProperty="id") int insert(User user); //根據(jù)id查詢 @Select("select * from user where id=#{id}") User selectById(String id); //查詢所有 @Select("select * from user") List<User> selectAll(); }
然后重新啟動(dòng)項(xiàng)目測(cè)試,測(cè)試結(jié)果跟上面完全一樣。
本文原創(chuàng)發(fā)布于:https://www.tapme.top/blog/detail/2018-09-01-10-38
源碼地址:https://github.com/FleyX/demo-project/tree/master/mybatis-test.
相關(guān)文章
設(shè)計(jì)模式系列之組合模式及其在JDK和MyBatis源碼中的運(yùn)用詳解
這篇文章主要介紹了組合模式及其在JDK和MyBatis源碼中的運(yùn)用,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-09-09java 實(shí)現(xiàn)websocket的兩種方式實(shí)例詳解
這篇文章主要介紹了java 實(shí)現(xiàn)websocket的兩種方式實(shí)例詳解,一種使用tomcat的websocket實(shí)現(xiàn),一種使用spring的websocket,本文通過(guò)代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2018-07-07只需兩步實(shí)現(xiàn)Eclipse+Maven快速構(gòu)建第一個(gè)Spring Boot項(xiàng)目
這篇文章主要介紹了只需兩步實(shí)現(xiàn)Eclipse+Maven快速構(gòu)建第一個(gè)Spring Boot項(xiàng)目,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-12-12SpringMVC跨服務(wù)器上傳文件中出現(xiàn)405錯(cuò)誤的解決
這篇文章主要介紹了SpringMVC跨服務(wù)器上傳文件中出現(xiàn)405錯(cuò)誤的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09java通過(guò)AES生成公鑰加密數(shù)據(jù)ECC加密公鑰
這篇文章主要為大家介紹了java通過(guò)AES生成公鑰加密數(shù)據(jù)ECC加密公鑰實(shí)現(xiàn)案例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12Spring?Data?Elasticsearch?5.x實(shí)現(xiàn)單詞糾錯(cuò)和自動(dòng)補(bǔ)全
這篇文章主要為大家介紹了Spring?Data?Elasticsearch?5.x實(shí)現(xiàn)單詞糾錯(cuò)和自動(dòng)補(bǔ)全示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08java實(shí)現(xiàn)定制數(shù)據(jù)透視表的示例詳解
數(shù)據(jù)透視表(Pivot?Table)是一種數(shù)據(jù)分析工具,通常用于對(duì)大量數(shù)據(jù)進(jìn)行匯總、分析和展示,本文主要介紹了如何使用Java將計(jì)算項(xiàng)添加到數(shù)據(jù)透視表中,感興趣的可以了解下2023-12-12詳解spring boot實(shí)現(xiàn)多數(shù)據(jù)源代碼實(shí)戰(zhàn)
本篇文章主要介紹了詳解spring boot實(shí)現(xiàn)多數(shù)據(jù)源代碼實(shí)戰(zhàn),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-07-07Java中常見(jiàn)的XML解析方法與應(yīng)用詳解
XML(eXtensible Markup Language)是一種用于存儲(chǔ)和傳輸數(shù)據(jù)的標(biāo)記語(yǔ)言,被廣泛應(yīng)用于表示和交換獨(dú)立于應(yīng)用程序和硬件平臺(tái)的結(jié)構(gòu)化信息,下面我們就來(lái)看看它的常見(jiàn)解析方法有哪些吧2024-01-01