SpringBoot 系列教程 Mybatis+註解整合篇
上一篇博文介紹了 SpringBoot 整合 mybatis 的過程,可是 xml 的方式,總感受讓人有點蛋疼;本文將介紹一種 noxml 的使用姿式,純用註解的方式來支持 CURDjava
<!-- more -->mysql
本文使用 SpringBoot 版本爲 2.2.1.RELEASE
, mybatis 版本爲1.3.2
,數據庫爲 mysql 5+git
推薦是用官方的教程來建立一個 SpringBoot 項目; 若是直接建立一個 maven 工程的話,將下面配置內容,拷貝到你的pom.xml
中github
mybatis-spring-boot-starter
,能夠減小使人窒息的配置<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.1.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.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies> <build> <pluginManagement> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </pluginManagement> </build> <repositories> <repository> <id>spring-snapshots</id> <name>Spring Snapshots</name> <url>https://repo.spring.io/libs-snapshot-local</url> <snapshots> <enabled>true</enabled> </snapshots> </repository> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/libs-milestone-local</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> <repository> <id>spring-releases</id> <name>Spring Releases</name> <url>https://repo.spring.io/libs-release-local</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories>
在 application.yml
配置文件中,加一下 db 的相關配置spring
spring: datasource: url: jdbc:mysql://127.0.0.1:3306/story?useUnicode=true&characterEncoding=UTF-8&useSSL=false username: root password:
接下來準備一個測試表(依然借用以前 db 操做系列博文中的表結構),用於後續的 CURD;表結果信息以下sql
DROP TABLE IF EXISTS `money`; CREATE TABLE `money` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(20) NOT NULL DEFAULT '' COMMENT '用戶名', `money` int(26) NOT NULL DEFAULT '0' COMMENT '有多少錢', `is_deleted` tinyint(1) NOT NULL DEFAULT '0', `create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '建立時間', `update_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新時間', PRIMARY KEY (`id`), KEY `name` (`name`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
在前一篇的基礎上進行擴展,重點在於幹掉了 xml 文件,在 DAO 接口上經過註解來實現 CURD數據庫
建立表對應的 PO 對象: MoneyPo
mybatis
@Data public class MoneyPo { private Integer id; private String name; private Long money; private Integer isDeleted; private Timestamp createAt; private Timestamp updateAt; }
表的操做接口,下面簡單的寫了四個接口,分別對應 CRUID 四種操做app
@Mapper public interface MoneyMapper { // 支持主鍵寫回到po @Options(useGeneratedKeys = true, keyProperty = "po.id", keyColumn = "id") @Insert("insert into money (name, money, is_deleted) values (#{po.name}, #{po.money}, #{po.isDeleted})") int savePo(@Param("po") MoneyPo po); @Select("select * from money where name=#{name}") @Results({@Result(property = "id", column = "id", id = true, jdbcType = JdbcType.INTEGER), @Result(property = "name", column = "name", jdbcType = JdbcType.VARCHAR), @Result(property = "money", column = "money", jdbcType = JdbcType.INTEGER), @Result(property = "isDeleted", column = "is_deleted", jdbcType = JdbcType.TINYINT), @Result(property = "createAt", column = "create_at", jdbcType = JdbcType.TIMESTAMP), @Result(property = "updateAt", column = "update_at", jdbcType = JdbcType.TIMESTAMP)}) List<MoneyPo> findByName(@Param("name") String name); @Update("update money set money=money+#{money} where id=#{id}") int addMoney(@Param("id") int id, @Param("money") int money); @Delete("delete from money where id = #{id,jdbcType=INTEGER}") int delPo(@Param("id") int id); @Select("<script> select * from money " + "<trim prefix=\"WHERE\" prefixOverrides=\"AND | OR\">" + " <if test=\"id != null\">" + " id = #{id}" + " </if>" + " <if test=\"name != null\">" + " AND name=#{name}" + " </if>" + " <if test=\"money != null\">" + " AND money=#{money}" + " </if>" + "</trim>" + "</script>") @Results({@Result(property = "id", column = "id", id = true, jdbcType = JdbcType.INTEGER), @Result(property = "name", column = "name", jdbcType = JdbcType.VARCHAR), @Result(property = "money", column = "money", jdbcType = JdbcType.INTEGER), @Result(property = "isDeleted", column = "is_deleted", jdbcType = JdbcType.TINYINT), @Result(property = "createAt", column = "create_at", jdbcType = JdbcType.TIMESTAMP), @Result(property = "updateAt", column = "update_at", jdbcType = JdbcType.TIMESTAMP)}) List<MoneyPo> findByPo(MoneyPo po); }
從 mapper 的實現上,也能夠看出來,經過 @Insert
, @Select
, @Update
, @Delete
四個註解來實現 CURD,使用上面這種方式時,有幾個點須要注意dom
@Options(useGeneratedKeys = true, keyProperty = "po.id", keyColumn = "id")
<script>
來包裝動態 sql<resultMap>
的映射關係接下來簡單測試一下上面的四個接口,看是否能夠正常工做
啓動類
@SpringBootApplication public class Application { public Application(MoneyRepository repository) { repository.testMapper(); } public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
測試類
@Repository public class MoneyRepository { @Autowired private MoneyMapper moneyMapper; private Random random = new Random(); public void testMapper() { MoneyPo po = new MoneyPo(); po.setName("mybatis noxml user"); po.setMoney((long) random.nextInt(12343)); po.setIsDeleted(0); moneyMapper.savePo(po); System.out.println("add record: " + po); moneyMapper.addMoney(po.getId(), 200); System.out.println("after update: " + moneyMapper.findByName(po.getName())); moneyMapper.delPo(po.getId()); System.out.println("after delete: " + moneyMapper.findByName(po.getName())); } }
輸出結果
盡信書則不如,以上內容,純屬一家之言,因我的能力有限,不免有疏漏和錯誤之處,如發現 bug 或者有更好的建議,歡迎批評指正,不吝感激
下面一灰灰的我的博客,記錄全部學習和工做中的博文,歡迎你們前去逛逛