SpringDataJpa项目中的使用

Posted 坚持就是胜利

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringDataJpa项目中的使用相关的知识,希望对你有一定的参考价值。

1. Jpa的使用

1.1 pom.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="http://maven.apache.org/POM/4.0.0"
 3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 5     <modelVersion>4.0.0</modelVersion>
 6 
 7     <groupId>com.springdataJpa</groupId>
 8     <artifactId>springdataJpa</artifactId>
 9     <packaging>pom</packaging>
10     <version>1.0-SNAPSHOT</version>
11     <modules>
12         <module>jdbcTemplate</module>
13         <module>jpa</module>
14     </modules>
15 
16     <!-- Spring boot 父引用-->
17     <parent>
18         <groupId>org.springframework.boot</groupId>
19         <artifactId>spring-boot-starter-parent</artifactId>
20         <version>1.4.1.RELEASE</version>
21     </parent>
22 
23     <dependencies>
24         <!-- Spring boot 核心web-->
25         <dependency>
26             <groupId>org.springframework.boot</groupId>
27             <artifactId>spring-boot-starter-web</artifactId>
28         </dependency>
29         <dependency>
30             <groupId>org.springframework.boot</groupId>
31             <artifactId>spring-boot-starter-data-jpa</artifactId>
32         </dependency>
33         <dependency>
34             <groupId>org.projectlombok</groupId>
35             <artifactId>lombok</artifactId>
36             <version>1.16.18</version>
37         </dependency>
38         <dependency>
39             <groupId>com.alibaba</groupId>
40             <artifactId>fastjson</artifactId>
41             <version>1.2.29</version>
42         </dependency>
43         <dependency>
44             <groupId>org.springframework.boot</groupId>
45             <artifactId>spring-boot-starter-logging</artifactId>
46         </dependency>
47         <dependency>
48             <groupId>org.springframework.boot</groupId>
49             <artifactId>spring-boot-starter-test</artifactId>
50         </dependency>
51         <dependency>
52             <groupId>com.oracle</groupId>
53             <artifactId>ojdbc14</artifactId>
54             <version>10.2.0.4.0</version>
55         </dependency>
56         <!--<dependency>
57             <groupId>mysql</groupId>
58             <artifactId>mysql-connector-java</artifactId>
59         </dependency>-->
60     </dependencies>
61 
62     <build>
63         <plugins>
64             <plugin>
65                 <groupId>org.springframework.boot</groupId>
66                 <artifactId>spring-boot-maven-plugin</artifactId>
67                 <executions>
68                     <execution>
69                         <goals>
70                             <goal>repackage</goal>
71                         </goals>
72                     </execution>
73                 </executions>
74                 <configuration>
75                     <executable>true</executable>
76                 </configuration>
77             </plugin>
78         </plugins>
79     </build>
80 </project>

1.2 application.properties

 1 server.port=8089
 2 server.servlet-path=/
 3 spring.resources.static-locations=classpath:/static/,classpath:/templates/
 4 spring.mvc.view.suffix=.html
 5 
 6 #配置数据源
 7 #mysql
 8 #spring.datasource.driver-class-name=com.mysql.jdbc.Driver
 9 #spring.datasource.url=jdbc:mysql://localhost:3306/jpa
10 #spring.datasource.username=root
11 #spring.datasource.password=root
12 
13 #oracle
14 spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
15 spring.datasource.url=jdbc:oracle:thin:@localhost:1521:orcl
16 spring.datasource.username=scott
17 spring.datasource.password=scott
18 
19 spring.jpa.hibernate.ddl-auto=update
20 
21 spring.jpa.properties.hibernate.hbm2ddl.auto=update
22 spring.jpa.show-sql=true
23 ##懒加载默认就为true
24 spring.jpa.open-in-view=true
25 
26 #在控制台输出彩色日志
27 spring.output.ansi.enabled=always

