概述
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());
}
}
}
具體規範
可以參照官網給出的命名規範.