springboot:使用JPA-Hibernate

Spring Boot整合JPA实战
本文详细介绍如何在Spring Boot项目中整合JPA实现数据库操作,包括配置MySQL连接、定义实体类、创建Repository接口及Service层,并通过RESTful API提供增删查功能。

步骤:

  1. 在pom.xml文件中添加mysql,spring-data-jpa的依赖。

      <!-- 添加mysql数据库驱动依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
      </dependency>
      <!-- 添加spring-data-jpa依赖 -->
      <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-data-jpa</artifactId>
      </dependency>

2在application.properties文件中配置mysql链接属性。

在res/main/resources下创建一个application.properties文件:

  1. 在application.propertices文件中配置JPA配置信息;

  ##########################################
###datasource--指定mysql数据库连接信息
###spring.datasource.url:mysql地址
###spring.datasource.user:数据库用户名
###spring.datasource.password:数据库密码
###spring.datasource.driverClassName:对应数据库驱动
###spring.datasource.max-active:指定连接池中最大的活跃连接数
###spring.datasource.max-idle:指定连接池最大的空闲连接数量.
###spring.datasource.min-idle:指定必须保持连接的最小值(For DBCP and Tomcat connection pools)
###spring.datasource.initial-size:指定启动连接池时,初始建立的连接数量
###
###其他信息总结:
###spring.dao.exceptiontranslation.enabled是否开启PersistenceExceptionTranslationPostProcessor,默认为true
###spring.datasource.abandon-when-percentage-full设定超时被废弃的连接占到多少比例时要被关闭或上报
###spring.datasource.allow-pool-suspension使用Hikari pool时,是否允许连接池暂停,默认为: false
###spring.datasource.alternate-username-allowed是否允许替代的用户名.
###spring.datasource.auto-commit指定updates是否自动提交.
###spring.datasource.catalog指定默认的catalog.
###spring.datasource.commit-on-return设置当连接被归还时,是否要提交所有还未完成的事务
###spring.datasource.connection-init-sql指定连接被创建,再被添加到连接池之前执行的sql.
###spring.datasource.connection-init-sqls使用DBCP connection pool时,指定初始化时要执行的sql
###spring.datasource.connection-properties.[key]在使用DBCP connection pool时指定要配置的属性
###spring.datasource.connection-test-query指定校验连接合法性执行的sql语句
###spring.datasource.connection-timeout指定连接的超时时间,毫秒单位.
###spring.datasource.continue-on-error在初始化数据库时,遇到错误是否继续,默认false
###spring.datasource.data指定Data (DML)脚本
###spring.datasource.data-source-class-name指定数据源的全限定名.
###spring.datasource.data-source-jndi指定jndi的地址
###spring.datasource.data-source-properties.[key]使用Hikari connection pool时,指定要设置的属性
###spring.datasource.db-properties使用Tomcat connection pool,指定要设置的属性
###spring.datasource.default-auto-commit是否自动提交.
###spring.datasource.default-catalog指定连接默认的catalog.
###spring.datasource.default-read-only是否设置默认连接只读.
###spring.datasource.default-transaction-isolation指定连接的事务的默认隔离级别.
###spring.datasource.driver-class-name指定driver的类名,默认从jdbc url中自动探测.
###spring.datasource.fair-queue是否采用FIFO返回连接.
###spring.datasource.health-check-properties.[key]使用Hikari connection pool时,在心跳检查时传递的属性
###spring.datasource.idle-timeout指定连接多久没被使用时,被设置为空闲,默认为10ms
###spring.datasource.ignore-exception-on-pre-load当初始化连接池时,是否忽略异常.
###spring.datasource.init-sql当连接创建时,执行的sql
###spring.datasource.initial-size指定启动连接池时,初始建立的连接数量
###spring.datasource.initialization-fail-fast当创建连接池时,没法创建指定最小连接数量是否抛异常
###spring.datasource.initialize指定初始化数据源,是否用data.sql来初始化,默认: true
###spring.datasource.isolate-internal-queries指定内部查询是否要被隔离,默认为false
###spring.datasource.jdbc-interceptors使用Tomcat connection pool时,指定jdbc拦截器,分号分隔
###spring.datasource.jdbc-url指定JDBC URL.
###spring.datasource.jmx-enabled是否开启JMX,默认为: false
###spring.datasource.jndi-name指定jndi的名称.
###spring.datasource.leak-detection-threshold使用Hikari connection pool时,多少毫秒检测一次连接泄露.
###spring.datasource.log-abandoned使用DBCP connection pool,是否追踪废弃statement或连接,默认为: false
###spring.datasource.log-validation-errors当使用Tomcat connection pool是否打印校验错误.
###spring.datasource.login-timeout指定连接数据库的超时时间.
###spring.datasource.max-age指定连接池中连接的最大年龄
###spring.datasource.max-lifetime指定连接池中连接的最大生存时间,毫秒单位.
###spring.datasource.max-open-prepared-statements指定最大的打开的prepared statements数量.
###spring.datasource.max-wait指定连接池等待连接返回的最大等待时间,毫秒单位.
###spring.datasource.maximum-pool-size指定连接池最大的连接数,包括使用中的和空闲的连接.
###spring.datasource.min-evictable-idle-time-millis指定一个空闲连接最少空闲多久后可被清除.
###spring.datasource.min-idle指定必须保持连接的最小值(For DBCP and Tomcat connection pools)
###spring.datasource.minimum-idle指定连接维护的最小空闲连接数,当使用HikariCP时指定.
###spring.datasource.name指定数据源名.
###spring.datasource.num-tests-per-eviction-run指定运行每个idle object evictor线程时的对象数量
###spring.datasource.password指定数据库密码.
###spring.datasource.platform指定schema要使用的Platform(schema-${platform}.sql),默认为: all
###spring.datasource.pool-name指定连接池名字.
###spring.datasource.pool-prepared-statements指定是否池化statements.
###spring.datasource.propagate-interrupt-state在等待连接时,如果线程被中断,是否传播中断状态.
###spring.datasource.read-only当使用Hikari connection pool时,是否标记数据源只读
###spring.datasource.register-mbeans指定Hikari connection pool是否注册JMX MBeans.
###spring.datasource.remove-abandoned指定当连接超过废弃超时时间时,是否立刻删除该连接.
###spring.datasource.remove-abandoned-timeout指定连接应该被废弃的时间.
###spring.datasource.rollback-on-return在归还连接时,是否回滚等待中的事务.
###spring.datasource.schema指定Schema (DDL)脚本.
###spring.datasource.separator指定初始化脚本的语句分隔符,默认: ;
###spring.datasource.sql-script-encoding指定SQL scripts编码.
###spring.datasource.suspect-timeout指定打印废弃连接前的超时时间.
###spring.datasource.test-on-borrow当从连接池借用连接时,是否测试该连接.
###spring.datasource.test-on-connect创建时,是否测试连接
###spring.datasource.test-on-return在连接归还到连接池时是否测试该连接.
###spring.datasource.test-while-idle当连接空闲时,是否执行连接测试.
###spring.datasource.time-between-eviction-runs-millis指定空闲连接检查、废弃连接清理、空闲连接池大小调整之间的操作时间间隔
###spring.datasource.transaction-isolation指定事务隔离级别,使用Hikari connection pool时指定
###spring.datasource.url指定JDBC URL.
###spring.datasource.use-disposable-connection-facade是否对连接进行包装,防止连接关闭之后被使用.
###spring.datasource.use-equals比较方法名时是否使用String.equals()替换==.
###spring.datasource.use-lock是否对连接操作加锁
###spring.datasource.username指定数据库名.
###spring.datasource.validation-interval指定多少ms执行一次连接校验.
###spring.datasource.validation-query指定获取连接时连接校验的sql查询语句.
###spring.datasource.validation-query-timeout指定连接校验查询的超时时间.
###spring.datasource.validation-timeout设定连接校验的超时时间,当使用Hikari connection pool时指定
###spring.datasource.validator-class-name用来测试查询的validator全限定名.
###spring.datasource.xa.data-source-class-name指定数据源的全限定名.
###spring.datasource.xa.properties指定传递给XA data source的属性
###spring.datasource.url=jdbc:mysql://localhost:3306/test?user=root&password=root&useUnicode=true&characterEncoding=UTF8
##########################################
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
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
##########################################
##SPring JPA配置信息
###spring.jpa.database指定目标数据库.
###spring.jps.show-sq:是否显示sql语句
###spring.jpa.hibernate.ddl-auto指定DDL mode (none, validate, update, create, create-drop). 当使用内嵌数据库时,默认是create-drop,否则为none.
###spring.jpa.hibernate.naming-strategy指定命名策略.
###其他:
###spring.jpa.database-platform指定目标数据库的类型.
###spring.jpa.generate-ddl是否在启动时初始化schema,默认为false
###spring.jpa.hibernate.ddl-auto指定DDL mode (none, validate, update, create, create-drop). 当使用内嵌数据库时,默认是create-drop,否则为none.
###spring.jpa.hibernate.naming-strategy指定命名策略.
###spring.jpa.open-in-view是否注册OpenEntityManagerInViewInterceptor,绑定JPA EntityManager到请求线程中,默认为: true
###spring.jpa.properties添加额外的属性到JPA provider.
###spring.jpa.show-sql是否开启sql的log,默认为: false
##########################################
spring.jpa.database = MYSQL
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.freemarker.charset=UTF-8 
  1. 编写测试案例;

