Spring Data简单使用

Spring Data JPA 快速起步

  • 开发环境搭建
  • Spring Data JPA开发
Maven依赖添加
<dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-jpa</artifactId>
      <version>1.11.7.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>5.0.12.Final</version>
    </dependency>
Beans-new.xml
<?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/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!--加载配置文件-->
    <context:property-placeholder location="classpath:db.properties"/>

    <!--1 配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="username" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="url" value="${jdbc.url}"/>
    </bean>

    <!--2 配置EntityManagerFactory-->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
        </property>
        <property name="packagesToScan" value="com.imooc"/><!--指定包扫描-->

        <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><!--显示sql语句-->
                <prop key="hibernate.format_sql">true</prop><!--格式化sql语句-->
                <prop key="hibernate.hbm2ddl.auto">update</prop><!--自动创建表-->
            </props>
        </property>

    </bean>

    <!--3 配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>

    <!--4 配置支持注解的事务-->
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!--5 配置spring data-->
    <jpa:repositories base-package="com.imooc" entity-manager-factory-ref="entityManagerFactory"/>

    <context:component-scan base-package="com.imooc"/>

</beans>
实体类Employee
package com.imooc.domain;

import javax.persistence.*;

/**
 * Created by zghgchao 2017/12/29 17:05
 * 雇员:先开发实体类 ===> 自动生成数据表
 */
@Entity
@Table(name = "test_employee")
public class Employee {

    @Id
    @GeneratedValue
    private Integer id;

    private String name;

    private Integer age;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Column(length = 20)
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}


Spring Data测试
package com.imooc;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Created by zghgchao 2017/12/29 20:28
 */
public class SpringDataTest {

    private ApplicationContext ctx = null;

    @Before
    public void setup() {
        ctx = new ClassPathXmlApplicationContext("beans-new.xml");
        System.out.println("------------------setup---------------------");
    }

    @After
    public void tearDown() {
        ctx = null;
        System.out.println("------------------tearDown---------------------");
    }

    @Test
    public void testEntityManagerFactory() {
	//运行后会根据beans-new.xml中的【EntityManagerFactory】配置,在Mysql中生成相应的表
    }
}
EmployeeRepository接口的实现
package com.imooc.repository;

import com.imooc.domain.Employee;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.RepositoryDefinition;
import org.springframework.data.repository.query.Param;

import java.util.List;


/**
 * Created by zghgchao 2017/12/29 17:09
 */
@RepositoryDefinition(domainClass = Employee.class, idClass = Integer.class)
public interface EmployeeRepository {//extends Repository<Employee, Integer>

    Employee findByName(String name);

    //where name like ?% and age < ?
    List<Employee> findByNameStartingWithAndAgeLessThan(String name, Integer age);

    //where name like %? and age < ?
    List<Employee> findByNameEndingWithAndAgeLessThan(String name, Integer age);

    //where name in (?,?...) or age < ?
    List<Employee> findByNameInOrAgeLessThan(List<String> names, Integer age);

    //where name in (?,?...) and age < ?
    List<Employee> findByNameInAndAgeLessThan(List<String> names, Integer age);

    @Query("select o from Employee o where id=(select max(id) from Employee t1)")
    Employee getEmployeeByMaxId();

    @Query("select o from Employee o where o.name = ?1 and o.age = ?2")
    List<Employee> queryParam1(String name, Integer age);

    @Query("select o from Employee o where o.name = :name and o.age = :age")
    List<Employee> queryParam2(@Param(value = "name") String name, @Param(value = "age") Integer age);

    @Query("select o from Employee o where o.name like %?1%")
    List<Employee> queryLike1(String name);

    @Query("select o from Employee o where o.name like %:name%")
    List<Employee> queryLike2(@Param(value = "name") String name);

    @Query(nativeQuery = true, value = "select COUNT(1) from Employee;")
    long getCount();

    @Modifying
    @Query("update Employee o set o.age=:age where o.id=:id")
    void updata(@Param("id") Integer id, @Param("age") Integer age);
}
EmployeeRepositorTest测试类
package com.imooc.repository;

import com.imooc.domain.Employee;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static org.junit.Assert.*;

/**
 * Created by zghgchao 2017/12/29 20:53
 */
