spring boot学习教程(5):spring boot hibernate 配置

本文介绍如何在SpringBoot项目中使用Hibernate实现数据持久化。通过配置pom.xml引入所需依赖,并设置application.properties文件来连接MySQL数据库。示例展示了实体类如何通过JPA注解实现自动表创建。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在说具体如何在spring boot 使用Hibernate前,先抛装引玉些知识点?什么是JPA呢?

JPA全称Java Persistence API.JPA通过JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。

接下里就说本文章重点了,那么怎么操作呢?只需要如下配置就可以了?

pom.xml配置:
dependency>
mysql
mysql-connector-java



org.springframework.boot
spring-boot-starter-data-jpa

application.properties配置:

#

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

#

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

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

那么就可以使用Hibernate带来的好处了,在实体类注解@Entity就会自动进行表的DDL操作了。

我们在com.kfit.test.bean.Demo 中加入注解:@Entity
@Entity//加入这个注解,Demo就会进行持久化了,在这里没有对@Table进行配置,请自行配置。
publicclass Demo {
@Id @GeneratedValue
private long id;//主键.
private String name;//测试名称.
//其它代码省略.

这时候运行就会在数据库看到demo表了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值