步骤:

  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
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

springboot:使用JPA-Hibernate的更多相关文章

  1. springboot 集成 jpa/hibernate

    pom.xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId> ...

  2. Springboot对JPA的支持及使用

    目的: 1.springboot之jpa支持 2.Springboot+bootstrap界面版之增删改查及图片上传 springboot之jpa支持 导入相关pom依赖 <dependency ...

  3. SpringBoot之使用jpa/hibernate

    Springboot版本是2.1.3.RELEASE 1.依赖 List-1.1 <dependency> <groupId>org.springframework.boot& ...

  4. SpringBoot + Jpa(Hibernate) 架构基本配置

    1.基于springboot-1.4.0.RELEASE版本测试 2.springBoot + Hibernate + Druid + Mysql + servlet(jsp) 一.maven的pom ...

  5. Springboot+Atomikos+Jpa+Mysql实现JTA分布式事务

    1 前言 之前整理了一个spring+jotm实现的分布式事务实现,但是听说spring3.X后不再支持jotm了,jotm也有好几年没更新了,所以今天整理springboot+Atomikos+jp ...

  6. 带你搭一个SpringBoot+SpringData JPA的环境

    前言 只有光头才能变强. 文本已收录至我的GitHub仓库,欢迎Star:https://github.com/ZhongFuCheng3y/3y 不知道大家对SpringBoot和Spring Da ...

  7. 二、springboot使用jpa

    花了几天时间,好好看了看springboot的jpa部分,总结了常用的形式. 1.通过STS工具添加jpa的依赖项 要连mysql,测试的时候需要web,顺便添加了lombok不写set和get方法了 ...

  8. SpringBoot 中 JPA 的使用

    详细连接 简书https://www.jianshu.com/p/c14640b63653 新建项目,增加依赖 在 Intellij IDEA 里面新建一个空的 SpringBoot 项目.具体步骤参 ...

  9. Spring Boot + Jpa(Hibernate) 架构基本配置

    本文转载自:https://blog.csdn.net/javahighness/article/details/53055149 1.基于springboot-1.4.0.RELEASE版本测试 2 ...

  10. 第11章—使用对象关系映射持久化数据—SpringBoot+SpringData+Jpa进行查询修改数据库

    SpringBoot+SpringData+Jpa进行查询修改数据库 JPA由EJB 3.0软件专家组开发,作为JSR-220实现的一部分.但它又不限于EJB 3.0,你可以在Web应用.甚至桌面应用 ...

随机推荐

  1. OpenResty: 反向代理

    打开文件 注:我配置的是 443  <--> 8083 以下域名根据自己的修改 请自行重启,测试.

  2. Nothing to say

    1. This moment will nap, you will have a dream; but this moment study, you will interpret a dream.此刻 ...

  3. centos7 编译安装 haproxy1.8.20

    当前系统信息: [root@localhost ~]# cat /etc/os-release NAME="CentOS Linux" VERSION="7 (Core) ...

  4. C#】通过遍历IFrame访问页面元素

    最近在做一个小项目,期间需要用到C#去操作IE页面中的元素,实现自动填写表单并且提交的功能,想这网上关于这方面的东西肯定很多,于是开始在网上找资料. 在逆心的博客上找到些东西对自己帮助很大,原文链接: ...

  5. SharePoint - Another Way to Delete Site Collection

    I had created a site collection. But there is a problem of web-frontend server (I did not know when ...

  6. Typescript 学习 - 类

    class class 并不是一种新的数据结构,只是在函数原型基础上的语法糖 class People { hand: number; constructor(hand: number) { this ...

  7. Rancher 构建 CI/CD 自动化流程 - 动态配置 Jenkins-slave(二)

    一.说明 1.1 说明 前面介绍采用 Jenkinsfile + KubernetesPod.yaml 方式进行部署项目(Rancher 构建 CI/CD 自动化流程 - 动态配置 Jenkins-s ...

  8. SQL Server ----- 还原数据库,将另一台电脑上的数据库装在本机

    1.创建好数据库,记住安装位置,,和需要还原的数据库的位置 还原数据库的意思就是 根据创建的数据库,还原备份的数据库,如果数据库中没有数据库要新建数据库. 2.进来后如图 3.找你需要的还原数据库的位 ...

  9. SpringBoot 基础(一)

    目录 SpringBoot 基础(一) 一.简介 二.重要注解 三.基本应用开发 1. lombok的使用 2. SpringBoot 的参数传递 3. 对象参数校验 4. 静态资源 四.Spring ...

  10. for循环中的switch的break和continue作用范围

    for循环中的switch的break和continue作用范围 不空泛的讲理论了,上代码.看下面这个代码: #include <stdio.h> #include <stdlib. ...