SpringBoot和druid數據源集成Jpa

一、pom文件java

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 4     <modelVersion>4.0.0</modelVersion>
 5 
 6     <groupId>com.example</groupId>
 7     <artifactId>demo</artifactId>
 8     <version>0.0.1-SNAPSHOT</version>
 9     <packaging>jar</packaging>
10 
11     <name>demo</name>
12     <description>Demo project for Spring Boot</description>
13 
14     <parent>
15         <groupId>org.springframework.boot</groupId>
16         <artifactId>spring-boot-starter-parent</artifactId>
17         <version>2.1.0.RELEASE</version>
18         <relativePath/> <!-- lookup parent from repository -->
19     </parent>
20 
21     <properties>
22         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
23         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
24         <druid.version>1.1.10</druid.version>
25         <mysql-connector.version>5.1.39</mysql-connector.version>
26         <java.version>1.8</java.version>
27     </properties>
28 
29     <dependencies>
30         <dependency>
31             <groupId>org.springframework.boot</groupId>
32             <artifactId>spring-boot-starter-data-jpa</artifactId>
33         </dependency>
34         <dependency>
35             <groupId>org.springframework.boot</groupId>
36             <artifactId>spring-boot-starter-web</artifactId>
37         </dependency>
38         <dependency>
39             <groupId>org.mybatis.spring.boot</groupId>
40             <artifactId>mybatis-spring-boot-starter</artifactId>
41             <version>1.3.2</version>
42         </dependency>
43         <!-- MySQL 鏈接驅動依賴 -->
44         <dependency>
45             <groupId>mysql</groupId>
46             <artifactId>mysql-connector-java</artifactId>
47             <version>${mysql-connector.version}</version>
48         </dependency>
49         <dependency>
50             <groupId>com.alibaba</groupId>
51             <artifactId>druid</artifactId>
52             <version>${druid.version}</version>
53         </dependency>
54         <dependency>
55             <groupId>com.alibaba</groupId>
56             <artifactId>druid-spring-boot-starter</artifactId>
57             <version>${druid.version}</version>
58         </dependency>
59         <dependency>
60             <groupId>javax.servlet</groupId>
61             <artifactId>javax.servlet-api</artifactId>
62         </dependency>
63 
64         <dependency>
65             <groupId>org.springframework.boot</groupId>
66             <artifactId>spring-boot-starter-test</artifactId>
67             <scope>test</scope>
68         </dependency>
69         <!-- MySql 5.5 Connector -->
70         <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
71         <dependency>
72             <groupId>mysql</groupId>
73             <artifactId>mysql-connector-java</artifactId>
74             <version>5.1.47</version>
75         </dependency>
76     </dependencies>
77     <build>
78         <plugins>
79             <plugin>
80                 <groupId>org.springframework.boot</groupId>
81                 <artifactId>spring-boot-maven-plugin</artifactId>
82             </plugin>
83         </plugins>
84     </build>
85 </project>
pom文件內容

二、yml文件mysql

 1 spring:
 2   datasource:
 3     druid:
 4       mysql:
 5         name: mysql
 6         type: com.alibaba.druid.pool.DruidDataSource
 7         driver-class-name: com.mysql.jdbc.Driver
 8         url: jdbc:mysql://localhost:3306/smbms?useUnicode=true&characterEncoding=utf8&useSSL=false
 9         username: root
10         password: 123456
yml文件

三、編寫entityweb

 1 @Entity
 2 @Table(name = "smbms_user")//指明映射到數據庫中的哪一個表
 3 public class User {
 4     @javax.persistence.Id
 5     @GeneratedValue(strategy = GenerationType.AUTO)//對於自增的主鍵加註解
 6     private Integer id;
 7     //用戶編碼
 8     private String userCode;
 9 
10     @Column(name = "user_Name")
11     private String userName;
12 
13     @Column(name = "user_Password")
14     private String userPassword;
15 
16     //用戶性別
17     @Column(name = "gender")
18     private int gender;
19 
20     @Column(name = "birthday")
21     private Date birthday;
22     @Column(name = "phone")
23     private String phone;
24     @Column(name = "address")
25     private String address;
26 
27     @Column(name = "create_By")
28     private Integer createBy;
29 
30     @Column(name = "creation_Date")
31     private Date creationDate;
32 
33     @Column(name = "modify_By")
34     private Integer modifyBy;
35 
36     //更新時間
37     @Column(name = "modify_Date")
38     private Date modifyDate;
entity

四、編寫daospring

 1 /**
 2  * @RepositoryDefinition(domainClass = UserDao.class, idClass = Integer.class)
 3  * public interface UserDao{}等價於如下方式
 4  */
 5 @Repository
 6 public interface UserDao extends JpaRepository<User, Integer> {
 7 
 8     public List<User> findById(int id);
 9 
10     @Modifying
11     @Transactional
12     @Query(value = "update  User set userName =?1 where id=?2 ")
13     void updateName(String userName, int id);
14 
15     //註解使用sql語句的時候,只要把nativeQuery屬性改成true就能夠了,同時,書寫sql語句須要使用value來定義,
16     // nativeQuery = true表示使用寫的sql,不是HQL
17     @Query(nativeQuery = true, value = "select * from smbms_user where user_name= ? ")
18     public List<User> findByUserName(String name);
19 
20 }
dao

五、配置datasourcesql

 1 @Configuration
 2 public class GlobalDataSourceConfiguration {
 3 
 4   private static Logger LOG = LoggerFactory.getLogger(GlobalDataSourceConfiguration.class);
 5 
 6   @Bean
 7   @ConfigurationProperties(prefix = "spring.datasource.druid.mysql")
 8   public DataSource primaryDataSource() {
 9     LOG.info("-------------------- primaryDataSource init ---------------------");
10     return DruidDataSourceBuilder.create().build();
11   }
12 }
datasource

六、備註數據庫

1)Dao層要寫成interface,而後繼承 JpaRepository<Entity,Key>,第一個是這個接口有關的實體,第二個參數是這個實體的主鍵。apache

