Spring Data --- Repository接口

Rpository接口概述

  • Repository 接口是Spring Data 的一个核心接口 ,他不提供任何的方法,开发者需要在自己定义的接口中声明需要的方法
public interface Repository<T,Id extends Serializable>{}
  • Spring Data可以让我们值定义接口,只要遵循Spring Data的规范,就无需实现类
    -与继承Repository 等价的一种方式 ,就是在持久层接口上使用@RepositoryDefinition注解,并为其指定domainClass 和idClass属性。

Repository的子接口

  • Repository 提供了最基本的数据访问功能,其子接口扩展了一些功能。

    • Repository: 仅仅是一个标识,表明任何继承他的均为仓库接口类
    • CrudRepository: 继承Repository ,实现了一组CRUD相关的方法
    • PagingAndSortingRepository:继承CrudRepository ,实现了一组分页排序相关的方法
    • JpaRepository:继承PagingAndSortingRepository,实现一组JPA规范的相关方法
    • 自定义的 XxxxRepository 需要继承JpaRepository,这样的接口就具备了通用的数据访问控制层的能力
    • JpaSpecificationExecutor: 不属于Repository体系,实现了一组JPA Criteria查询相关的方法

实例讲解

  • Person 实体类
@Table(name = "JPA_PERSON")
@Entity
public class Person {
    private Integer id;
    private String name;
    private String email;
    private Date brith;
    private Address address;
    @GeneratedValue // 生成策略
    @Id
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Date getBrith() {
        return brith;
    }

    public void setBrith(Date brith) {
        this.brith = brith;
    }
    @JoinColumn(name="ADDRESS_ID")
    @ManyToOne
    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Person [id=" + id + ", name=" + name + ", email=" + email + ", brith=" + brith + ", address=" + address
                + "]";
    }
  • Repository 接口实现类
public interface PersonRepository extends  Repository{
    Person getByName(String name);
}
  • 测试类
public class SpringDataTest {
   private ApplicationContext ctx = null ;
   PersonRepsotory personRepsotory = null;
    {
       ctx =  new ClassPathXmlApplicationContext("applicationContext.xml");
         personRepsotory = ctx.getBean(PersonRepsotory.class);
       }
 @Test
   public void  testHelloWorldSpringData(){

        Person person = personRepsotory.getByName("aa");
        System.out.println(person);
   }

@Test
    public void test() throws SQLException {
        DataSource dataSource = ctx.getBean(DataSource.class);
        System.out.println(dataSource.getConnection());
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章