(1). 创建实体类Demo

package com.zhaolixiang.spring_boot1.demo.bean;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * 创建了一个实体类。
 * 
 * 如何持久化呢?
 * 
 * 1、使用@Entity进行实体类的持久化操作,当JPA检测到我们的实体类当中有
 * 
 * @Entity 注解的时候,会在数据库中生成对应的表结构信息。
 * 
 * 
 * 如何指定主键以及主键的生成策略?
 * 
 * 2、使用@Id指定主键.
 * 
 * 
 * 
 * @author Angel -- 守护天使
 * @version v.0.1
 * @date 2016年12月17日
 */
@Entity
@Table(name="cat")
public class Cat {
    
    /**
     * 使用@Id指定主键.
     * 
     * 使用代码@GeneratedValue(strategy=GenerationType.AUTO)
     * 指定主键的生成策略,mysql默认的是自增长。
     * 
     */
    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;//主键.
    
    private String catName;//姓名. cat_name
    
    private int catAge;//年龄. cat_age;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getCatName() {
        return catName;
    }

    public void setCatName(String catName) {
        this.catName = catName;
    }

    public int getCatAge() {
        return catAge;
    }

    public void setCatAge(int catAge) {
        this.catAge = catAge;
    }
    
    
}

(2). 创建jpa repository接口操作持久化(CrudREpository)

