最近又出来一套新的数据交互层的技术spring data JPA,我做了一个案例尝试了一番,感觉比较好用,下来将完成的效果进行展示
搭建spring data jpa环境
1、引入maven依赖
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.8</version>
</dependency>
<!-- spring jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.8.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.6.Final</version>
</dependency>
2、在beans.xml中定义dataSource节点
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
3、在beans.xml中的beans节点中追加如下配置
<!-- 声明entityManagerFactoryBean -->
<bean id="entityManagerFactoryBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.
HibernateJpaVendorAdapter"></bean>
</property>
<property name="packagesToScan" value="org.giles.springdatajpa"></property>
<property name="jpaProperties">
<props>
<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactoryBean" ref="entityManagerFactoryBean"></property>
</bean>
<!--配置支持注解的事务 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- 配置spring data -->
<jpa:repositories base-package="org.giles" entity-manager-factory-ref="entityManagerFactoryBean"/>
<!-- 包浏览器 -->
<context:component-scan base-package="org.giles"></context:component-scan>
使用spring data JPA实现CRUD操作
1、编写实体对象
@Entity
public class Employee {
private Integer eid;
private String ename;
private int age;
@GeneratedValue
@Id
public Integer getEid() {
return eid;
}
public void setEid(Integer eid) {
this.eid = eid;
}
@Column(length=20)
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
2、编写数据交互层接口
如果要完成的是关系型数据库的CRUD操作,自定义类要继承JpaRepository
public interface EmployeeRepository extends JpaRepository<Employee,Integer>,JpaSpecificationExecutor<Employee>{
@Query("select o from Employee o where o.ename like ?1")
public Employee findEmployeeByEname(String ename);
@Modifying
@Query("update Employee e set e.ename= ?1,e.age= ?2 where e.eid= ?3")
public void updateEmployee(String ename,int age,int eid);
}
3、编写业务层
@Service
public class EmployeeService{
private EmployeeRepository employeeRepository;
@Autowired
public void setEmployeeRepository(EmployeeRepository employeeRepository) {
this.employeeRepository = employeeRepository;
}
/**
* 增加用户操作
* @param employee
*/
public void addEmployee(Employee employee) {
employeeRepository.save(employee);
}
/**
* 批量增加操作
* @param employees
*/
public void addEmployee(List<Employee> employees){
for (Employee employee : employees) {
employeeRepository.save(employee);
}
}
/**
* 按ID查询对象操作
* @param eid
* @return
*/
public Employee findByEid(Integer eid){
return employeeRepository.findOne(eid);
}
/**
* 查询所有操作
* @return
*/
public List<Employee> findAll(){
return employeeRepository.findAll();
}
/**
* 删除操作
* @param eid
*/
@Transactional
public void deleteEmployeeByEid(Integer eid){
employeeRepository.delete(eid);
}
/**
* 修改操作
* @param employee
*/
@Transactional
public void updateEmployee(Employee employee){
employeeRepository.updateEmployee(employee.getEname(),employee.getAge(),employee.getEid());
}
/**
* 按姓名查询用户对象
* @param ename
* @return
*/
public Employee findEmployeeByEname(String ename){
return employeeRepository.findEmployeeByEname(ename);
}
/**
* 分页操作
* @param currentPage
* @param pageSize
* @return
*/
public Page<Employee> findAllByPage(final Employee employee,int currentPage,int pageSize){
Sort.Order order=new Sort.Order(Sort.Direction.ASC,"eid");
Sort sort=new Sort(order);
Specification<Employee> specification=new Specification<Employee>() {
public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> query, CriteriaBuilder criteria) {
Path path1=root.get("age");
Predicate p1=criteria.gt(path1,employee.getAge());
Path path2=root.get("ename");
Predicate p2=criteria.like(path2,"%"+employee.getEname()+"%");
return criteria.and(p1,p2);
}
};
Pageable pageable=new PageRequest((currentPage-1)*pageSize,pageSize,sort);
Page<Employee> page=employeeRepository.findAll(specification,pageable);
return page;
}
}
4、编写测试类
public class EmpServiceTest {
private ApplicationContext cxt;
@Before
public void setup(){
cxt=new ClassPathXmlApplicationContext("beans.xml");
}
@Test
public void testSave(){
EmployeeService employeeService=cxt.getBean(EmployeeService.class);
Employee employee=new Employee();
employee.setEname("张三");
employee.setAge(33);
employeeService.addEmployee(employee);
}
@Test
public void testSave2(){
EmployeeService employeeService=cxt.getBean(EmployeeService.class);
List<Employee> employees=new ArrayList<Employee>();
for(int i=0;i<10;i++){
Employee employee=new Employee();
employee.setEname("张三"+i);
employee.setAge(i);
employees.add(employee);
}
employeeService.addEmployee(employees);
}
@Test
public void testSave3(){
EmployeeService employeeService=cxt.getBean(EmployeeService.class);
Employee employee=employeeService.findByEid(1);
System.out.println(employee.getEid()+"\t"+employee.getEname()+"\t"+employee.getAge());
}
@Test
public void testSave4(){
EmployeeService employeeService=cxt.getBean(EmployeeService.class);
List<Employee> all=employeeService.findAll();
for (Employee employee : all) {
System.out.println(employee.getEid()+"\t"+employee.getEname()+"\t"+employee.getAge());
}
}
@Test
public void testSave5(){
EmployeeService employeeService=cxt.getBean(EmployeeService.class);
employeeService.deleteEmployeeByEid(1);
}
@Test
public void testFindByEnameLike(){
EmployeeService employeeService=cxt.getBean(EmployeeService.class);
Employee employee=employeeService.findEmployeeByEname("张三0");
System.out.println("姓名:"+employee.getEname());
}
@Test
public void testUpdateEmployee(){
EmployeeService employeeService=cxt.getBean(EmployeeService.class);
Employee employee=new Employee();
employee.setEid(3);
employee.setEname("李四");
employee.setAge(45);
employeeService.updateEmployee(employee);
}
@Test
public void testFindAllByPage(){
EmployeeService employeeService=cxt.getBean(EmployeeService.class);
Employee employee=new Employee();
employee.setEname("张三");
employee.setAge(3);
Page<Employee> page=employeeService.findAllByPage(employee,1,5);
int totalPages=page.getTotalPages();
int size=page.getSize();
System.out.println("共"+totalPages+"页");
System.out.println("共"+size+"条记录");
List<Employee> employees=page.getContent();
for (Employee item : employees) {
System.out.println(item.getEid()+"\t"+item.getEname()+"\t"+item.getAge());
}
}
搭建spring data jpa环境
1、引入maven依赖
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.8</version>
</dependency>
<!-- spring jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.8.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.6.Final</version>
</dependency>
2、在beans.xml中定义dataSource节点
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
3、在beans.xml中的beans节点中追加如下配置
<!-- 声明entityManagerFactoryBean -->
<bean id="entityManagerFactoryBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.
HibernateJpaVendorAdapter"></bean>
</property>
<property name="packagesToScan" value="org.giles.springdatajpa"></property>
<property name="jpaProperties">
<props>
<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactoryBean" ref="entityManagerFactoryBean"></property>
</bean>
<!--配置支持注解的事务 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- 配置spring data -->
<jpa:repositories base-package="org.giles" entity-manager-factory-ref="entityManagerFactoryBean"/>
<!-- 包浏览器 -->
<context:component-scan base-package="org.giles"></context:component-scan>
使用spring data JPA实现CRUD操作
1、编写实体对象
@Entity
public class Employee {
private Integer eid;
private String ename;
private int age;
@GeneratedValue
@Id
public Integer getEid() {
return eid;
}
public void setEid(Integer eid) {
this.eid = eid;
}
@Column(length=20)
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
2、编写数据交互层接口
如果要完成的是关系型数据库的CRUD操作,自定义类要继承JpaRepository
public interface EmployeeRepository extends JpaRepository<Employee,Integer>,JpaSpecificationExecutor<Employee>{
@Query("select o from Employee o where o.ename like ?1")
public Employee findEmployeeByEname(String ename);
@Modifying
@Query("update Employee e set e.ename= ?1,e.age= ?2 where e.eid= ?3")
public void updateEmployee(String ename,int age,int eid);
}
3、编写业务层
@Service
public class EmployeeService{
private EmployeeRepository employeeRepository;
@Autowired
public void setEmployeeRepository(EmployeeRepository employeeRepository) {
this.employeeRepository = employeeRepository;
}
/**
* 增加用户操作
* @param employee
*/
public void addEmployee(Employee employee) {
employeeRepository.save(employee);
}
/**
* 批量增加操作
* @param employees
*/
public void addEmployee(List<Employee> employees){
for (Employee employee : employees) {
employeeRepository.save(employee);
}
}
/**
* 按ID查询对象操作
* @param eid
* @return
*/
public Employee findByEid(Integer eid){
return employeeRepository.findOne(eid);
}
/**
* 查询所有操作
* @return
*/
public List<Employee> findAll(){
return employeeRepository.findAll();
}
/**
* 删除操作
* @param eid
*/
@Transactional
public void deleteEmployeeByEid(Integer eid){
employeeRepository.delete(eid);
}
/**
* 修改操作
* @param employee
*/
@Transactional
public void updateEmployee(Employee employee){
employeeRepository.updateEmployee(employee.getEname(),employee.getAge(),employee.getEid());
}
/**
* 按姓名查询用户对象
* @param ename
* @return
*/
public Employee findEmployeeByEname(String ename){
return employeeRepository.findEmployeeByEname(ename);
}
/**
* 分页操作
* @param currentPage
* @param pageSize
* @return
*/
public Page<Employee> findAllByPage(final Employee employee,int currentPage,int pageSize){
Sort.Order order=new Sort.Order(Sort.Direction.ASC,"eid");
Sort sort=new Sort(order);
Specification<Employee> specification=new Specification<Employee>() {
public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> query, CriteriaBuilder criteria) {
Path path1=root.get("age");
Predicate p1=criteria.gt(path1,employee.getAge());
Path path2=root.get("ename");
Predicate p2=criteria.like(path2,"%"+employee.getEname()+"%");
return criteria.and(p1,p2);
}
};
Pageable pageable=new PageRequest((currentPage-1)*pageSize,pageSize,sort);
Page<Employee> page=employeeRepository.findAll(specification,pageable);
return page;
}
}
4、编写测试类
public class EmpServiceTest {
private ApplicationContext cxt;
@Before
public void setup(){
cxt=new ClassPathXmlApplicationContext("beans.xml");
}
@Test
public void testSave(){
EmployeeService employeeService=cxt.getBean(EmployeeService.class);
Employee employee=new Employee();
employee.setEname("张三");
employee.setAge(33);
employeeService.addEmployee(employee);
}
@Test
public void testSave2(){
EmployeeService employeeService=cxt.getBean(EmployeeService.class);
List<Employee> employees=new ArrayList<Employee>();
for(int i=0;i<10;i++){
Employee employee=new Employee();
employee.setEname("张三"+i);
employee.setAge(i);
employees.add(employee);
}
employeeService.addEmployee(employees);
}
@Test
public void testSave3(){
EmployeeService employeeService=cxt.getBean(EmployeeService.class);
Employee employee=employeeService.findByEid(1);
System.out.println(employee.getEid()+"\t"+employee.getEname()+"\t"+employee.getAge());
}
@Test
public void testSave4(){
EmployeeService employeeService=cxt.getBean(EmployeeService.class);
List<Employee> all=employeeService.findAll();
for (Employee employee : all) {
System.out.println(employee.getEid()+"\t"+employee.getEname()+"\t"+employee.getAge());
}
}
@Test
public void testSave5(){
EmployeeService employeeService=cxt.getBean(EmployeeService.class);
employeeService.deleteEmployeeByEid(1);
}
@Test
public void testFindByEnameLike(){
EmployeeService employeeService=cxt.getBean(EmployeeService.class);
Employee employee=employeeService.findEmployeeByEname("张三0");
System.out.println("姓名:"+employee.getEname());
}
@Test
public void testUpdateEmployee(){
EmployeeService employeeService=cxt.getBean(EmployeeService.class);
Employee employee=new Employee();
employee.setEid(3);
employee.setEname("李四");
employee.setAge(45);
employeeService.updateEmployee(employee);
}
@Test
public void testFindAllByPage(){
EmployeeService employeeService=cxt.getBean(EmployeeService.class);
Employee employee=new Employee();
employee.setEname("张三");
employee.setAge(3);
Page<Employee> page=employeeService.findAllByPage(employee,1,5);
int totalPages=page.getTotalPages();
int size=page.getSize();
System.out.println("共"+totalPages+"页");
System.out.println("共"+size+"条记录");
List<Employee> employees=page.getContent();
for (Employee item : employees) {
System.out.println(item.getEid()+"\t"+item.getEname()+"\t"+item.getAge());
}
}
相关推荐
**Spring Data JPA** 是一个基于 **Java** 的开源框架,它是 **Spring Framework** 的一个模块,主要用于简化 **Java Persistence API (JPA)** 的使用。JPA 是 Java 平台上的一个标准,用于管理和持久化应用程序的...
Spring Data JPA API。 Spring Data JPA 开发文档。 官网 Spring Data JPA API。
通过使用Spring Data JPA,开发者可以避免编写大量的JPA(Java Persistence API)和SQL代码,专注于业务逻辑。本笔记将深入探讨Spring Data JPA的核心概念、功能以及如何在实际项目中应用。 首先,我们需要理解JPA...
本教程将详细介绍 Spring Data JPA 的核心概念与使用方法,帮助开发者从基础入门到实现复杂查询的完整过程。 第一章:Spring Data JPA 入门 Spring Data JPA 简化了 JPA(Java Persistence API)的开发,通过约定...
"spring data jpa官方文档中文翻译"则提供了Spring Data JPA的详细指南,包括其设计原理、基本概念、使用方法和最佳实践。"JPA2.0官方文档"则深入讲解了JPA规范的各个方面,包括实体管理、查询、事务和并发控制等。 ...
然而,尽管Spring Data JPA带来了诸多便利,但在实际使用中也会遇到一些挑战和难点: 1. **SQL性能问题**: - Spring Data JPA虽然简化了查询编写,但可能导致生成的SQL不够优化,尤其是在处理大数据量或复杂查询...
'SpringDataJPA从入门到精通'以SpringBoot为技术基础 从入门到精通 由浅入深地介绍SpringDataJPA的使用。有语法 有实践 有原理剖析。'SpringDataJPA从入门到精通'分为12章 内容包括整体认识JPA、JPA基础查询方法、...
默认情况下,Spring Data JPA使用Hibernate作为JPA的实现。Hibernate提供了丰富的功能,如缓存、二级缓存、懒加载等,但也需要考虑其性能和内存使用。 8. **Specifications** 对于更复杂的查询需求,Spring Data ...
Spring Data JPA是Spring框架的一个扩展,它简化了对Java Persistence API (JPA) 的使用,使数据库操作更加便捷。通过Spring Data JPA,我们可以直接通过接口定义来实现对数据库的CRUD操作,无需编写大量的DAO层代码...
- **强大的查询支持**:除了简单的 CRUD 方法,Spring Data JPA 还支持基于方法名的复杂查询,甚至可以使用 JPA Querydsl 或 Specification 进行更复杂的查询。 - **事务管理**:Spring Data JPA 结合 Spring 的事务...
Spring Data JPA 默认使用Hibernate 作为JPA 实现。Hibernate 是一个流行的ORM(对象关系映射)框架,它将Java 对象与数据库记录对应起来。我们可以配置Hibernate 具体的行为,如缓存策略、实体监听器等。 通过这...
1. **简介**:了解Spring Data JPA的目标,它是如何简化JPA的使用,以及它如何与其他Spring模块集成。 2. **快速入门**:包括设置项目依赖,配置数据源和JPA供应商(如Hibernate),以及创建第一个Repository接口。...
Spring-data-jpa 的目标是利用 Spring 的强大功能来进一步简化 JPA 的使用。它不仅提供了简单的 CRUD 操作,还支持更复杂的查询、分页、排序等功能,并且与 Spring 框架无缝集成,使得开发者能够更加专注于业务逻辑...
使用 SpringBoot + SpringDataJPa 设计通用的权限管理系统,适合管理系统快速开发迭代,可用于开发模板,项目经过测试,可完美运行! 使用 SpringBoot + SpringDataJPa 设计通用的权限管理系统,适合管理系统快速...
SpringBoot集成了SpringDataJPA之后,就可以利用SpringBoot的自动配置能力,让开发者能够快速搭建和运行使用SpringDataJPA的项目。 在SpringBoot项目中整合SpringDataJPA,首先要导入必要的Maven依赖。在项目中,...
Spring Data JPA是Spring Framework的一个模块,它简化了JPA的使用。它提供了自动配置、基于方法的查询支持、Repository抽象层等特性,极大地提高了开发效率。通过定义简单的接口,Spring Data JPA可以自动生成对应...
Spring Data JPA 是 Spring 框架的一个模块,它为使用 JPA(Java Persistence API)提供了强大的支持,简化了数据访问层的开发。通过使用 Spring Data JPA,我们可以避免编写大量重复的 CRUD(创建、读取、更新、...