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());
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章