美文网首页我爱编程
SpringBoot中的SpringDate-jpa与hiber

SpringBoot中的SpringDate-jpa与hiber

作者: 励志做一名老中医 | 来源:发表于2018-04-09 20:10 被阅读335次

1.最近在学习springboot,过程中看到了如何在springboot中使用hibernate, 学习中是说使用springdata-jpa-hibernate,其实我觉得不用这么负责  其实就是怎么在springboot中使用hibernate.


1. 在pom文件中进行依赖

2.配置文件中配置数据源与jpa的参数

########################################################

###datasource -- \u6307\u5b9amysql\u6570\u636e\u5e93\u8fde\u63a5\u4fe1\u606f.

########################################################

spring.datasource.url = jdbc:mysql://192.168.199.200:3306/dw_myself

spring.datasource.username = ceshi

spring.datasource.password = Ceshi123

spring.datasource.driverClassName = com.mysql.jdbc.Driver

spring.datasource.max-active=20

spring.datasource.max-idle=8

spring.datasource.min-idle=8

spring.datasource.initial-size=10

########################################################

### Java Persistence Api --  Spring jpa\u7684\u914d\u7f6e\u4fe1\u606f.

########################################################

# Specify the DBMS

spring.jpa.database = MYSQL

# Show or not log for each sql query

spring.jpa.show-sql = true

# Hibernate ddl auto (create, create-drop, update)

spring.jpa.hibernate.ddl-auto = update

# Naming strategy

#[org.hibernate.cfg.ImprovedNamingStrategy  #org.hibernate.cfg.DefaultNamingStrategy]

spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy

# stripped before adding them to the entity manager)

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

3.创建一个实体类,不需要先创建表,框架会将你创建的实体类生成一张表.

如果需要规定一下字段的属性,我们可以使用一下这些注解(在字段上使用,多个注解中间用空格隔开)

@GeneratedValue提供了主键的生成策略,@GeneratedValue注解有两个属性,分别是strategy和generator,其中generator属性的值是一个字符串,默认为"",其声明了主键生成器的名称(对应于同名的主键生成器@SequenceGenerator和@TableGenerator)

JPA为开发人员提供了四种主键生成策略,其被定义在枚举类GenerationType中,包括GenerationType.TABLE,GenerationType.SEQUENCE,GenerationType.IDENTITY和GenerationType.AUTO。下面分别介绍这四种主键生成策略。

具体每一种生成策略是怎样写的请参考JPA主键生成器和主键生成策略 - CSDN博客

而普通字段的属性则使用@column这个注解进行设置.具体的属性请参考JPA的Column注解总结 - CSDN博客

4. 创建数据层接口

在创建数据层接口时可以使用多种方式访问数据库;

    1.创建接口继承 CrudRepository接口.

            该接口给出了访问表的一些基本方法,接口实现一个Repository接口 该接口没有方法,作为一个表示接口存在.相当于使用@RepositoryDefinition注解, 该接口的作用是让spring管理该接口,将实体生成后放入ioc容器当中.

2.直接继承Repostitory接口.

    2.1直接继承Repostitory接口,是没有什么写好的方法的 所以需要你自己去创建访问方法,而且创建的方法的命名也是有要求的.

比如  以字段  aaa  为条件进行查询 方法名就是findByAaa.    

    2.2 如果使用自定义的sql那么就需要在方法上加入@query的注解

    使用方法与hibernate的hql语句相同.

3. 使用分页或者排序

继承PagingAndSortingRepository,类中存在两个框架提供的实体类 

1.sort 排序类

2.Pageable

相关文章

网友评论

    本文标题:SpringBoot中的SpringDate-jpa与hiber

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