public class EmployeeRepositoryTest {

    private ApplicationContext ctx = null;
    private EmployeeRepository employeeRepository = null;

    @Before
    public void setup() {
        ctx = new ClassPathXmlApplicationContext("beans-new.xml");
        employeeRepository = ctx.getBean(EmployeeRepository.class);
        System.out.println("------------------setup---------------------");
    }

    @After
    public void tearDown() {
        ctx = null;
        System.out.println("------------------tearDown---------------------");
    }


    @Test
    public void testFindByName() throws Exception {
        Employee employee = employeeRepository.findByName("zhangsan");
        System.out.println(employee.toString());
    }

    @Test
    public void testFindByNameStartingWithAndAgeLessThan() throws Exception {
        List<Employee> list = employeeRepository.findByNameStartingWithAndAgeLessThan("test", 23);
        for (Employee employee : list) {
            System.out.println(employee.toString());
        }
    }

    @Test
    public void findByNameEndingWithAndAgeLessThan() throws Exception {
        List<Employee> list = employeeRepository.findByNameEndingWithAndAgeLessThan("1", 23);
        for (Employee employee : list) {
            System.out.println(employee.toString());
        }
    }

    @Test
    public void findByNameInOrAgeLessThan() throws Exception {
        List<String> names = new ArrayList<String>();
        names.add("test1");
        names.add("test2");
        names.add("test3");
        List<Employee> list = employeeRepository.findByNameInOrAgeLessThan(names,22);
        for (Employee employee : list) {
            System.out.println(employee.toString());
        }
    }
    @Test
    public void findByNameInAndAgeLessThan() throws Exception {
        List<String> names = new ArrayList<String>();
        names.add("test1");
        names.add("test2");
        names.add("test3");
        List<Employee> list = employeeRepository.findByNameInAndAgeLessThan(names,22);
        for (Employee employee : list) {
            System.out.println(employee.toString());
        }
    }

    @Test
    public void getEmployeeByMaxId() throws Exception {
        Employee employee = employeeRepository.getEmployeeByMaxId();
        System.out.println(employee.toString());
    }

    /**
     * 不能直接调用,没有添加事务
     * @throws Exception
     */
    @Test
    public void updata() throws Exception {
        employeeRepository.updata(1,22);//运行报错,更新操作必须要有【事务】
    }

    @Test
    public void getCount() throws Exception {
        System.out.println(employeeRepository.getCount());
    }

    @Test
    public void queryLike2() throws Exception {
        List<Employee> list = employeeRepository.queryLike2("test");
        for (Employee employee : list) {
            System.out.println(employee.toString());
        }
    }

    @Test
    public void queryLike1() throws Exception {
        List<Employee> list = employeeRepository.queryLike1("test");
        for (Employee employee : list) {
            System.out.println(employee.toString());
        }
    }

    @Test
    public void queryParam1() throws Exception {
        List<Employee> list = employeeRepository.queryParam1("zhangsan", 20);
        for (Employee employee : list) {
            System.out.println(employee.toString());
        }
    }

    @Test
    public void queryParam2() throws Exception {
        List<Employee> list = employeeRepository.queryParam2("zhangsan", 20);
        for (Employee employee : list) {
            System.out.println(employee.toString());
        }
    }

}
EmployeeJpaRepository类的实现
package com.imooc.repository;

import com.imooc.domain.Employee;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * Created by zghgchao 2017/12/30 9:24
 */
public interface EmployeeJpaRepository extends JpaRepository<Employee,Integer> {
}
Service层,为updata添加事务
package com.imooc.service;

import com.imooc.domain.Employee;
import com.imooc.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by zghgchao 2017/12/29 17:18
 */
@Service
public class EmployeeService {

    @Autowired
    private EmployeeRepository employeeRepository;

 
    @Transactional
    public void updata(Integer id,Integer age){
        employeeRepository.updata(id,age);
    }

}


EmployeeJpaRepositoryTest测试类
package com.imooc.repository;

import com.imooc.domain.Employee;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import static org.junit.Assert.*;

/**
 * Created by zghgchao 2017/12/30 10:23
 */
public class EmployeeJpaRepositoryTest {
    private ApplicationContext ctx = null;
    private EmployeeJpaRepository employeeJpaRepository = null;

