Spring 三种数据库连接方式、传统连接、JdbcTemplate、Spring Jpa data(下)

我现在经常用到Spring JPA Data

和逆向工程一样方便

 

GitHub地址:https://github.com/binlian/binglian-Spring-JPA-Data

它有自己的定义规则,可以不用在写那些SQL语句了,

可以根据id name来查询 两个一起查询等

public Employee findByName(String name);

这传代码就是 根据name查询数据

Spring 三种数据库连接方式、传统连接、JdbcTemplate、Spring Jpa data(下)_第1张图片

 

Spring 三种数据库连接方式、传统连接、JdbcTemplate、Spring Jpa data(下)_第2张图片

 

Maven jar引入 放入pom.xml

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

        
            org.hibernate
            hibernate-entitymanager
            4.3.6.Final
        

 

Spring 三种数据库连接方式、传统连接、JdbcTemplate、Spring Jpa data(下)_第3张图片

配置文件

bean-new.xml

其实这些配置都是一环扣一环的

true  打印SQL语句
true  这个是代码格式化





    
    
        
        
        
        
    

    
    
        
        
            
        
        

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

    

    
    
        
    

    
    

    
    

    

然后看下代码

使用Jpa 需要继承Repository

也可以使用注解方式(添加注解能到达到不用extends Repository的功能)

@RepositoryDefinition(domainClass = Employee.class, idClass = Integer.class)

 

Repository类的定义:
public interface Repository {

}

Repository是一个空接口,标记接口
没有包含方法声明的接口

 

package com.binglian.repository;

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 com.binglian.domain.Employee;

import java.util.List;


@RepositoryDefinition(domainClass = Employee.class, idClass = Integer.class)
public interface EmployeeRepository { //extends Repository{

    public Employee findByName(String name);

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

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

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

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

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

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

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

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

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

    @Query(nativeQuery = true, value = "select count(1) from employee")
    public long getCount();

    @Modifying
    @Query("update Employee o set o.age = :age where o.id = :id")
    public void update(@Param("id")Integer id, @Param("age")Integer age);



}

test类

package com.imooc.repository;


import org.hibernate.action.internal.EntityIncrementVersionProcess;
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 com.binglian.domain.Employee;
import com.binglian.repository.EmployeeJpaRepository;
import com.binglian.repository.EmployeePagingAndSortingReposity;
import com.binglian.repository.EmployeeRepository;
import com.binglian.service.EmployeeService;

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

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:"+employee);
    	
    	System.out.println("emloyee(10)"+employeeJpaRepository.exists(10));
    	System.out.println("emloyee(102)"+employeeJpaRepository.exists(102));
    }
   
}

 

 

更新删除 需要@Modifying

也需要service 才可以成功运行
 

Spring 三种数据库连接方式、传统连接、JdbcTemplate、Spring Jpa data(下)_第4张图片

 

@Modifying
@Query("update Employee o set o.age = :age where o.id = :id")
 public void update(@Param("id")Integer id, @Param("age")Integer age);

 

 

自动创建数据库 根据实体类自动创建数据库

package com.binglian.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

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

    private Integer id;

    private String name;

    private Integer age;

    @GeneratedValue
    @Id
    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;
    }
}

 

 

 

CrudReository

Spring 三种数据库连接方式、传统连接、JdbcTemplate、Spring Jpa data(下)_第5张图片

 

package com.binglian.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.binglian.domain.Employee;

public interface EmployeeJpaRepository extends JpaRepository{

}

test类

save使用

employeeService.save(employees);

package com.imooc.repository;


import org.hibernate.action.internal.EntityIncrementVersionProcess;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.binglian.domain.Employee;
import com.binglian.repository.EmployeeRepository;
import com.binglian.service.EmployeeService;

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

public class EmployeeCrudRepositoryTest {


    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  testSave(){
    	
    	List employees=new ArrayList();
    	
    	Employee employee=null;
    	for(int i=0;i<100;i++){
    		employee=new Employee();
    		employee.setAge(100-i);
    		employee.setName("test"+i);
    		employees.add(employee);
    	}
    	
    	employeeService.save(employees);
    }
}

 

 

这个分页在工作也比较常用

分页、排序

Spring 三种数据库连接方式、传统连接、JdbcTemplate、Spring Jpa data(下)_第6张图片

package com.binglian.repository;

import org.springframework.data.repository.PagingAndSortingRepository;

import com.binglian.domain.Employee;

public interface EmployeePagingAndSortingReposity extends PagingAndSortingRepository{

}

 

Test类