1.3 model

  1.3.1 BaseDomain.class

 1 package com.springdatajpa.model.base;
 2 
 3 import com.alibaba.fastjson.annotation.JSONField;
 4 
 5 import javax.persistence.Column;
 6 import javax.persistence.MappedSuperclass;
 7 import javax.persistence.PrePersist;
 8 import javax.persistence.PreUpdate;
 9 import java.io.Serializable;
10 import java.util.Date;
11 
12 /**
13 * @date 2018/7/30
14 */
15 @MappedSuperclass
16 abstract public class BaseDomain implements Serializable {
17 
18     /**
19      * 创建日期
20      */
21     @Column(name = "date_created")
22     @JSONField(format = "yyyy-MM-dd HH:mm:ss")
23     private Date dateCreated;
24 
25     /**
26      * 最后更新日期
27      */
28     @Column(name = "last_updated")
29     @JSONField(format = "yyyy-MM-dd HH:mm:ss")
30     private Date lastUpdated;
31 
32     @Column(name = "version")
33     private Integer version;
34 
35     @Column(name = "is_delete")
36     private Boolean isDelete = false;
37 
38     @JSONField(format = "yyyy-MM-dd HH:mm:ss")
39     private Date deleteDate;
40 
41     public Date getDateCreated() {
42         return dateCreated;
43     }
44 
45     public void setDateCreated(Date dateCreated) {
46         this.dateCreated = dateCreated;
47     }
48 
49     public Date getLastUpdated() {
50         return lastUpdated;
51     }
52 
53     public void setLastUpdated(Date lastUpdated) {
54         this.lastUpdated = lastUpdated;
55     }
56 
57     public Integer getVersion() {
58         return version;
59     }
60 
61     public void setVersion(Integer version) {
62         this.version = version;
63     }
64 
65     public Boolean getIsDelete() {
66         return isDelete;
67     }
68 
69     public void setIsDelete(Boolean isDelete) {
70         if (isDelete != null && isDelete) {
71             this.deleteDate = new Date();
72         }
73         this.isDelete = isDelete;
74     }
75 
76     @PrePersist
77     protected void prePersist() {
78         dateCreated = new Date();
79         version = 1;
80     }
81 
82 
83     @PreUpdate
84     private void preUpdate() {
85         lastUpdated = new Date();
86         if (version == null) {
87             version = 1;
88         } else {
89             version++;
90         }
91     }
92 }

1.3.2 Student.class

 1 package com.springdatajpa.model;
 2 
 3 import com.springdatajpa.model.base.BaseDomain;
 4 import lombok.Data;
 5 import org.hibernate.annotations.GenericGenerator;
 6 
 7 import javax.persistence.*;
 8 import java.io.Serializable;
 9 import java.util.List;
10 
11 /**
12  * @date 2018/7/30
13  */
14 @Entity
15 @Data
16 public class Student extends BaseDomain implements Serializable {
17     /**
18      * 主键.
19      */
20     @Id
21     @GenericGenerator(name = "PKUUID", strategy = "uuid2")
22     @GeneratedValue(generator = "PKUUID")
23     private String id;
24     /**
25      * 姓名.
26      */
27     private String name;
28     /**
29      * 编号.
30      */
31     private String studentNo;
32     /**
33      * 年龄
34      */
35     private Integer age;
36 
37     /**
38      * 地址列表
39      */
40     @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "student")
41     private List<Address> addresses;
42 
43 }

1.3.3 Address.class

 1 package com.springdatajpa.model;
 2 
 3 import com.springdatajpa.model.base.BaseDomain;
 4 import lombok.Data;
 5 import org.hibernate.annotations.GenericGenerator;
 6 
 7 import javax.persistence.*;
 8 import java.io.Serializable;
 9 