    @Before
    public void setup() {
        ctx = new ClassPathXmlApplicationContext("beans-new.xml");
        employeeJpaRepository = ctx.getBean(EmployeeJpaRepository.class);
        System.out.println("------------------setup---------------------");
    }

    @After
    public void tearDown() {
        ctx = null;
        System.out.println("------------------tearDown---------------------");
    }

    @Test
    public void testFind(){
        Employee employee = employeeJpaRepository.findOne(99);
        System.out.println(employee.toString());
    }
}

EmployeeCrudRepository接口
package com.imooc.repository;

import com.imooc.domain.Employee;
import org.springframework.data.repository.CrudRepository;

/**
 * Created by zghgchao 2017/12/30 9:03
 */
public interface EmployeeCrudRepository extends CrudRepository<Employee,Integer> {
}

service类
package com.imooc.service;

import com.imooc.domain.Employee;
import com.imooc.repository.EmployeeCrudRepository;
import com.imooc.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by zghgchao 2017/12/29 17:18
 */
@Service
public class EmployeeService {

  
    @Autowired
    private EmployeeCrudRepository employeeCrudRepository;


    @Transactional
    public void save(List<Employee> employees){
        employeeCrudRepository.save(employees);
    }

EmployeeServiceTest
package com.imooc.service;

import com.imooc.domain.Employee;
import com.imooc.repository.EmployeeRepository;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.*;

/**
 * Created by zghgchao 2017/12/29 22:53
 */
public class EmployeeServiceTest {

    private ApplicationContext ctx = null;
    private EmployeeService employeeService = null;

    @Before
    public void setup() {
        ctx = new ClassPathXmlApplicationContext("beans-new.xml");
        employeeService = ctx.getBean(EmployeeService.class);
        System.out.println("------------------setup---------------------");
    }

    @After
    public void tearDown() {
        ctx = null;
        System.out.println("------------------tearDown---------------------");
    }

    @Test
    public void save() throws Exception {
        List<Employee> employees = new ArrayList<Employee>();

        Employee employee = null;
        for (int i = 0; i < 100; i++) {
            employee = new Employee();
            employee.setName("test" + i);
            employee.setAge(100 - i);
            employees.add(employee);
        }

        employeeService.save(employees);
    }

}
EmployeePagingAndSortingRepository接口
package com.imooc.repository;

import com.imooc.domain.Employee;
import org.springframework.data.repository.PagingAndSortingRepository;

/**
 * Created by zghgchao 2017/12/30 9:24
 */
public interface EmployeePagingAndSortingRepository extends PagingAndSortingRepository<Employee,Integer> {
}
EmployeePagingAndSortingRepositoryTest
package com.imooc.repository;

import com.imooc.domain.Employee;
import com.imooc.service.EmployeeService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import static org.junit.Assert.*;

/**
 * Created by zghgchao 2017/12/30 9:25
 */
public class EmployeePagingAndSortingRepositoryTest {
    private ApplicationContext ctx = null;
    private EmployeePagingAndSortingRepository employeePagingAndSortingRepository = null;

    @Before
    public void setup() {
        ctx = new ClassPathXmlApplicationContext("beans-new.xml");
        employeePagingAndSortingRepository = ctx.getBean(EmployeePagingAndSortingRepository.class);
        System.out.println("------------------setup---------------------");
    }

    @After
    public void tearDown() {
        ctx = null;
        System.out.println("------------------tearDown---------------------");
    }

    @Test
    public void testPage() {
        Pageable pageable = new PageRequest(0, 5);//page:index是从零开始的
        Page<Employee> page = employeePagingAndSortingRepository.findAll(pageable);
        System.out.println("getTotalPages--总页数" + page.getTotalPages());
        System.out.println("getTotalElements--总记录数" + page.getTotalElements());
        System.out.println("getNumber--当前第几页" + (page.getNumber() + 1));
        System.out.println("getContent--当前页面的集合" + page.getContent());
        System.out.println("getNumberOfElements--当前页面的记录数" + page.getNumberOfElements());
    }