2)幾種主鍵生成策略的比較:api

  SEQUENCE,IDENTITY兩種策略因爲針對的是特殊的一些數據庫,因此若是在需求前期,未肯定系統要支持的數據庫類型時,最好不要使用。由於一旦更改數據庫類型時,例如從Oracle變動爲MySQL時,此時使用的Sequence策略就不能使用了,這時候須要變動設置,會變得很麻煩。mybatis

  AUTO自動生成策略雖然可以自動生成主鍵,但主鍵的生成規則是JPA的實現者來肯定的,一旦使用了這種策略,用戶沒有辦法控制,好比說初識值是多少,每次累加值是多少,這些只能靠JPA默認的實現來生成。對於比較簡單的主鍵,對主鍵生成策略要求少時,採用的這種方式比較好。app

  TABLE生成策略是將主鍵的值持久化在數據庫中表中,由於只要是關係型的數據庫,均可以建立一個表,來專門保存生成的值,這樣就消除了不一樣數據庫之間的不兼容性。另外,這種策略也但是設置具體的生成策略,又彌補了AUTO策略的不足。因此,這種策略既能保證支持多種數據庫,又有必定的靈活性。

     若以上的4種主鍵生成策略仍不知足需求,這時能夠經過必定的規則來設置主鍵的值。例如利用UUID做爲主鍵,也是經常使用的策略之一,此時就須要在程序中自動生成,而後設置到實體的主鍵上,而不能經過JPA的主鍵生成策略來實現了。
3)幾種註解

@Basic 表示一個簡單的屬性到數據庫表的字段的映射,對於沒有任何標註的 getXxxx() 方法

@Basic fetch: 表示該屬性的讀取策略,有 EAGER 和 LAZY 兩種,分別表示主支抓取和延遲加載,默認爲 EAGER,optional:表示該屬性是否容許爲null, 默認爲true

@Transient:表示該屬性並不是一個到數據庫表的字段的映射,ORM框架將忽略該屬性.若是一個屬性並不是數據庫表的字段映射,就務必將其標示爲@Transient,不然,ORM框架默認其註解爲@Basic

1 //工具方法,不須要映射爲數據表的一列
2     @Transient
3     public String getInfo(){
4         return "lastName:"+lastName+",email:"+email;
5     }
transient實列

@Temporal:在覈心的 Java API 中並無定義 Date 類型的精度(temporal precision). 而在數據庫中,表示 Date 類型的數據有 DATE, TIME, 和 TIMESTAMP 三種精度(即單純的日期,時間,或者二者 兼備)。

1 @Temporal(TemporalType.TIMESTAMP)// 時間戳
2     public Date getCreatedTime() {
3         return createdTime;
4         }
5 
6 @Temporal(TemporalType.DATE) //時間精確到天
7     public Date getBirth() {
8         return birth;
9     }
temporal實例

4)jpa語法與sql語法比較

Keyword Sample JPQL snippet

And

findByLastnameAndFirstname

… where x.lastname = ?1 and x.firstname = ?2

Or

findByLastnameOrFirstname

… where x.lastname = ?1 or x.firstname = ?2

Is,Equals

findByFirstname,findByFirstnameIs,findByFirstnameEquals

… where x.firstname = ?1

Between

findByStartDateBetween

… where x.startDate between ?1 and ?2

LessThan

findByAgeLessThan

… where x.age < ?1

LessThanEqual

findByAgeLessThanEqual

… where x.age ⇐ ?1

GreaterThan

findByAgeGreaterThan

… where x.age > ?1

GreaterThanEqual

findByAgeGreaterThanEqual

… where x.age >= ?1

After

findByStartDateAfter

… where x.startDate > ?1

Before

findByStartDateBefore

… where x.startDate < ?1

IsNull

findByAgeIsNull

… where x.age is null

IsNotNull,NotNull

findByAge(Is)NotNull

… where x.age not null

Like

findByFirstnameLike

… where x.firstname like ?1

NotLike

findByFirstnameNotLike

… where x.firstname not like ?1

StartingWith

findByFirstnameStartingWith

… where x.firstname like ?1(parameter bound with appended %)

EndingWith

findByFirstnameEndingWith

… where x.firstname like ?1(parameter bound with prepended %)

Containing

findByFirstnameContaining

… where x.firstname like ?1(parameter bound wrapped in%)

OrderBy

findByAgeOrderByLastnameDesc

… where x.age = ?1 order by x.lastname desc

Not

findByLastnameNot

… where x.lastname <> ?1

In

findByAgeIn(Collection<Age> ages)

… where x.age in ?1

NotIn

findByAgeNotIn(Collection<Age> age)

… where x.age not in ?1

True

findByActiveTrue()

… where x.active = true

False

findByActiveFalse()

… where x.active = false

IgnoreCase

findByFirstnameIgnoreCase

… where UPPER(x.firstame) = UPPER(?1)

以上僅供參考!!!!!!!!!!!!

相關文章
相關標籤/搜索