SpringBoot JPA-Hibernate
Posted 袋子里的袋鼠
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot JPA-Hibernate相关的知识,希望对你有一定的参考价值。
1)pom.xml添加mysql,spring-data-jpa依赖
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId></dependency>
2)在application.properties文件中配置MySQL连接配置文件
########################################################
###datasource
########################################################
spring.datasource.url = jdbc:mysql://localhost:3306/test
spring.datasource.username = root
spring.datasource.password = root
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
3)在application.properties文件中配置JPA配置信息
########################################################
### Java Persistence Api
########################################################
# 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
4)测试
实体类:@Entity标注类上,进行实体类的持久化操作,当JPA检测到我们的实体类当中有@Entity 注解的时候,会在数据库中生成对应的表结构信息。使用@Id指定主键, 使用代码@GeneratedValue(strategy=GenerationType.AUTO) 指定主键的生成策略,mysql默认的是自增长,例:@Id @GeneratedValue(strategy=GenerationType.AUTO)private int id;//主键.
service接口:
public interface CatRepository extends CrudRepository<Cat, Integer>{}
service实现类:
@Service
public class CatService {
@Resource
private CatRepository catRepository;//service的接口
@Transactional//事务的绑定.
public void save(Cat cat){
catRepository.save(cat);
}
}
以上是关于SpringBoot JPA-Hibernate的主要内容,如果未能解决你的问题,请参考以下文章
SpringBoot入门到精通-SpringBoot自定义starter
最全面的SpringBoot教程——SpringBoot概述