spring-boot-route(九)整合JPA操做數據庫

單調的增刪改查讓愈來愈多的程序員感到乏味,這時候就出現了不少優秀的框架,完成了對增刪改查操做的封裝,只須要簡單配置,無需書寫任何sql,就能夠完成增刪改查。這裏比較推薦的是Spring Data Jpa。java

Spring Data JPA是Spring Data家族的一部分,能夠輕鬆實現基於JPA的存儲庫。 此模塊處理對基於JPA的數據訪問層的加強支持。 它使構建使用數據訪問技術的Spring驅動應用程序變得更加容易。mysql

咱們繼續使用前兩章用的數據庫結構來進行演示。git

一 引入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: 使用一個特定的數據庫表格來保存主鍵github

  • SEQUENCE: 根據底層數據庫的序列來生成主鍵,條件是數據庫支持序列。這個值要與generator一塊兒使用,generator 指定生成主鍵使用的生成器(多是orcale中本身編寫的序列)redis

  • IDENTITY: 主鍵由數據庫自動生成(主要是支持自動增加的數據庫,如mysql)spring

  • AUTO: 主鍵由程序控制,也是GenerationType的默認值sql

主鍵生成策略擴展數據庫

自定義主鍵生成器:緩存

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(三)實現多文件上傳

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(十一)數據庫配置信息加密

spring-boot-route(十二)整合redis作爲緩存

spring-boot-route(十三)整合RabbitMQ

spring-boot-route(十四)整合Kafka

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(二十三)開發微信公衆號

這個系列的文章都是工做中頻繁用到的知識,學完這個系列,應付平常開發綽綽有餘。若是還想了解其餘內容,掃面下方二維碼告訴我,我會進一步完善這個系列的文章!

相關文章
相關標籤/搜索