springboot支付项目之springboot集成jpa

springboot集成spring-jpajava

本文主要内容:mysql

1:spring boot怎么集成spring-jpa以及第一个jpa查询示例spring

如jpa几个经常使用注解、lombok注解使用sql

2:怎么设置idea中在pom中添加依赖的时候自动联想。数据库

3:集成过程当中遇到的问题及解决.如mysql时区问题、jpa懒加载问题。springboot

咱们听从MVC三层模式,DAO层设计与开发、Service层设计与开发以及Controller层。框架

咱们先来DAO层设计开发,Spring boot项目基础框架建立这里就省略。maven

本文出自:凯哥Java(kaigejava)ide

《spring boot支付项目》。凯哥我的博客:www.kaigejava.comspring-boot

一:相关jar依赖添加

由于使用到了mysql,在POM.XML文件中引入mysql相关jar及操做数据库相关的。这里咱们使用的是spring-jpa来操做数据库。具体jra以下:

<!-- mysql 相关的依赖-->

<dependency>

  <groupId>mysql</groupId>

  <artifactId>mysql-connector-java</artifactId>

</dependency>

<!-- jpa相关依赖-->

<dependency>

  <groupId>org.springframework.boot</groupId>

  <artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>


在教你们一个idea怎么在pom文件中输入坐标时候联想,以下图:在输入atrifactid的时候能够联想到,以下图:

document_image_rId9.png

document_image_rId10.png

操做:file-->settings界面,依次找到:build,execution,Deployment-->Bulid Tools-->maven-->Repositories.以下图:

document_image_rId11.png

点击更新就能够了。

二:数据库链接配置。这里咱们使用的是yml格式的。配置以下图:

document_image_rId12.png

spring:

 datasource:

   driver-class-name: com.mysql.cj.jdbc.Driver

   username: root

   password: 123456

   url: jdbc:mysql://localhost/springboot-wxpay?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false

 jpa:

   show-sql: true

说明:

spring.jpa.show-sql=true.这句意思是:打印sql语句。

在url后面添加serverTimeizone=UTC是为了解决时区错误的问题。

三:建立实体及测试

3.1:建立ProductCategory实体对象。使用spring-jpa方式:

document_image_rId13.png

说明:

@Entity:spring-jpa实体注解

@Data: lombok注解用于自动生产get/set方法的

@Id:jpa的主键注解

@GeneratedValue:注解生成策略

3.2:建立repository接口对象

document_image_rId14.png

说明:使用jpa的须要继承Jparepository这个对象(有多个,这里就用简单的)

其中泛型,咱们查看源码:

document_image_rId15.png

T:实体对象的。也就是咱们上面建立的ProductCategory对象

ID:实体对象的ID类型。咱们使用的事Integer类型。因此这里就写Integer。

四:建立测试类,进行测试:

在IDEA中,建立测试类快捷键:选中类名以后,ctrl+shift+t。以下图:

document_image_rId16.png

document_image_rId17.png

运行结果:

document_image_rId18.png

在控制台上,咱们能够看到hibernate打印的sql语句以及打印出查询的结果。说明springboot继承jpa成功。

若是出现could not initialize proyx的时候,以下图错误:


document_image_rId19.png

在实体上面添加@Proxy(lazy = false)

document_image_rId20.png

说明:@ToString 是直接添加toString方法的。

相关文章
相关标签/搜索