10 /**
11  * @author12  * @date 2018/7/30
13  */
14 @Entity
15 @Data
16 public class Address extends BaseDomain implements Serializable {
17     /**
18      * 主键.
19      */
20     @Id
21     @GenericGenerator(name = "PKUUID", strategy = "uuid2")
22     @GeneratedValue(generator = "PKUUID")
23     private String id;
24     /**
25      * 地址
26      */
27     private String addressDetail;
28     /**
29      * 学生id.
30      */
31     @ManyToOne
32     @JoinColumn(name = "STUDENT_ID", foreignKey = @ForeignKey(name = "FK_STUDENT_ADDRESS"))
33     private Student student;
34 
35 }

1.4 repository

1.4.1 StudentRepo.class

 1 package com.springdatajpa.repository;
 2 
 3 import com.springdatajpa.model.Student;
 4 import org.springframework.data.jpa.repository.JpaRepository;
 5 import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
 6 import org.springframework.data.repository.CrudRepository;
 7 
 8 /**
 9  * @author10  * @date 2018/7/30
11  */
12 public interface StudentRepo extends JpaRepository<Student,String>,JpaSpecificationExecutor<Student> {
13 
14     Student findById(String id);
15 }

1.4.2 AddressRepo.class

 1 package com.springdatajpa.repository;
 2 
 3 import com.springdatajpa.model.Address;
 4 import org.springframework.data.jpa.repository.JpaRepository;
 5 import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
 6 
 7 /**
 8  * @author 9  * @date 2018/7/30
10  */
11 public interface AddressRepo extends JpaRepository<Address,String>,JpaSpecificationExecutor<Address> {
12     Address findById(String id);
13 }

1.5 specification

1.5.1 StudentSpecification.class

 1 package com.springdatajpa.specification;
 2 
 3 import com.springdatajpa.dto.StudentQuery;
 4 import org.springframework.data.jpa.domain.Specification;
 5 import org.springframework.util.StringUtils;
 6 
 7 import javax.persistence.criteria.CriteriaBuilder;
 8 import javax.persistence.criteria.CriteriaQuery;
 9 import javax.persistence.criteria.Predicate;
10 import javax.persistence.criteria.Root;
11 import java.util.ArrayList;
12 import java.util.List;
13 
14 /**
15  * @author16  * @date 2018/7/30
17  */
18 public class StudentSpecification<T> implements Specification<T> {
19     private StudentQuery studentQuery;
20 
21     public StudentSpecification() {
22     }
23 
24     public StudentSpecification(StudentQuery studentQuery) {
25         this.studentQuery = studentQuery;
26     }
27 
28     @Override
29     public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
30         List<Predicate> predicates = new ArrayList<>();
31         predicates.add(cb.equal(root.get("isDelete"), false));
32         if (!StringUtils.isEmpty(studentQuery.getName()) && !studentQuery.getName().isEmpty()) {
33             predicates.add(cb.equal(root.get("name"), studentQuery.getName()));
34         }
35         if (!StringUtils.isEmpty(studentQuery.getAge()) && !studentQuery.getAge().isEmpty()) {
36             predicates.add(cb.equal(root.get("age"), studentQuery.getAge()));
37         }
38         if (!StringUtils.isEmpty(studentQuery.getStudentNo()) && !studentQuery.getStudentNo().isEmpty()) {
39             predicates.add(cb.equal(root.get("studentNo"), studentQuery.getStudentNo()));
40         }
41         if (studentQuery.getStartTime() != null) {
42             predicates.add(cb.greaterThanOrEqualTo(root.get("dateCreated"), studentQuery.getStartTime()));
43         }
44         if (studentQuery.getEndTime() != null) {
45             predicates.add(cb.lessThanOrEqualTo(root.get("dateCreated"), studentQuery.getEndTime()));
46         }
47         return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
48     }
49 }

 

以上是关于SpringDataJpa项目中的使用的主要内容,如果未能解决你的问题,请参考以下文章

从片段类中的对话框添加项目到recyclerview。

Eclipse 中的通用代码片段或模板

片段中 ListView 的 setOnItemClickListener

关于SpringDataJpa中测试出现StackOverflowError错误问题

片段中的 notifyDataSetChanged() 不刷新列表视图

如何访问 MainActivity() 中的片段元素?