您的位置:首页 > 编程语言 > Java开发

Spring Data自定义Repository接口方法定义规范

2017-07-29 12:28 671 查看

概述

Repository 接口是 Spring Data 的一个核心接口,它不提供任何方法,开发者需要在自己定义的接口中声明需要的方法 public interface Repository

@Entity
public class Employee {

private Integer id;
private String name;
private Integer age;

//省略getter/setter方法
}
Repository接口方法的具体命名.
@RepositoryDefinition(domainClass = Employee.class, idClass = Integer.class)
public interface EmployeeRepository { //extends Repository<Employee,Integer>{

public Employee findByName(String name);

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

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

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

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

}


这里是测试方法:

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() {
//org.springframework.data.jpa.repository.support.SimpleJpaRepository@1a9c0566
System.out.println(employeeRepository);
Employee employee = employeeRepository.findByName("zhangsan");
System.out.println("id:" + employee.getId()
+ " , name:" + employee.getName()
+ " ,age:" + employee.getAge());
}

@Test
public void testFindByNameStartingWithAndAgeLessThan() {
List<Employee> employees = employeeRepository.findByNameStartingWithAndAgeLessThan("test", 22);

for (Employee employee : employees) {
System.out.println("id:" + employee.getId()
+ " , name:" + employee.getName()
+ " ,age:" + employee.getAge());
}
}
}


具体规范

可以参照官网给出的命名规范.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring