美文网首页
springboot 使用jpa

springboot 使用jpa

作者: 瓢鳍小虾虎 | 来源:发表于2020-10-24 09:35 被阅读0次

首先创建项目中要选择的一些配置:

image.png image.png

项目中配置文件配置数据库连接参数和jpa配置

#数据库,启动项目需要通过配置连接数据库
spring.datasource.url=jdbc:mysql://localhost:3306/demo?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true

#数据库用户名和密码
spring.datasource.username=root
spring.datasource.password=xxxxxxxx

#mysql驱动类,com.mysql.cj.jdbc.Driver是mysql-connect-java6的,com.mysql.jdbc.Driver是mysql-connector-java5的
#使用前者需要指定serverTimezone,如果设定serverTimezone=UTC,会比中国时间早8个小时,可以配置serverTimezone=Shanghai
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

#配置自动更新,让表数据会跟随entity类的变化而变化
spring.jpa.properties.hibernate.hbm2ddl.auto=update

#sql方言
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect

#开启sql打印方便调试
spring.jpa.show-sql=true

#开启sql格式化方便展示
spring.jpa.properties.hibernate.format_sql=true

关联entity和数据库表:

1.idea连接数据库


image.png
image.png

2.idea支持jpa


添加jpa支持
image.png

完成后idea左边就会多出这样的菜单


image.png
关联上数据库
image.png
image.png

如果想使用jpa反向生成entity

先创建entity包


创建entity包
image.png
image.png

这时entity包中会多一个创建好的user实体类


image.png

repository:
创建repository并继承JpaRepository,常规单表操作不需要手动实现


image.png

如果需要自定义查找,比如根据name查询结果:


image.png

不使用框架反向生成entity,通过写实体类动态生成数据库表

image.png

只要启动application就会自动创建表


image.png

jpa增删改查###

jpaRepository自带方法:如果表中有对应数据就更新,没有则新增


image.png

jpa单表查询关键字拼凑方法###

在repository中可以根据以下规则自定义实现单表查询操作


image.png
image.png

相关文章

网友评论

      本文标题:springboot 使用jpa

      本文链接:https://www.haomeiwen.com/subject/vveumktx.html