The previous blog post described SpringBoot's process of integrating mybatis, but the way xml works always feels a bit frustrating; this article introduces a noxml usage posture that supports CURD purely with annotations
<!-- more -->
I. Environment
This article uses SpringBoot version 2.2.1.RELEASE, mybatis version 1.3.2, and database mysql 5+
1. Project Setup
It is recommended that you create a SpringBoot project with an official tutorial; if you create a maven project directly, copy the following configuration into your pom.xml
- The main introduction is mybatis-spring-boot-starter, which reduces the choking configuration
<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>
2. Configuration Information
In the application.yml configuration file, add the db configuration
spring: datasource: url: jdbc:mysql://127.0.0.1:3306/story?useUnicode=true&characterEncoding=UTF-8&useSSL=false username: root password:
Next, prepare a test table (still borrowing the table structure from previous db operation series blogs) for subsequent URDs; the table results are as follows
DROP TABLE IF EXISTS `money`; CREATE TABLE `money` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(20) NOT NULL DEFAULT '' COMMENT 'User name', `money` int(26) NOT NULL DEFAULT '0' COMMENT 'How much money', `is_deleted` tinyint(1) NOT NULL DEFAULT '0', `create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Creation Time', `update_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Update Time', PRIMARY KEY (`id`), KEY `name` (`name`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
II. Instance Integration
Expand from the previous article, focusing on eliminating xml files and implementing CURD through annotations on DAO interfaces
1. PO
Create PO object for table: MoneyPo
@Data public class MoneyPo { private Integer id; private String name; private Long money; private Integer isDeleted; private Timestamp createAt; private Timestamp updateAt; }
2. DAO interface
Table's operation interface, the following simple written four interfaces, corresponding to four CRUID operations
@Mapper public interface MoneyMapper { // Supports primary keys to write back to 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); }
From the implementation of mapper, you can also see that CURD is implemented through four annotations @Insert, @Select, @Update, @Delete. There are several points to note when using this approach
- insert: When we want the inserted primary key to be written back to PO, we can configure @Options(useGeneratedKeys = true, keyProperty = "po.id", keyColumn = "id")
- Dynamic sql: in the comment, wrap the dynamic SQL with <script>
- @Results Implement mapping relationships for <resultMap>
5. Testing
Next, simply test the four interfaces above to see if they work properly
Startup Class
@SpringBootApplication public class Application { public Application(MoneyRepository repository) { repository.testMapper(); } public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
Test Class
@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())); } }
Output Results
II. Other
0. Project
- Project: https://github.com/liuyueyi/spring-boot-demo
- Project Source: https://github.com/liuyueyi/spring-boot-demo/tree/master/spring-boot/104-mybatis-noxml
1.A grey Blog
Unlike letters, the above are purely family statements. Due to limited personal abilities, there are unavoidable omissions and errors. If bug s are found or there are better suggestions, you are welcome to criticize and correct them with gratitude.
Below is a grey personal blog, which records all the blogs in study and work. Welcome to visit it
- A Grey Blog Personal Blog https://blog.hhui.top
- A Grey Blog-Spring Thematic Blog http://spring.hhui.top