3.Spring Boot的數(shù)據(jù)訪問

Spring Data項目是Spring用來解決數(shù)據(jù)訪問問題的一攬子解決方案。包含了大量了關(guān)系型數(shù)據(jù)庫及非關(guān)系型數(shù)據(jù)庫的解決方案。

1.Spring Data主要的包含的子項目

  • Spring Data Commons - Core Spring concepts underpinning every Spring Data project.

  • Spring Data Gemfire - Provides easy configuration and access to GemFire from Spring applications.

  • Spring Data JPA - Makes it easy to implement JPA-based repositories.

  • Spring Data KeyValue - Map-based repositories and SPIs to easily build a Spring Data module for key-value stores.

  • Spring Data LDAP - Provides Spring Data repository support for Spring LDAP.

  • Spring Data MongoDB - Spring based, object-document support and repositories for MongoDB.

  • Spring Data REST - Exports Spring Data repositories as hypermedia-driven RESTful resources.

  • Spring Data Redis - Provides easy configuration and access to Redis from Spring applications.

  • Spring Data for Apache Cassandra - Spring Data module for Apache Cassandra.

  • Spring Data for Apache Solr - Spring Data module for Apache Solr.

2.Spring Data Commons

Spring Data Commons是以上子項目的底層。它提供了統(tǒng)一的API。并且封裝了Spring Data Repository抽象類。

不同的子項目在分別實現(xiàn)了自己的Repository。比如Spring Data JPA是JpaRepository。Spring Data MongoDB是MongoRepository等等。

Spring Data還是提供了根據(jù)屬性進行計數(shù)、刪除、查詢等方法。

3.Spring Data Jpa(重點)

JPA即 Java Persistence API。JPA是基于O/R映射的標準規(guī)范。JPA主要實現(xiàn)由:Hibernate、EclipseLink、OpenJPA等實現(xiàn)。

  • 1.創(chuàng)建數(shù)據(jù)庫
CREATE DATABASE IF NOT EXISTS springbootstudy CHARSET utf8 COLLATE utf8_general_ci;
  • 2.創(chuàng)建表
CREATE TABLE person(
 id BIGINT(20) NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT '自增主鍵',
 NAME VARCHAR(50) NOT NULL DEFAULT '' COMMENT '姓名',
 age TINYINT NOT NULL DEFAULT 0 COMMENT '年齡',
 gmt_create DATE COMMENT '創(chuàng)建時間',
 gmt_modified DATE COMMENT '更新時間'
)ENGINE=INNODB 

3.1 Spring Boot的支持

1.JDBC的配置

查看spring-boot-starter-data-jpa的pom文件可以看到該jar需要依賴于spring-boot-starter-jdbc。而Spring Boot對于JDBC的自動配置在org.springframework.boot.autoconfigure.jdbc包中。

通過查看DataSourceProperties類,得知通過spring.datasource為前綴的屬性自動配置JDBC

Spring Boot對于JPA的自動配置放置在org.springframework.boot.autoconfigure.orm.jpa里。使用spring.jpa前綴進行配置。也通過源碼看到Spring Boot默認的JPA的實現(xiàn)是Hibernate

3.2 實戰(zhàn)代碼配置

  • 配置spring.datasource
spring.datasource.username=root
spring.datasource.data-password=xxxx
spring.datasource.url=jdbc:mysql://localhost:3306/springdbootstudy?serverTimezone=Asia/Shanghai
spring.datasource.driverClassName = com.mysql.jdbc.Driver
  • 配置spring.jpa
# hibernate提供了根據(jù)實體類自動維護數(shù)據(jù)庫表結(jié)構(gòu)的功能。而none代表不做任何處理
spring.jpa.hibernate.ddl-auto=none
#顯示真實的sql
spring.jpa.show-sql=true
#讓控制臺輸出的json字符串格式更加美觀
spring.jackson.serialization.indent-output=true
  • 1.創(chuàng)建person實體類
@Entity //@Entity注解指明這是一個和數(shù)據(jù)庫表影射的實體類
@Table(name = "person")//@Table代表類名稱和數(shù)據(jù)庫表名稱一致。

public class Person implements Serializable {

    private static final long serialVersionUID = -6082167954080285357L;

    /**
     * 自增id
     */
    @Id  //@Id注解指明這個屬性映射為數(shù)據(jù)庫的主鍵
    @GeneratedValue(strategy = GenerationType.AUTO) //@GeneratedValue注解默認使用主鍵生成方式為自增
    private long id;

    /**
     * 姓名
     */
    private String name;

    /**
     * 年齡
     */
    private Integer age;

    /**
     * 創(chuàng)建時間
     */
    @Column(name = "gmt_create")//@Cloumn注解來表明映射屬性名和字段名。不注解的表明屬性名稱跟數(shù)據(jù)庫表字段名稱一致。
    private Date create;

    /**
     * 更新時間
     */
    @Column(name = "gmt_modified")
    private Date modified;

    //省略getter/setter
    
    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", create=" + create +
                ", modified=" + modified +
                '}';
    }
}
  • 2.創(chuàng)建repository
public interface PersonRepository extends JpaRepository<Person, Long> {

    /**
     * 常規(guī)查詢。根據(jù)屬性名稱來定義查詢方法
     *
     * @param name
     * @return
     */
    List<Person> findByName(String name);

    /**
     * 查詢多個屬性之間用And連接
     *
     * @param name
     * @param age
     * @return
     */
    List<Person> findByNameAndAge(String name, String age);

    /**
     * 通過名稱Like查詢
     *
     * @param name
     * @return
     */
    List<Person> findByNameLike(String name);

    /**
     * 使用@Query查詢,參數(shù)按照名稱綁定
     *
     * @param name
     * @param age
     * @return
     */
    @Query("select p from Person p where p.name= :name and p.age= :age")
    Person withNameAndAgeQuery(@Param("name") String name, @Param("age") Integer age);
}
  • 測試
   @RequestMapping("save")
    public String insert() {
        String msg = null;
        try {
            Person p = new Person();
            p.setName("張三");
            p.setAge(18);
            p.setCreate(new Date());
            personRepository.save(p);
            msg = "成功";
        } catch (Exception ex) {
            msg = ex.getMessage();
        }
        return msg;
    }

    @RequestMapping("find")
    public String find() {
        try {
            //List<Person> ss=personRepository.findByName("張三");
//List<Person> ss=personRepository.withNameAndAge("張三",19);
//            for (Person p:ss){
//                System.out.println(p.toString());
//            }
            Person p = personRepository.withNameAndAgeQuery("張三", 18);
            System.out.println(p.toString());
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return "sa";
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容