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


项目中配置文件配置数据库连接参数和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连接数据库


2.idea支持jpa


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

关联上数据库


如果想使用jpa反向生成entity
先创建entity包



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

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

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

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

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

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

jpa单表查询关键字拼凑方法###
在repository中可以根据以下规则自定义实现单表查询操作


网友评论