Spring Data简单使用

Spring Data JPA 快速起步

  • 开发环境搭建
  • Spring Data JPA开发
Maven依赖添加

      org.springframework.data
      spring-data-jpa
      1.11.7.RELEASE
    

    
      org.hibernate
      hibernate-entitymanager
      5.0.12.Final
    
Beans-new.xml




    
    

    
    
        
        
        
        
    

    
    
        
        
            
        
        

        
            
                org.hibernate.cfg.ImprovedNamingStrategy
                org.hibernate.dialect.MySQL5InnoDBDialect
                true
                true
                update
            
        

    

    
    
        
    

    
    

    
    

    

实体类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 findByName(String name);

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

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

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

    //where name in (?,?...) and age < ?
    List findByNameInAndAgeLessThan(List 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 queryParam1(String name, Integer age);

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

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

    @Query("select o from Employee o where o.name like %:name%")
    List 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 list = employeeRepository.findByNameStartingWithAndAgeLessThan("test", 23);
        for (Employee employee : list) {
            System.out.println(employee.toString());
        }
    }

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

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

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

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

    @Test
    public void queryParam2() throws Exception {
        List 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 {
}
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 {
}

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 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 employees = new ArrayList();

        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 {
}
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 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 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, JpaSpecificationExecutor {
}
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 specification = new Specification() {
            public Predicate toPredicate(Root root,
                                         CriteriaQuery query,
                                         CriteriaBuilder cb) {
                Path path = root.get("age");
                return cb.gt(path,50);
            }
        };

        Page 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】







你可能感兴趣的:(java)