Sort.Direction.DESC,"id"根据id正序
Sort.Order order=new Sort.Order(Sort.Direction.DESC,"id");
Sort sort=new Sort(order);
       

//page:index是0开始的,不是从1开始的

Pageable pageable=new PageRequest(0, 5);

Page page=employeePagingAndSortingReposity.findAll(pageable);
    

Page 封装了页数这些属性
System.out.println("查询的总页数"+page.getTotalPages());
System.out.println("查询的总记录数"+page.getTotalElements());

 

package com.imooc.repository;


import org.hibernate.action.internal.EntityIncrementVersionProcess;
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 com.binglian.domain.Employee;
import com.binglian.repository.EmployeePagingAndSortingReposity;
import com.binglian.repository.EmployeeRepository;
import com.binglian.service.EmployeeService;

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

public class EmployeePagingSortingRepositoryTest {


    private ApplicationContext ctx = null;

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

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

    
    
    @Test
    public void testPage(){
    	
    	//根据id正序排序
    	Sort.Order order=new Sort.Order(Sort.Direction.DESC,"id");
    	Sort sort=new Sort(order);
    	
    	//page:index是0开始的,不是从1开始的
    	Pageable pageable=new PageRequest(0, 5);
    	Page page=employeePagingAndSortingReposity.findAll(pageable);
    
    	System.out.println("查询的总页数"+page.getTotalPages());
    	System.out.println("查询的总记录数"+page.getTotalElements());
    	System.out.println("查询的当前第几页"+page.getNumber());
    	System.out.println("查询的当前页面的集合"+page.getContent());
    	System.out.println("查询的当前页面的记录数"+page.getNumberOfElements());
    	
    }
   
}

 

 

JpaRepository

 

Spring 三种数据库连接方式、传统连接、JdbcTemplate、Spring Jpa data(下)_第7张图片

package com.binglian.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.binglian.domain.Employee;

public interface EmployeeJpaRepository extends JpaRepository{

}

JpaSpecificationRepository

这个是多继承可以使用两个方法

package com.binglian.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

import com.binglian.domain.Employee;

/**
 * 也是可以多继承
 * @author binglian
 *
 */
public interface EmployeeJpaSpecificationExecutorRepository 
		extends JpaRepository,JpaSpecificationExecutor{

}

 

 

/**
    	 * root:就是我们要查询的类型(Employee)
    	 * query:添加查询天剑
    	 * cb:构建Predicate
    	 */
    	Specification specification=new Specification() {

			@Override
			public Predicate toPredicate(Root root,
						CriteriaQuery query, 
						CriteriaBuilder cb) {

				Path path=root.get("age");
				
				
				return cb.gt(path, 50);//age大于20;
			}
		
    	};
    	
    	Page page=employeeJpaSpecificationExecutorRepository.findAll(specification,pageable);
    	
package com.imooc.repository;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

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 org.springframework.data.jpa.domain.Specification;

import com.binglian.domain.Employee;
import com.binglian.repository.EmployeeJpaRepository;
import com.binglian.repository.EmployeeJpaSpecificationExecutorRepository;

public class EmployeeJpaSpecificationExecutorRepositoryTest {

	private ApplicationContext ctx = null;

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

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

    
    /**
     * 分页
     * 排序
     * 查询条件
     */
    @Test
    public void testQuery(){
    	//根据id正序排序
    	Sort.Order order=new Sort.Order(Sort.Direction.DESC,"id");
    	Sort sort=new Sort(order);
    
    	
    	
    	//page:index是0开始的,不是从1开始的
    	Pageable pageable=new PageRequest(0, 5);
    	
    	
    	/**
    	 * root:就是我们要查询的类型(Employee)
    	 * query:添加查询天剑
    	 * cb:构建Predicate
    	 */
    	Specification specification=new Specification() {

			@Override
			public Predicate toPredicate(Root root,
						CriteriaQuery query, 
						CriteriaBuilder cb) {

				Path path=root.get("age");
				
				
				return cb.gt(path, 50);//age大于20;
			}
		
    	};
    	
    	Page page=employeeJpaSpecificationExecutorRepository.findAll(specification,pageable);
    	
//    	Page page=employeeJpaSpecificationExecutorRepository.findAll(pageable);
    
    	System.out.println("查询的总页数"+page.getTotalPages());
    	System.out.println("查询的总记录数"+page.getTotalElements());
    	System.out.println("查询的当前第几页"+page.getNumber());
    	System.out.println("查询的当前页面的集合"+page.getContent());
    	System.out.println("查询的当前页面的记录数"+page.getNumberOfElements());
    	
    }
}

 

你可能感兴趣的:(springboot)