package com.zhaolixiang.spring_boot1.demo.repository;

import org.springframework.data.repository.CrudRepository;

import com.zhaolixiang.spring_boot1.demo.bean.Cat;

public interface CatRepository  extends CrudRepository<Cat, Integer>{

}

(3). 创建service类

package com.zhaolixiang.spring_boot1.demo.service;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.springframework.stereotype.Service;

import com.zhaolixiang.spring_boot1.demo.bean.Cat;
import com.zhaolixiang.spring_boot1.demo.repository.CatRepository;

@Service
public class CatService {
    
    @Resource
    private CatRepository catRepository;
    /**
     * save,update,delete方法需要绑定事物
     * 使用@Transactional进行事物绑定
     */
    //保存数据
    @Transactional
    public void save(Cat cat) {
        catRepository.save(cat);
    }
    //删除数据
    @Transactional
    public void delete(int id) {
        catRepository.delete(id);
    }
     //查询数据
    @Transactional
     public Iterable<Cat> getAll() {
         return catRepository.findAll();
        
    }
    

}

(4). 创建restfil请求类

package com.zhaolixiang.spring_boot1.demo.controller;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.zhaolixiang.spring_boot1.demo.bean.Cat;
import com.zhaolixiang.spring_boot1.demo.service.CatService;


