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

spring data 接口之 Repository

2016-01-18 15:49 387 查看
Repository 是一个标记接口,继承该接口的Bean 会被Spring 容器识别为一个RepositoryBean,继承该接口的接口,有两大特点:

1. 使用Query 注解查询

2. 使用方法名查询:遵循SpringData 规范 命名,命名规则 :(find | get | read) + By + field ( + 条件关键字 + filed),注意条件关键字首字母大写

3. spring data repository 接口中的方法默认只有查询 和 保存的 事务, 没有更新和删除的事务

一 接口类声明:继承接口 Repository

package org.zgf.spring.data.dao;

import java.util.List;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.query.Param;
import org.zgf.spring.data.entity.StudentPO;
/**
* Repository 是一个标记接口,继承该接口的Bean 会被Spring 容器识别为一个RepositoryBean,继承该接口的接口,有两大特点:
* 1. 使用Query 注解查询
* 2. 使用方法名查询:遵循SpringData 规范 命名,命名规则 :(find | get | read) + By + field  ( + 条件关键字 + filed)
* 	      注意条件关键字首字母大写
* 3. spring data repository 接口中的方法默认只有查询 和 保存的 事务, 没有更新和删除的事务
* @author: zonggf
* @date: 2016年1月15日-下午12:57:23
*/
public interface IStudentBaseRepositoy extends Repository<StudentPO, Integer>{

// jpql= SELECT stu from StudentPO stu where stu.name = ?
public StudentPO findByName(String name);

// jpql= SELECT stu from StudentPO stu where stu.age > ?
public List<StudentPO> findByAgeGreaterThan(Integer age);

@Query(value="SELECT stu from StudentPO stu where student.id = ?1")
public StudentPO getStudentPO(Integer id);

@Query(value="SELECT stu from StudentPO stu where student.name = ?name")
public StudentPO getStudentPOByName(@Param("name") String name);

}


二 测试类

package org.zgf.spring.data.dao;

import java.util.List;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.zgf.spring.data.base.BaseTest;
import org.zgf.spring.data.dao.IStudentBaseRepositoy;
import org.zgf.spring.data.entity.StudentPO;

/**
* @ClassName: Test_IStudentBaseRepositoy
* @Description:
* @author: zonggf
* @date: 2016年1月15日-下午1:01:25
*/
public class Test_IStudentBaseRepositoy extends BaseTest{

@Autowired
private IStudentBaseRepositoy studentBaseRepositoy ;

@Test
public void test_findByName(){
String name = "zong";
StudentPO studentPO = this.studentBaseRepositoy.findByName(name);
System.out.println(studentPO);
}

@Test
public void test_greaterThan(){
List<StudentPO> students = this.studentBaseRepositoy.findByAgeGreaterThan(10);
for (StudentPO studentPO : students) {
System.out.println(studentPO);
}
}

@Test
public void test_query(){
StudentPO studentPO = this.studentBaseRepositoy.getStudentPO(1);
System.out.println(studentPO);
}

}


三 源代码下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: