springboot 集成 jpa/hibernate springboot 学习之集成JPA SpringBoot 2.1.1.RELEASE 集成JPA Spring Data JPA 中findOne() 和 getOne()的区别 SpringData系列四 @Query注解及@Modifying注解 在Spring Data JPA 中使用Update Query更新实体类@DynamicUpdate,@DynamicInsert

pom.xml

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

还需要一个根据实际情况的 mysql connecter

application.properties

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/detectx?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.open-in-view=false

这里 ?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai 必须要加上,能解决中文编码问题和springboot 2.0 以上版本的报错问题

spring.jpa.properties.hibernate.format_sql=true  这里的这个key虽然找不到,但是其实是有效的,参考 https://cloud.tencent.com/developer/ask/55788

SpringBoot将允许您使用以下方法设置任何可用的Hibernate属性:

spring.jpa.properties.*

所以spring.jpa.properties.hibernate.format_sql=true也会起作用的。

springboot 2.0 以上需要注意的:

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/project?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root

必须要这个 不然会报各种错 参考:
https://www.cnblogs.com/EasonJim/p/6906713.html
https://www.jianshu.com/p/836d455663da

springboot 设置不需要设置项目名的方式(更加方便了前端对于资源的引用和nginx的解析)

server.servlet.context-path=/
即可不需要以项目名作为web目录

hibernate 相关:

org.hibernate.LazyInitializationException: could not initialize proxy - no Session
getOne换成findOne即可


hibernate 解决诡异的mysql存入中文乱码:
使用hibernate查询mysql,通过bean的get方法拿到字符串再写入mysql中的字段会乱码,需要String string = xxx.get(),把get方法拿到的值传入到新的string中,在存入数据库就不会中文乱码了。

jpa的具体搭建情况可以参考项目 detectx 和 project(女仆管理系统),rm只是单纯地集成了hibernate4,因为已经集成了mybatis,又因为是个ssm项目,所以无法再集成jpa了。

关于 jpa/hibernate 的有选择性的更新这个功能,只能通过手动设定的方式实现,目前没有方法实现自动有选择性的更新,mybatis支持。

参考:

SpringBoot 2.1.1.RELEASE 集成JPA

Spring Data JPA 中findOne() 和 getOne()的区别

SpringData系列四 @Query注解及@Modifying注解

在Spring Data JPA 中使用Update Query更新实体类@DynamicUpdate,@DynamicInsert