@RestController
@RequestMapping("/cat")
public class CatController {
    
    @Resource
    private CatService catService;
    
    @RequestMapping("/save")
    public String save(){
        Cat cat = new Cat();
        cat.setCatName("jack");
        cat.setCatAge(3);
        catService.save(cat);
        return "save ok.";
    }
    
    @RequestMapping("/delete")
    public String delete(){
        catService.delete(1);
        return "delete ok";
    }
    
    @RequestMapping("/getAll")
    public Iterable<Cat> getAll(){
        return catService.getAll();
    }
    
}

(5). 测试

  1. 总结;

个人在按照上面步骤操作时,demo并没有在数据库中定义表结构,最后发现,Demo类文件不在App.class最在的文件目录中!!!

个人在按照上面步骤操作时,突然读取不到数据库的信息,也不报错,到后来才发现数据库调用错了,本来调用服务器来测试的,不知道什么时候调用本地数据库了,本地数据库对应表里没有信息,所有一直调用不到,大一呀!!!

数据库test不会自动生成,需要首先自己创建。



作者:AiPuff
链接:http://www.jianshu.com/p/4d1844a5680c
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

转载于:https://www.cnblogs.com/gyadmin/p/8084430.html

<think> 我们正在讨论Spring配置文件中关于MongoDB和JPA的配置。用户提供的配置如下: ```yaml spring: data: mongodb: uri: mongodb://localhost:27017/user jpa: hibernate: ddl-auto: update show-sql: true properties: hibernate: dialect: org.hibernate.dialect.MySQL8Dialect ``` 用户想确认这个配置是否正确。我们需要分别检查MongoDB和JPA的配置。 ### 1. MongoDB配置分析 - **配置项**:`spring.data.mongodb.uri` - **值**:`mongodb://localhost:27017/user` - **分析**:这个配置指定了MongoDB的连接URI。URI的格式为:`mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]` - 本例中:`localhost:27017`是主机和端口,`/user`表示数据库名称为`user`。 - 这是MongoDB连接的标准格式,配置正确。 ### 2. JPA配置分析 - **配置项**:`spring.jpa` - `hibernate.ddl-auto: update`:Hibernate在启动时根据实体类自动更新数据库表结构(如新增字段、修改字段等)。这是常用配置,正确。 - `show-sql: true`:在控制台输出SQL语句,便于调试,正确。 - `properties.hibernate.dialect: org.hibernate.dialect.MySQL8Dialect`:指定Hibernate使用MySQL8的方言。这确保了Hibernate生成的SQL语法适用于MySQL8。 ### 3. 潜在问题 - **混合使用MongoDB和JPA**:注意,MongoDB是非关系型数据库,而JPAHibernate)是关系型数据库的ORM框架。如果同一个项目同时使用两者,通常意味着项目同时操作两种数据库(如MySQL和MongoDB)。需要确保: 1. 关系型数据库(如MySQL)的数据源配置是否缺失? - 当前配置中没有出现`spring.datasource`(如URL、用户名、密码等)。如果项目需要同时使用JPA操作MySQL,则必须补充数据源配置。 2. 如果没有关系型数据库操作需求,则JPA配置是多余的,可以移除。 ### 结论 - **若项目同时使用MySQL和MongoDB**:当前配置缺少MySQL数据源(`spring.datasource`)的必填项(url, username, password等),需补充完整。例如: ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/your_db?useSSL=false username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver data: mongodb: uri: mongodb://localhost:27017/user jpa: # ... 原有jpa配置 ``` - **若项目仅使用MongoDB**:则JPA配置应全部移除,避免干扰。 - **若项目仅使用MySQL**:则MongoDB配置应移除。 ### 配置修正建议 根据实际需求选择: - **双数据库配置示例**: ```yaml spring: # 关系型数据库配置(MySQL) datasource: url: jdbc:mysql://localhost:3306/my_sql_db?characterEncoding=utf8 username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver # MongoDB配置 data: mongodb: uri: mongodb://localhost:27017/user # JPA配置 jpa: hibernate: ddl-auto: update show-sql: true properties: hibernate: dialect: org.hibernate.dialect.MySQL8Dialect ``` - **仅MongoDB配置示例**: ```yaml spring: data: mongodb: uri: mongodb://localhost:27017/user # 删除所有jpa配置 ``` ### 验证方法 启动Spring Boot应用,观察日志: 1. 若双数据库配置正确: - 应看到MySQL连接成功日志 - 应看到MongoDB连接成功日志 2. 若缺少数据源配置,启动时会报错: > `Failed to configure a DataSource: 'url' attribute is not specified...` 请根据项目实际需求调整配置。 §§相关问题§§ 1. 如何在Spring Boot中同时配置MySQL和MongoDB? 2. Spring Data JPA和Spring Data MongoDB如何避免配置冲突? 3. Hibernate的ddl-auto有哪些可选值?分别代表什么含义? </think> 根据您的配置内容,我将分析 MongoDB 和 JPA 的配置正确性: ```yaml spring: data: mongodb: uri: mongodb://localhost:27017/user # MongoDB连接配置 jpa: # JPA配置部分 hibernate: ddl-auto: update show-sql: true properties: hibernate: dialect: org.hibernate.dialect.MySQL8Dialect ``` ### 一、配置分析结论 1. **MongoDB 配置正确 ✅** `spring.data.mongodb.uri` 格式符合标准,指向本地 MongoDB 的 `user` 数据库: ```yaml uri: mongodb://localhost:27017/user # 协议://主机:端口/数据库名 ``` 2. **JPA 配置部分正确但有冲突 ️** - `ddl-auto: update` 和 `show-sql: true` 是有效的 JPA/Hibernate 配置 - **问题**:指定了 MySQL 方言但未配置 MySQL 数据源 ```yaml dialect: org.hibernate.dialect.MySQL8Dialect # 需要MySQL数据源支持 ``` ### 二、配置冲突图解 ```mermaid graph LR A[MongoDB配置] --> B[非关系型数据库] C[JPA配置] --> D[关系型数据库ORM] D --> E[需要MySQL数据源] E --> F[缺失spring.datasource配置] ``` ### 三、修正建议 1. **方案一:仅用 MongoDB(移除 JPA 配置)** ```yaml spring: data: mongodb: uri: mongodb://localhost:27017/user # 删除所有jpa配置 ``` 2. **方案二:同时使用 MongoDB + MySQL(补充数据源)** ```yaml spring: datasource: # 添加MySQL数据源 url: jdbc:mysql://localhost:3306/your_db username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver data: mongodb: uri: mongodb://localhost:27017/user jpa: hibernate: ddl-auto: update show-sql: true ``` ### 四、配置验证方法 1. **启动应用检查日志**: - 正确日志:`Connected to MongoDB at localhost:27017` - 错误日志:`Failed to obtain JDBC Connection`(如果未配置MySQL数据源但保留JPA) 2. **测试脚本**: ```java @SpringBootTest class ConfigTest { @Autowired(required = false) private MongoTemplate mongoTemplate; // MongoDB操作模板 @Test void testMongoConnection() { assertNotNull(mongoTemplate); // 验证MongoDB配置生效 } } ``` > **关键原则**:JPA 和 MongoDB 配置可共存,但 JPA 必须搭配关系型数据库(如 MySQL)的数据源[^1]。若只需 MongoDB,应删除所有 `spring.jpa` 配置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值