    @Test
    public void testPageAndSort() {


        Sort sort = new Sort(Sort.Direction.DESC,"id");

        Pageable pageable = new PageRequest(1, 5,sort);//page:index是从零开始的
        Page<Employee> page = employeePagingAndSortingRepository.findAll(pageable);
        System.out.println("getTotalPages--总页数" + page.getTotalPages());
        System.out.println("getTotalElements--总记录数" + page.getTotalElements());
        System.out.println("getNumber--当前第几页" + (page.getNumber() + 1));
        System.out.println("getContent--当前页面的集合" + page.getContent());
        System.out.println("getNumberOfElements--当前页面的记录数" + page.getNumberOfElements());
    }
}
EmployeeJpaSpecificationExecutor
package com.imooc.repository;

import com.imooc.domain.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

/**
 * Created by zghgchao 2017/12/30 10:32
 */
public interface EmployeeJpaSpecificationExecutor
        extends JpaRepository<Employee, Integer>, JpaSpecificationExecutor<Employee> {
}
EmployeeJpaSpecificationExecutorTest
package com.imooc.repository;

import com.imooc.domain.Employee;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.*;

import static org.junit.Assert.*;

/**
 * Created by zghgchao 2017/12/30 10:40
 */
public class EmployeeJpaSpecificationExecutorTest {

    private ApplicationContext ctx = null;
    private EmployeeJpaSpecificationExecutor employeeJpaSpecificationExecutor = null;

    @Before
    public void setup() {
        ctx = new ClassPathXmlApplicationContext("beans-new.xml");
        employeeJpaSpecificationExecutor = ctx.getBean(EmployeeJpaSpecificationExecutor.class);
        System.out.println("------------------setup---------------------");
    }

    @After
    public void tearDown() {
        ctx = null;
        System.out.println("------------------tearDown---------------------");
    }

    @Test
    public void testPage() {
        Pageable pageable = new PageRequest(0, 5);//page:index是从零开始的

        /**
         * root:就是我们要查询的类型
         * query:添加查询条件
         * cb:构建Predicate
         */
        Specification<Employee> specification = new Specification<Employee>() {
            public Predicate toPredicate(Root<Employee> root,
                                         CriteriaQuery<?> query,
                                         CriteriaBuilder cb) {
                Path path = root.get("age");
                return cb.gt(path,50);
            }
        };

        Page<Employee> page = employeeJpaSpecificationExecutor.findAll(specification,pageable);
        System.out.println("getTotalPages--总页数" + page.getTotalPages());
        System.out.println("getTotalElements--总记录数" + page.getTotalElements());
        System.out.println("getNumber--当前第几页" + (page.getNumber() + 1));
        System.out.println("getContent--当前页面的集合" + page.getContent());
        System.out.println("getNumberOfElements--当前页面的记录数" + page.getNumberOfElements());
    }
}

【https://gitee.com/robei/SpringDataProject】







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Data JPA 是一个用于简化数据库访问的框架,它基于 JPA (Java Persistence API) 规范,提供了一种更简单、更高效的方式来访问和操作数据库。 下面是使用 Spring Data JPA 的一般步骤: 1. 添加依赖:在你的项目中,添加 Spring Data JPA 的依赖。你可以在 Maven 或 Gradle 配置文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> ``` 2. 配置数据库连接:在 `application.properties` 或 `application.yml` 文件中配置数据库连接信息,包括数据库 URL、用户名、密码等。 3. 创建实体类:创建与数据库表对应的实体类,并使用 JPA 注解来映射实体类与数据库表之间的关系。 ```java @Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private Integer age; // getters and setters } ``` 4. 创建 Repository 接口:创建一个继承自 `JpaRepository` 的接口,并通过方法命名规则或自定义查询方法来定义数据库操作。 ```java public interface UserRepository extends JpaRepository<User, Long> { List<User> findByAgeGreaterThan(Integer age); } ``` 5. 使用 Repository:在需要访问数据库的地方,注入 Repository 接口,并调用其中的方法进行数据库操作。 ```java @Service public class UserService { @Autowired private UserRepository userRepository; public List<User> getUsersByAgeGreaterThan(Integer age) { return userRepository.findByAgeGreaterThan(age); } } ``` 这只是 Spring Data JPA 的基本用法,你还可以使用更高级的特性,如分页、排序、复杂查询等。希望这些信息对你有帮助!如果你有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值