SpringBoot和druid数据源集成Jpa

1、pom文件

 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文件内容

2、yml文件

 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文件

3、编写entity

 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

4、编写dao

 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

5、配置datasource

 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

6、备注

1)Dao层要写成interface,然后继承 JpaRepository<Entity,Key>,第一个是这个接口有关的实体,第二个参数是这个实体的主键。

2)几种主键生成策略的比较:

  SEQUENCE,IDENTITY两种策略由于针对的是特殊的一些数据库,所以如果在需求前期,未确定系统要支持的数据库类型时,最好不要使用。因为一旦更改数据库类型时,例如从Oracle变更为MySQL时,此时使用的Sequence策略就不能使用了,这时候需要变更设置,会变得很麻烦。

  AUTO自动生成策略虽然能够自动生成主键,但主键的生成规则是JPA的实现者来确定的,一旦使用了这种策略,用户没有办法控制,比如说初识值是多少,每次累加值是多少,这些只能靠JPA默认的实现来生成。对于比较简单的主键,对主键生成策略要求少时,采用的这种方式比较好。

  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语法比较

KeywordSampleJPQL 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)

以上仅供参考!!!!!!!!!!!!

转载于:https://www.cnblogs.com/zxh-xy/p/10585419.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值