SpringData JPA示例
1. 添加pom
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</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>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version><!--$NO-MVN-MAN-VER$-->
</dependency>
<!-- swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
<!-- 开发者工具,当classpath下有文件更新自动触发应用重启 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.2.Final</version>
</dependency>
<!-- 使用缓存 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
</dependencies>
2. db链接设置 application.properties
spring.jpa.properties.hibernate.hbm2ddl.auto是hibernate的配置属性,其主要作用是:自动创建、更新、验证数据库表结构。该参数的几种配置如下:
Ø create:每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,哪怕两次没有任何改变也要这样执行,这就是导致数据库表数据丢失的一个重要原因。
Ø create-drop:每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。
Ø update:最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时根据model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等应用第一次运行起来后才会。
Ø validate:每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值。
Ø none: 启动时不做任何操作
#springfox.documentation.swagger.v2.path=/api-docs
#server.contextPath=/v2
server.port=8080
swagger.enable=true
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT&useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=1234
#只会执行ddl
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jackson.serialization.indent_output=true
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
3. DDL
dropdatabaseifexists mybatis;
createdatabase mybatis;
use mybatis;
createtablemybatis.CUSTOMERS (
ID bigint auto_increment notnull,
NAMEvarchar(15) notnull,
EMAIL varchar(128) ,
PASSWORDvarchar(8) ,
PHONE int ,
ADDRESS varchar(255),
SEX char(1) ,
IS_MARRIED bit,
DESCRIPTION text,
IMAGE blob,
BIRTHDAY date,
REGISTERED_TIME timestamp,
primarykey (ID)
);
INSERTINTOmybatis.CUSTOMERS (NAME,PHONE,ADDRESS) VALUES ('老赵', '123456' , 'address 1');
INSERTINTOmybatis.CUSTOMERS (NAME,PHONE,ADDRESS) VALUES ('老王', '654321' , 'address 2');
会自动执行DDL
4. 配置SwaggerConfig
5. 使用jpa生成Customers实体
注意:需要在自增的id get方法上加上@GeneratedValue(strategy =GenerationType.AUTO)
@Id
@Column(name = "ID", unique = true, nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
returnthis.id;
}
6. 生产CustomersJpaRepository和CustomersRepository
注意:sql里的表名必须和对象名完全一致,包括大小写
package com.example.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.domain.Customers;
publicinterface CustomersJpaRepository extends JpaRepository<Customers,Long>{
}
package com.example.repository;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.query.Param;
import com.example.domain.Customers;
//注意:sql里的表名必须和对象名完全一致,包括大小写
publicinterface CustomersRepository extends Repository<Customers,Long>{
@Query(value = "fromCustomers o where id=(select max(id) from Customers p)")
public Customers getCustomersByMaxId();
@Query(value = "fromCustomers o where o.name=?1 and o.phone=?2")
public List<Customers> queryParams1(String name, Integer phone);
@Query(value = "fromCustomers o where o.name=:name and o.phone=:phone")
public List<Customers> queryParams2(@Param("name")String name, @Param("phone")Integer phone);
@Query(value = "fromCustomers o where o.name like %?1%")
public List<Customers> queryLike1(String name);
@Query(value = "fromCustomers o where o.name like %:name%")
public List<Customers> queryLike2(@Param("name")String name);
@Query(nativeQuery = true, value = "select count(1) from Customers o")
publiclong getCount();
}
Repository:是SpringData的一个核心接口,它不提供任何方法,开发者需要在自己定义的接口中声明需要的方法。
CrudRepository:继承Repository,提供增删改查方法,可以直接调用。
PagingAndSortingRepository:继承CrudRepository,具有分页查询和排序功能(本类实例)
JpaRepository:继承PagingAndSortingRepository,针对JPA技术提供的接口
JpaSpecificationExecutor:可以执行原生SQL查询
继承不同的接口,有两个不同的泛型参数,他们是该持久层操作的类对象和主键类型。
7. 配置customersService并且加缓存
package com.example.service;
import java.util.List;
import org.springframework.data.repository.query.Param;
import com.example.domain.Customers;
publicinterface CustomersService {
public Customers getCustomersByMaxId();
public List<Customers> queryParams1(String name, Integer phone);
public List<Customers> queryParams2(@Param("name")String name, @Param("phone")Integer phone);
public List<Customers> queryLike1(String name);
public List<Customers> queryLike2(@Param("name")String name);
publiclong getCount();
public List<Customers> findAll();
public Customers findOne(Long id);
publicvoid delete(longid);
publicvoid deleteAll();
publicvoid save(List<Customers> entities);
publicvoid save(Customers entity);
}
package com.example.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
importorg.springframework.transaction.annotation.Transactional;
import com.example.domain.Customers;
import com.example.repository.CustomersJpaRepository;
import com.example.repository.CustomersRepository;
import com.example.service.CustomersService;
@Service(value = "customersService")
@Transactional
@CacheConfig(cacheNames = "customers")
publicclass CustomersServiceImpl implements CustomersService{
@Autowired
private CustomersRepository customersRepository;
@Autowired
private CustomersJpaRepository customersJpaRepository;
@Override
@Cacheable
public Customers getCustomersByMaxId() {
returncustomersRepository.getCustomersByMaxId();
}
@Override
@Cacheable
public List<Customers> queryParams1(String name, Integer phone) {
returncustomersRepository.queryParams1(name, phone);
}
@Override
@Cacheable
public List<Customers> queryParams2(String name, Integer phone) {
return customersRepository.queryParams2(name, phone);
}
@Override
@Cacheable
public List<Customers> queryLike1(String name) {
return customersRepository.queryLike1(name);
}
@Override
@Cacheable
public List<Customers> queryLike2(String name) {
return customersRepository.queryLike2(name);
}
@Override
@Cacheable
publiclong getCount() {
return customersRepository.getCount();
}
@Override
@Cacheable
public List<Customers> findAll() {
returncustomersJpaRepository.findAll();
}
@Override
@Cacheable
public Customers findOne(Long id) {
returncustomersJpaRepository.findOne(id);
}
@Override
@Cacheable
publicvoid deleteAll(){
customersJpaRepository.deleteAll();
}
@Override
@Cacheable
publicvoid delete(longid){
customersJpaRepository.delete(id);
}
@Override
@Cacheable
publicvoid save(List<Customers> entities){
customersJpaRepository.save(entities);
}
@Override
@Cacheable
publicvoid save(Customers entity){
customersJpaRepository.save(entity);
}
}
8. 配置CustomersController
package com.example.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.example.domain.Customers;
import com.example.service.CustomersService;
@RestController
@RequestMapping("/customers")
publicclass CustomersController {
@Autowired
private CustomersService customersService;
@RequestMapping(value="getCustomersByMaxId", method=RequestMethod.GET)
public Customers getCustomersByMaxId(){
returncustomersService.getCustomersByMaxId();
}
@RequestMapping(value="queryParams1/{name}/{phone}", method=RequestMethod.POST)
public List<Customers> queryParams1(String name, Integer phone){
returncustomersService.queryParams1(name, phone);
}
//http://localhost:8080/customers/queryParams2/%7Bname%7D/%7Bphone%7D?name=老赵&phone=123456
@RequestMapping(value="queryParams2/{name}/{phone}", method=RequestMethod.POST)
public List<Customers> queryParams2(@Param("name")String name, @Param("phone")Integer phone){
returncustomersService.queryParams2(name, phone);
}
@RequestMapping(value="queryLike1/{name}", method=RequestMethod.POST)
public List<Customers> queryLike1(String name){
returncustomersService.queryLike1(name);
}
//http://localhost:8080/customers/queryLike2/%7Bname%7D?name=老王
@RequestMapping(value="queryLike2/{name}", method=RequestMethod.POST)
public List<Customers> queryLike2(@Param("name")String name){
returncustomersService.queryLike2(name);
}
@RequestMapping(value="getCount", method=RequestMethod.GET)
publiclong getCount(){
returncustomersService.getCount();
}
@RequestMapping(value="findAll", method=RequestMethod.GET)
public List<Customers> findAll() {
returncustomersService.findAll();
}
@RequestMapping(value="findOne", method=RequestMethod.POST)
public Customers findOne(Long id) {
returncustomersService.findOne(id);
}
@RequestMapping(value="deleteAll", method=RequestMethod.GET)
publicvoid deleteAll(){
customersService.deleteAll();
}
@RequestMapping(value="delete", method=RequestMethod.POST)
publicvoid delete(longid){
customersService.delete(id);
}
@RequestMapping(value="saveAll", method=RequestMethod.POST)
publicvoid save(List<Customers> entities){
customersService.save(entities);
}
@RequestMapping(value="save", method=RequestMethod.POST)
publicvoid save(Customers entity){
customersService.save(entity);
}
}
9. 配置启动项DemoApplication
package com.example;
import org.springframework.boot.SpringApplication;
importorg.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching
publicclass DemoApplication {
publicstaticvoid main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
//to visithttp://localhost:8080/swagger-ui.html
}
转载于:https://www.cnblogs.com/xiang--liu/p/9710248.html
SpringData JPA示例相关推荐
- 带你搭一个SpringBoot+SpringData JPA的环境
前言 只有光头才能变强. 文本已收录至我的GitHub仓库,欢迎Star:https://github.com/ZhongFuCheng3y/3y 不知道大家对SpringBoot和Spring Da ...
- idea加入springboot插件_带你搭一个SpringBoot+SpringData JPA的环境
前言 只有光头才能变强. 不知道大家对SpringBoot和Spring Data JPA了解多少,如果你已经学过Spring和Hibernate的话,那么SpringBoot和SpringData ...
- SpringData JPA条件查询、排序、分页查询
前言 在刚开始学习的时候,在dao的定义的接口需要继承JpaRepository<T, ID>接口和JpaSpecificationExecutor< T >接口,但是一直以来 ...
- spring boot 整合多数据源JDBC、多数据源mybatis、多数据源springdata jpa
目录 代码地址:(spring-boot github地址) 1.springboot整合JDBC 2.springboot整合mybatis 3.springboot整合springdata jpa ...
- SpringBoot简介、SpringBoot 入门程序搭建、与JDBC、Druid、Mybatis和SpringData JPA的整合
一.SpringBoot 简介: spring boot并不是一个全新的框架,它不是spring解决方案的一个替代品,而是spring的一个封装.所以,你以前可以用spring做的事情,现在用spri ...
- Spring Boot的Spring Data JPA示例
1.简介 在本文中,我们将演示如何利用功能强大的Spring Data JPA API与本课程中的数据库(内存中的H2数据库)进行交互. Spring Data JPA提供了一组非常强大且高度抽象的接 ...
- SpringData+JPA+mysql, cannot be null when ‘hibernate.dialect‘ not set
SpringData+JPA+mysql 8, 报错 cannot be null when 'hibernate.dialect' not set 是因为Hibernate SQL方言没有设置导致的 ...
- Spring Boot中使用Spring Data JPA示例
JPA是Java Persistence API的简称,是sun公司早期推出的Java持久层规范,目前实现JPA规范的主流框架有Hibernate.OpenJPA等.Hibernate框架是当前较为流 ...
- 【持久层框架】- SpringData - JPA
SpringData - JPA
最新文章
- OpenCV-Python:K值聚类
- JAVA中如何将一个json形式的字符串转为json对象或对象列表
- 37 | 案例篇:DNS 解析时快时慢,我该怎么办?
- ES6之路第九篇:Set和Map数据结构
- 使用Source Monitor检测Java代码的环复杂度
- SpringCloud 教程 | 第一篇: 服务的注册与发现Eureka
- 你是愛我還是需要我?
- 计算机格式化为ntfs,u盘无法格式化成ntfs怎么办解决教程
- halcon 深度学习标注_halcon深度学习: 分类
- 自动化立体仓库AS/RS货架|分离式仓库货架与整体式仓库货架如何运用?
- 免ajax省市三级联动:http://runjs.cn/detail/rcsqficf
- 经典圣诞老人题----同步与互斥
- SAP 月末结账步骤
- 全国计算机二级考试中 ms office高级应用与C语言哪个适合大学生?
- Jquery实现淘宝服饰精品案例
- 【Python与数据分析实验报告】Pandas数据分析基础应用
- 胡润首次发布《2019胡润全球独角兽榜》,11家区块链公司入选!
- 开源软件和商业软件版本的介绍:alpha、beta、rc、GA等等
- openCV专栏(八):图像轮廓:绘制轮廓
- 实例004 计算正方形的边长