單調的增刪改查讓越來越多的程序員感到乏味,這時候就出現了很多優秀的框架,完成了對增刪改查操作的封裝,只需要簡單配置,無需書寫任何sql,就可以完成增刪改查。這里比較推薦的是Spring Data Jpa。
Spring Data JPA是Spring Data家族的一部分,可以輕松實現基於JPA的存儲庫。 此模塊處理對基於JPA的數據訪問層的增強支持。 它使構建使用數據訪問技術的Spring驅動應用程序變得更加容易。
我們繼續使用前兩章用的數據庫結構來進行演示。
一 引入mysql和spring-data-jpa依賴
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
二 創建實體類
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Student implements Serializable {
private static final long serialVersionUID = 6712540741269055064L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer studentId;
private Integer age;
private String name;
private Integer sex;
private Date createTime;
private Integer status;
}
@GeneratedValue是主鍵生成策略,Jpa自帶的幾種主鍵生成策略如下:
-
TABLE: 使用一個特定的數據庫表格來保存主鍵
-
SEQUENCE: 根據底層數據庫的序列來生成主鍵,條件是數據庫支持序列。這個值要與generator一起使用,generator 指定生成主鍵使用的生成器(可能是orcale中自己編寫的序列)
-
IDENTITY: 主鍵由數據庫自動生成(主要是支持自動增長的數據庫,如mysql)
-
AUTO: 主鍵由程序控制,也是GenerationType的默認值
主鍵生成策略擴展
自定義主鍵生成器:
public class MyGenerator implements IdentifierGenerator {
@Override
public Serializable generate(SharedSessionContractImplementor sharedSessionContractImplementor, Object o) throws HibernateException {
return getId();
}
public static long getId(){
return System.currentTimeMillis();
}
}
然后在實體類做一下配置:
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Student implements Serializable {
private static final long serialVersionUID = 6712540741269055064L;
@Id
@GenericGenerator(name="idGenerator",strategy = "com.javatrip.springdatajpa.entity.MyGenerator")
@GeneratedValue(generator = "idGenerator")
private Integer studentId;
private Integer age;
private String name;
private Integer sex;
private Date createTime;
private Integer status;
}
三 創建dao接口
dao層接口實現JpaRepository,泛型選擇pojo和其主鍵類型,就會自動實現簡單的CRUD等接口,無需手動開發,就能快速進行調用。
public interface StudentRepository extends JpaRepository<Student,Integer> {
/**
* 根據年齡,名字模糊查詢
* @return
*/
Student findByNameLikeAndAge(String name,int age);
}
Jpa除了實現CRUD方法,還支持字段名模糊查詢等各種不用手寫sql的操作。
四 測試類測試CRUD
@SpringBootTest
class SpringDataJpaApplicationTests {
@Autowired
StudentRepository repository;
@Test
void contextLoads() {
// 查詢所有實體
List<Student> all = repository.findAll();
// 根據id查詢實體類
Optional<Student> byId = repository.findById(100);
// 根據id刪除數據
repository.deleteById(100);
// 插入一條數據
// 如果數據庫存在該實體的主鍵,則更新,否則插入
Student student = new Student();
student.setAge(18);
student.setName("Java旅途");
repository.save(student);
repository.findByNameLikeAndAge("Java",18);
}
}
spring-data-jpa在外國程序員界非常普遍。相比其他兩種方式,它不需要寫sql就可以完成非常完善的數據操作,我也是比較推薦使用它作為orm框架。
本文示例代碼已上傳至github,點個star支持一下!
Spring Boot系列教程目錄
spring-boot-route(一)Controller接收參數的幾種方式
spring-boot-route(二)讀取配置文件的幾種方式
spring-boot-route(五)整合swagger生成接口文檔
spring-boot-route(六)整合JApiDocs生成接口文檔
spring-boot-route(七)整合jdbcTemplate操作數據庫
spring-boot-route(八)整合mybatis操作數據庫
spring-boot-route(九)整合JPA操作數據庫
spring-boot-route(十一)數據庫配置信息加密
spring-boot-route(十二)整合redis做為緩存
spring-boot-route(十三)整合RabbitMQ
spring-boot-route(十五)整合RocketMQ
spring-boot-route(十六)使用logback生產日志文件
spring-boot-route(十七)使用aop記錄操作日志
spring-boot-route(十八)spring-boot-adtuator監控應用
spring-boot-route(十九)spring-boot-admin監控服務
spring-boot-route(二十)Spring Task實現簡單定時任務
spring-boot-route(二十一)quartz實現動態定時任務
spring-boot-route(二十二)實現郵件發送功能
spring-boot-route(二十四)分布式session的一致性處理
spring-boot-route(二十五)兩行代碼實現國際化
spring-boot-route(二十六)整合webSocket
這個系列的文章都是工作中頻繁用到的知識,學完這個系列,應付日常開發綽綽有余。如果還想了解其他內容,掃面下方二維碼告訴我,我會進一步完善這個系列的文章!

