SpringBoot和druid数据源集成Jpa

时间:2021-10-11 11:04:16

1、pom文件

 <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>demo</name>
<description>Demo project for Spring Boot</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<druid.version>1.1.10</druid.version>
<mysql-connector.version>5.1.39</mysql-connector.version>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!-- MySQL 连接驱动依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- MySql 5.5 Connector -->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

pom文件内容

2、yml文件

 spring:
datasource:
druid:
mysql:
name: mysql
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/smbms?useUnicode=true&characterEncoding=utf8&useSSL=false
username: root
password: 123456

yml文件

3、编写entity

 @Entity
@Table(name = "smbms_user")//指明映射到数据库中的哪个表
public class User {
@javax.persistence.Id
@GeneratedValue(strategy = GenerationType.AUTO)//对于自增的主键加注解
private Integer id;
//用户编码
private String userCode; @Column(name = "user_Name")
private String userName; @Column(name = "user_Password")
private String userPassword; //用户性别
@Column(name = "gender")
private int gender; @Column(name = "birthday")
private Date birthday;
@Column(name = "phone")
private String phone;
@Column(name = "address")
private String address; @Column(name = "create_By")
private Integer createBy; @Column(name = "creation_Date")
private Date creationDate; @Column(name = "modify_By")
private Integer modifyBy; //更新时间
@Column(name = "modify_Date")
private Date modifyDate;

entity

4、编写dao

 /**
* @RepositoryDefinition(domainClass = UserDao.class, idClass = Integer.class)
* public interface UserDao{}等价于以下方式
*/
@Repository
public interface UserDao extends JpaRepository<User, Integer> { public List<User> findById(int id); @Modifying
@Transactional
@Query(value = "update User set userName =?1 where id=?2 ")
void updateName(String userName, int id); //注解使用sql语句的时候,只要把nativeQuery属性改为true就可以了,同时,书写sql语句需要使用value来定义,
// nativeQuery = true表示使用写的sql,不是HQL
@Query(nativeQuery = true, value = "select * from smbms_user where user_name= ? ")
public List<User> findByUserName(String name); }

dao

5、配置datasource

 @Configuration
public class GlobalDataSourceConfiguration { private static Logger LOG = LoggerFactory.getLogger(GlobalDataSourceConfiguration.class); @Bean
@ConfigurationProperties(prefix = "spring.datasource.druid.mysql")
public DataSource primaryDataSource() {
LOG.info("-------------------- primaryDataSource init ---------------------");
return DruidDataSourceBuilder.create().build();
}
}

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

 //工具方法,不需要映射为数据表的一列
@Transient
public String getInfo(){
return "lastName:"+lastName+",email:"+email;
}

transient实列

@Temporal:在核心的 Java API 中并没有定义 Date 类型的精度(temporal precision). 而在数据库中,表示 Date 类型的数据有 DATE, TIME, 和 TIMESTAMP 三种精度(即单纯的日期,时间,或者两者 兼备)。

 @Temporal(TemporalType.TIMESTAMP)// 时间戳
public Date getCreatedTime() {
return createdTime;
} @Temporal(TemporalType.DATE) //时间精确到天
public Date getBirth() {
return birth;
}

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)

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

SpringBoot和druid数据源集成Jpa