SpringBoot之使用jpa/hibernate
Springboot版本是2.1.3.RELEASE
1、依赖
List-1.1
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.2</version>
</dependency>
2、项目整体结构
图2.1
bootstrap.yml内容如下,我们不需要手动创建数据库表,jpa/hiberate会自动会为我们创建的
server:
port: 9092
servlet:
context-path: /serviceB
spring:
application:
name: cat-service-b
datasource:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.jdbc.Driver
username: root
password: ******
url: jdbc:mysql://pig-mysql:3306/cat?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowMultiQueries=true
database: mysql
hibernate:
ddl-auto: update
naming:
physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
show-sql: true
properties:
hibernate:
format_sql: true
physical-strategy的值为org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy,那么当实体的属性为驼峰结构时,对应到数据库表的字段上,会用"_"隔开。
3、代码详解
List-3.1 BaseEntity的内容,所有的实体都要继承这个类
import lombok.Data;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import java.util.Date;
@Data
@MappedSuperclass
public class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Integer id;
/** 创建人 */
@CreatedBy
protected String creator;
/** 创建时间 */
@CreatedDate
protected Date createDate;
/** 更新时间,默认是当前时间 */
@LastModifiedDate
protected Date updateDate = new Date();
/** 状态 0 表示删除, 1表示可操作 */
protected Integer status = 1;
public BaseEntity() {
if (null == this.id && null == this.createDate) {
this.createDate = new Date();
}
}
}
List-3.2 User的内容
import lombok.Data;
import lombok.ToString;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import javax.persistence.Entity;
import javax.persistence.Table;
@Data
@ToString
@Entity
@Table(name = "cat_user")
@SQLDelete(sql = "update cat_user set status = 0 where id = ?")
@Where(clause = "status <> 0")
public class User extends BaseEntity{
private String name;
private Integer age;
}
List-3.3 UserRepository的内容
import com.mjduan.project.catserviceb.entity.User;
import org.springframework.data.repository.CrudRepository;
public interface UserRepository extends CrudRepository<User, Integer> {
}
List-3.4 UserController的内容
import com.mjduan.project.catserviceb.entity.User;
import com.mjduan.project.catserviceb.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.Optional;
@Slf4j
@RestController
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping(value = www.dasheng178.com"/queryUser/{id}")
public User queryUser(@PathVariable(value = "id") Integer id) {
log.info("查询用户,id={}", id);
Optional<User> optionalUser = userRepository.findById(id);
User user = optionalUser.isPresent() ? optionalUser.get() : null;
log.info("返回,{}", user);
return user;
}
@GetMapping(value = "/saveUser/{name}")
public User saveUser(@PathVariable(www.fengshen157.com/ value = "name") String name) {
log.info("新增用户,name={}", name);
User user = new User();
user.setAge(20);
user.setName(name);
User save = userRepository.save(user);
log.info("返回,{}", save);
return save;
}
}
4、验证
在浏览器地址栏中输入
List-4.1
#保存name为Tom的用户
http://localhost:9092/serviceB/saveUser/Tom
#查询Id为1的用户
http://localhost:9092/serviceB/queryUser/1
一些思考:
自动创建表结构,我们不需要手动去创建,我们修改实体的时候,系统会自动更新数据库中的表结构。
所有实体都继承BaseEntity,那么每个实体对应的数据库表,在创建日期、更新日期等共有属性都同一了,这样在一定程度上便于代码理解和系统维护。
5、Reference
Springboot配置mysql连接的部分配置参考:https://github.com/pristinecore/springbootsample/blob/master/springbootsample/src/main/resources/database.properties
格式化SQL输出的参考:https://www.yongshiyule178.com stackoverflow.com/questions/25720396/how-to-set-hibernate-format-sql-in-spring-boot
SpringBoot之使用jpa/hibernate的更多相关文章
- springboot 集成 jpa/hibernate
pom.xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId> ...
- SpringBoot + Jpa(Hibernate) 架构基本配置
1.基于springboot-1.4.0.RELEASE版本测试 2.springBoot + Hibernate + Druid + Mysql + servlet(jsp) 一.maven的pom ...
- javaweb各种框架组合案例(六):springboot+spring data jpa(hibernate)+restful
一.介绍 1.springboot是spring项目的总结+整合 当我们搭smm,ssh,ssjdbc等组合框架时,各种配置不胜其烦,不仅是配置问题,在添加各种依赖时也是让人头疼,关键有些jar包之间 ...
- 解决 Springboot Unable to build Hibernate SessionFactory @Column命名不起作用
问题: Springboot启动报错: Caused by: org.springframework.beans.factory.BeanCreationException: Error creati ...
- [读书笔记] 四、SpringBoot中使用JPA 进行快速CRUD操作
通过Spring提供的JPA Hibernate实现,进行快速CRUD操作的一个栗子~. 视图用到了SpringBoot推荐的thymeleaf来解析,数据库使用的Mysql,代码详细我会贴在下面文章 ...
- SpringBoot整合StringData JPA
目录 SpringBoot整合StringData JPA application.yml User.class UserRepository.java UserController SpringBo ...
- SpringBoot整合SpringData JPA入门到入坟
首先创建一个SpringBoot项目,目录结构如下: 在pom.xml中添加jpa依赖,其它所需依赖自行添加 <dependency> <groupId>org.springf ...
- Spring Boot + Jpa(Hibernate) 架构基本配置
本文转载自:https://blog.csdn.net/javahighness/article/details/53055149 1.基于springboot-1.4.0.RELEASE版本测试 2 ...
- Springboot spring data jpa 多数据源的配置01
Springboot spring data jpa 多数据源的配置 (说明:这只是引入了多个数据源,他们各自管理各自的事务,并没有实现统一的事务控制) 例: user数据库 global 数据库 ...
随机推荐
- 在linux环境下为eclipse配置jdk以及Tomcat服务(附图解详细步骤)
环境:jdk8,Tomcat7,eclipse 需要先在linux上安装好对应的软件及java环境,如果还没有安装的,可以先去看我之前写的两篇博客:ubuntu/linux中安装Tomcat(附图解详 ...
- Java中 static、final和static final的特点及区别
final: final可以修饰:属性,方法,类,局部变量(方法中的变量) final修饰的属性的初始化可以在编译期,也可以在运行时,初始化后不能被改变. final修饰的属性跟具体对象有关,在运行期 ...
- VMware vCenter Converter迁移Linux系统虚拟机
(一)简介VMware vCenter Converter Standalone,是一种用于将虚拟机和物理机转换为 VMware 虚拟机的可扩展解决方案.此外,还可以在 vCenter Server ...
- Python函数初识
一.函数是什么 计算机语言中的函数是类比于数学中的函数演变来的,但是又有所不同.前面的知识中我们学会了运用基础语法(列表.字典)和流程控制语句貌似也能处理一些复杂的问题,但是相对于相似的大量重复性 ...
- rev命令详解
基础命令学习目录首页 rev命令将文件中的每行内容以字符为单位反序输出,即第一个字符最后输出,最后一个字符最先输出,依次类推. #cat a.txt wo shi mcw, nihao how do ...
- umount命令详解
基础命令学习目录首页 umount 用来卸载设备 -a:卸除/etc/mtab中记录的所有文件系统: -h:显示帮助: -n:卸除 ...
- AJAX(Asynchronous JavaScript and XML)学习笔记
基本概念: 1.AJAX不是一种新的编程语言,而是一种使用现有标准的新方法. 2.AJAX最大的优点是在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页内容,用于创建快速动态网页(传统网页如 ...
- 探路者 FInal冲刺中间产物
版本控制 https://git.coding.net/clairewyd/toReadSnake.git 版本控制报告 http://www.cnblogs.com/linym762/p/79976 ...
- Alpha版本测试文档
概述 本次测试主要是为了测试是否有导致崩溃的bug,验证是否符合软件基本需求. 测试环境 硬件测试:安卓系统手机,安卓平板. 测试人员 赖彦谕,金哉仁. 实际进度 2015/11/6 – 2015/1 ...
- 奔跑吧DKY——团队Scrum冲刺阶段博客汇总
第一周:团队展示 团队选题 需求规格说明书 第二周:完善需求规格说明书.制定团队编码规范.通过团队项目数据库设计 奔跑吧DKY--团队Scrum冲刺阶段-Day 1-领航 奔跑吧DKY--团队Scru ...