使用Mybatis框架編寫持久層代碼時,有時我們只需要單表的操作,但如果手寫的話就會產生一些機械重復的工作,而通用Mapper的出現幫我們解決了這個問題。
我使用的通用Mapper是巨佬abel533寫的框架,這個框架提供了極其方便的MyBatis單表的增刪改查,可以讓我們不必在單表操作的編寫上浪費多少時間。
通用Mapper的使用步驟
1.要使用通用Mapper需要先導入依賴
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.0.3</version>
</dependency>
2.編寫配置文件
在resource目錄下新建application.properties文件
#服務器相關配置
server.port=80
server.servlet.context-path=/learn
#數據庫連接信息
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/數據庫名
spring.datasource.username=root
spring.datasource.password=****
3.編寫啟動類
package com.learn;
//聲明該注解是springboot的引導類
@SpringBootApplication
@MapperScan("com.learn.mapper")//注冊通用mapper
public class MySpringBootApplication {
//main方法是程序的入口
public static void main(String[] args) {
//run方法,表示運行SpringBoot的引導類,參數就是SpringBoot的引導類字節碼對象
SpringApplication.run(MySpringBootApplication.class);
}
}
4.編寫實體類
package com.learn.domain;
/**
* User實體類
*/
//告知通用Mapper要對哪張表進行操作
@Table(name = "user")
public class User implements Serializable {
//告知通用Mapper此屬性對應表中的主鍵
@Id
//告知通用Mapper此屬性是自增長的
@KeySql(useGeneratedKeys = true)
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
//忽略此屬性,不作為查詢條件
@Transient
private String test;
}
5.新建UserMapper
package com.learn.mapper;
public interface UserMapper extends Mapper<User> {
//Mapper只需要繼承tk.mybatis.mapper.common.Mapper<T>這個接口,通用Mapper就會自動幫我們生成Mybatis的單表的增刪改查。
}
到這里通用Mapper就編寫完了,是不是特別方便快捷,下面我們來測試一下這些方法。
5.編寫測試類
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MySpringBootApplication.class)
public class UserMapper2Test {
@Autowired
private UserMapper userMapper;
//因為我懶,這里只寫了一個根據主鍵查詢,和一個根據User對象中的非空屬性查詢
@Test
public void TestMethod(){
int id = 41;
String username = "老王";
User user = userMapper.selectByPrimaryKey(id);
User user2 = new User();
user2.setUsername(username);
//根據User的非空屬性查詢
User user1 = userMapper.selectOne(user2);
System.out.println(user1);
System.out.println(user);
}
}
我自己還編寫了service來測試事務,事務的使用方式和之前一樣,只需要在方法上加@Transactional注解即可。
如有錯漏,歡迎指正!