Spring Data 단순 사용

22528 단어 자바
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 +
                    '}';
        }
    }
    

    스프링 데이터 테스트
    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);
    }
    
    EmployeeRepositor 테스트 클래스
    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());
            }
        }
    
    }
    EmployeeJpa Repository 류 의 실현
    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 층, upddata 에 트 랜 잭 션 추가
    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);
        }
    
    }
    

    EmployeeJpa Repository 테스트 클래스
    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());
        }
    }

    EmployeCrudRepository 인터페이스
    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 {
    }
    

    서비스 클래스
    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】

    좋은 웹페이지 즐겨찾기