springboot配置jpa

  配置方式

  pom依赖

  org.springframework.boot

  spring-boot-starter-aop

  application.xml配置

  #jpa配置

  spring.jpa.properties.hibernate.hbm2ddl.auto=update

  spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect

  spring.jpa.show-sql= true

  spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

  需要注意的是最后一行,用来定义命名策略,如果不设置,会使用默认的命名策略,比如建表时,会将有驼峰命名的转换为全小写,并用横线分割如:实体类名:userCommon,映射到表名就是user-common

  使用方式

  使用jpa有两种方式,一种是使用注解,另外一种是使用配置文件,这两种都可以实现,但是推荐使用注解,因为这种方式更加的简洁,且是主流趋势,下面主要介绍注解的方式。

  在需要映射的实体类添加如下注解

  @Entity :表明该类是一个实体类,添加了该注解后,才能被jpa扫描到

  @Table:可以自定义表名

  我们需要知道的是,上面两行注解就已经完成了jpa的映射,声明为实体类后,该类里面的属性默认都会进行映射到数据库,但是默认的往往是不符合我们的要求的,比如,命名、长度、主键、索引都是需要自己指定的,因此下面介绍一些常用的注解

  扩展注解

  在属性添加注解

  主键:

  @Id:一般用来声明主键

  @GeneratedValue(strategy=GenerationType.IDENTITY):设置主键为自增

  普通属性:无锡妇科检查医院 http://www.87554006.com/

  @column:可以自定义列名或者定义其他的数据类型

  比如@column(name=“content”, columnDefinition = “longtext”)

  @Transient:不进行数据库的映射,类似于排除

  页面直接得到格式化类型的值,主要针对日期类型

  @Temporal(TemporalType.DATE):如1994-05-06

  @Temporal(TemporalType.TIME):20:46:13

  @Temporal(TemporalType.TIMESTAMP):1994-05-06 20:46:13

  唯一索引

  @Table(name = “表名”, uniqueConstraints = {

  @UniqueConstraint(name = “索引名称”, columnNames = {“字段1”,“字段2”})

  }),

  表加index索引

  @Table(name = “表名”,indexes = {

  @Index(name = “索引名称”, columnList = “字段名”)

  })

  数据库初始化

  对数据库的初始化往往也是经常用到的,我们创建的数据库一般都需要一些初始化的数据,配置方式如下

  增加application.properties配置文件属性

  spring.datasource.data=classpath:database/data.sql

  spring.datasource.sql-script-encoding=utf-8

  spring.datasource.initialization-mode=ALWAYS

  创建data.sql文件,在项目启动的时候就会执行该sql文件,如果项目的数据已经被初始化,那么可以将最后一行的属性ALWAYS改为NEVER


猜你喜欢

转载自blog.51cto.com/14503791/2437036
今日推荐