SpringBoot开发案例之整合Spring-data-jpa
什么是spring-data
为了简化程序与数据库交互的代码,spring提供了一个现成的dao层框架,spring家族提供的spring-data适用于关系型数据库和nosql数据库
什么是jpa
JPA全称为Java持久性API(Java Persistence API),JPA是java EE 5标准之一,是一个ORM规范,由厂商来实现该规范,目前有hibernate、OpenJPA、TopLink、EclipseJPA等实现。
如何使用JPA
查询
- 查询所有数据 findAll()
- 分页查询 findAll(new PageRequest(0, 2))
- 根据id查询 findOne()
- 根据实体类属性查询: findByProperty (type Property); 例如:findByAge(int age);
- 排序: findAll(sort )
- Sort sort = new Sort(Sort.Direction.DESC, "age").and (new Sort(Sort.Direction.DESC, "id"));
- 条件查询 and/or/findByAgeLessThan/LessThanEqual 等,
- 例如: findByUsernameAndPassword(String username , String password)
- 总数 查询 count() 或者 根据某个属性的值查询总数countByAge(int age);
- 是否存在某个id exists()
修改,删除,新增
- 新增:直接使用 save(T) 方法
- 删除: delete() 或者 deleteByProperty 例如:deleteByAge(int age) ;
- 更新:
@Modifying
@Query("update Customer u set u.age = ?1 where u.id = ?2")
int update(int age1 , long id);
项目结构
相关配置
pom.xml(部分代码,详见源码):
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
application.properties:
# 项目contextPath server.context-path=/jpa # 服务端口 server.port=8080# session最大超时时间(分钟),默认为30 server.session-timeout=60# 该服务绑定IP地址,启动服务器时如本机不是该IP地址则抛出异常启动失败,只有特殊需求的情况下才配置 #server.address=192.168.1.66# tomcat最大线程数,默认为200 server.tomcat.max-threads=100# tomcat的URI编码 server.tomcat.uri-encoding=UTF-8#注意中文乱码 spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf-8 spring.datasource.username=root spring.datasource.password=123spring.datasource.driver-class-name=com.mysql.jdbc.Driver # Specify the DBMS spring.jpa.database=MYSQL # Show or not logforeach sql query spring.jpa.show-sql = true# DDL mode. This is actually a shortcutfor the "hibernate.hbm2ddl.auto" property. Default to "create-drop" when using an embedded database, "none"otherwise. spring.jpa.hibernate.ddl-auto =update # Hibernate4 naming strategy fully qualified name. Not supported with Hibernate 5. 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
spring.jpa.properties.hibernate.hbm2ddl.auto是hibernate的配置属性,其主要作用是:自动创建、更新、验证数据库表结构。该参数的几种配置如下:
- create:每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,哪怕两次没有任何改变也要这样执行,这就是导致数据库表数据丢失的一个重要原因。
- create-drop:每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。
- update:最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时根据model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等应用第一次运行起来后才会。
- validate:每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值。
实体类 User.java:
packagecom.itstyle.jpa.model;importjava.io.Serializable;import javax.persistence.*;/*** 用户实体(此处注意引用的注解包为javax.persistence*下面的)* 创建者 科帮网* 创建时间 2017年7月25日**/@Entity @Table(name= "sys_user")public class User implementsSerializable{private static final long serialVersionUID = 1L;@Id@GeneratedValue(strategy=GenerationType.AUTO)@Column(name= "id", nullable = false)privateLong id;@Column(nullable= false, name = "name")privateString name;@Column(nullable= false, name = "age")privateInteger age;---省略 get set 方法 }
数据操作UserRepository.java:
/*** 数据操作层* 创建者 科帮网* 创建时间 2017年7月25日**/ public interface UserRepository extends JpaRepository<User, Long>{User findByName(String name);User findByAge(Integer age);User findByNameAndAge(String name, Integer age);List<User>findByNameLike(String name);@Query("from User u where u.name=:name")User findUser(@Param("name") String name);}
小伙伴没有没有发现,我们只是定义了一个方法而已,怎么就这么奇妙的实现的对应功能?其实这是Spring-data-jpa的新特性,通过解析方法名创建查询。更多解析说明如下:
And => 等价于 SQL 中的 and 关键字 例如:findByUsernameAndPassword(String user, Striang pwd);
Or => 等价于 SQL 中的 or 关键字,例如:findByUsernameOrAddress(String user, String addr);
Between => 等价于 SQL 中的 between 关键字,例如:SalaryBetween(int max, int min);
LessThan => 等价于 SQL 中的 "<",例如: findBySalaryLessThan(int max);
GreaterThan => 等价于 SQL 中的">",例如: findBySalaryGreaterThan(int min);
IsNull => 等价于 SQL 中的 "is null",例如: findByUsernameIsNull();
IsNotNull => 等价于 SQL 中的 "is not null",例如: findByUsernameIsNotNull();
NotNull=> 与 IsNotNull 等价;
Like => 等价于 SQL 中的 "like",例如: findByUsernameLike(String user);
NotLike => 等价于 SQL 中的 "not like",例如: findByUsernameNotLike(String user);
OrderBy => 等价于 SQL 中的 "order by",例如: findByUsernameOrderBySalaryAsc(String user);
Not => 等价于 SQL 中的 "! =",例如: findByUsernameNot(String user);
In => 等价于 SQL 中的 "in",例如: findByUsernameIn(Collection userList) ,方法的参数可以是 Collection 类型,也可以是数组或者不定长参数;
NotIn => 等价于 SQL 中的 "not in",例如: findByUsernameNotIn(Collection userList) ,方法的参数可以是 Collection 类型,也可以是数组或者不定长参数;
创建一个按单字段排序的Sort对象: new Sort(Sort.Direction.DESC, "description").and(new Sort(Sort.Direction.ASC, "id"))
最终测试类SpringbootJpaApplication.java:
packagecom.itstyle.jpa;importjava.util.List;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.CommandLineRunner;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importcom.itstyle.jpa.model.User;importcom.itstyle.jpa.repository.UserRepository;@SpringBootApplicationpublic class SpringbootJpaApplication implementsCommandLineRunner {@AutowiredprivateUserRepository userRepository;public static voidmain(String[] args) {SpringApplication.run(SpringbootJpaApplication.class, args);}@Overridepublic void run(String... args) throwsException {try{User user= newUser();user.setName("张三");user.setAge(20);userRepository.save(user);List<User> u = userRepository.findByNameLike("%张三%");System.out.println(u.size());User us= userRepository.findByAge(20);System.out.println(us.getAge());us= userRepository.findByName("这是你干");}catch(Exception e) {e.printStackTrace();}} }
偶遇问题
No identifier specified for entity:
检查一下包是否引入正确,引入一下:
import javax.persistence.*;
中文乱码问题:
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf-8
在高版本mysql中需要指定是否进行SSL连接
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useSSL=false
代码:https://git.oschina.net/52itstyle/spring-data-jpa
作者: 小柒
出处: https://blog.52itstyle.com
转载于:https://www.cnblogs.com/walblog/articles/9483296.html
SpringBoot开发案例之整合Spring-data-jpa相关推荐
- springboot整合hibernate_峰哥说技术系列-17 .Spring Boot 整合 Spring Data JPA
今日份主题 Spring Boot 整合 Spring Data JPA JPA(Java Persistence API)是用于对象持久化的 API,是Java EE 5.0 平台标准的 ORM 规 ...
- springboot学习笔记(三)使用JDBC以及整合spring data jpa
spring boot JDBC的使用: 1.引入依赖 <dependency><groupId>mysql</groupId><artifactId> ...
- 第九章SpringBoot整合Spring Data JPA
目录 1 概述 2 Spring Data JPA整合 2.1 pom文件 2.2 配置文件 2.3 实体类 2.4 Dao接口 2.5 启动类 2.6 编写测试类 3 Spring Data JPA ...
- Springboot整合Spring Data JPA
1 Spring Data JPA 1.Spring Data JPA的概念 在介绍Spring Data JPA的时候,我们首先认识下Hibernate.Hibernate是数据访问解决技术的绝对霸 ...
- 【SpringBoot框架篇】11.Spring Data Jpa实战
文章目录 1.简介 1.1.JPA 1.2.Spring Data Jpa 1.3.Hibernate 1.4.Jpa.Spring Data Jpa.Hibernate三者之间的关系 2.引入依赖 ...
- Spring Boot整合Spring Data JPA操作数据
一. Sping Data JPA 简介 Spring Data JPA 是 Spring 基于 ORM 框架.JPA 规范的基础上封装的一套 JPA 应用框架,底层使用了 Hibernate 的 J ...
- Spring Boot 应用系列 1 -- Spring Boot 2 整合Spring Data JPA和Druid,双数据源
最近Team开始尝试使用Spring Boot + Spring Data JPA作为数据层的解决方案,在网上逛了几圈之后发现大家并不待见JPA,理由是(1)MyBatis简单直观够用,(2)以Hib ...
- Spring Boot 整合 Spring Data JPA
JPA 是一个基于 O/R 映射的 Java 持久化规范,其定义了一系列对象持久化的标准,目前实现这一规范的产品有 Hibernate.EclipseLink.OpenJPA.TopLink 等,这也 ...
- Spring整合Spring Data JPA——MySQL
1. MySQL下载和配置 进入官网:https://www.mysql.com/downloads/ 点击MySQL Community(GPL) Downloads 点击MySQL Communi ...
- SpringBoot2.0之三 优雅整合Spring Data JPA
在我们的实际开发的过程中,无论多复杂的业务逻辑到达持久层都回归到了"增删改查"的基本操作,可能会存在关联多张表的复杂sql,但是对于单表的"增删改查"也是不 ...
最新文章
- android.graphics.Paint方法setXfermode (Xfermode x...
- 难点电路详解之负反馈放大器电路(1)
- RabbitMQ 一二事(2) - 工作队列使用
- IOS开发之----异常处理
- ST17H26移植软时钟代码
- amd处理器更新zen4服务器芯片,AMD更新CPU、GPU路线图:Zen4架构与硬件光追可期
- linux如何标识用户账号和组账号,linux管理用户和组
- 全局变量、局部变量、静态全局变量、静态局部变量的区别
- Python 解释器中使用help()命令如何退出
- (49)FPGA线性单驱动(wire型)
- 计算机组成原理课程设计报告总结
- 贝叶斯公式的直观理解(先验概率/后验概率)
- (轉貼) 人人有功練!! 有功夫,沒懦夫 (News)
- R语言加载xlsl软件包
- 苹果CMS v10模板:大橙子vfed完美版视频网站模板
- 谷歌浏览器开启JavaScript
- 情景式领导力学习(1) - 介绍
- 人工智能技术涉及到的学科有哪些,22年最新
- 无盘服务器快慢取决于什么,cpu运行速度的快慢取决于什么
- C++重温笔记(一): C++再初识