【问题标题】:How to implement custom method in custom spring repository? [duplicate]如何在自定义 Spring 存储库中实现自定义方法? [复制]
【发布时间】:2016-03-27 19:36:21
【问题描述】:

假设我想要一个方法,获取超级主客户,有id=0

我有客户类:

@Entity
public class Customer {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long id;
    private String firstName;
    private String lastName;

    protected Customer() {}

    public Customer(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return String.format(
                "Customer[id=%d, firstName='%s', lastName='%s']",
                id, firstName, lastName);
    }

}

According to dox,我应该创建两个额外的类/接口。

所以我有CustomerCustom接口:

public interface CustomerCustom {

   Customer getVeryMainCustomer();

}

在哪里声明了一个方法getVeryMainCustomer

然后我的曝光仓库界面变成如下:

public interface CustomerRepository extends CrudRepository<Customer, Long>, CustomerCustom {

    List<Customer> findByLastName(String lastName);
}

它同时扩展了CrudRepository 和我的CustomerCustom

但接下来我应该实现CustomerCustom。但是该怎么做呢?

我写的

public class CustomerCustomImpl implements CustomerCustom {

   @Override
   public Customer getVeryMainCustomer() {
      return null;
   }


}

bot 不知道,在实现中要写什么。如何接触客户?

【问题讨论】:

  • 该方法应该做什么?您是否考虑过使用@Query?什么是表结构或Customer
  • Customer的表结构是JPA在Customer类定义的基础上自动定义的。该方法应该选择ID = 0的客户。是的,如果可能的话,我想使用@Query

标签: java spring spring-data-jpa


【解决方案1】:

@Query:

public interface CustomerRepository extends CrudRepository<Customer, Long> {

    List<Customer> findByLastName(String lastName);

    @Query("SELECT c FROM Customer c WHERE c.id = 0")
    Customer getVeryMainCustomer();
}

Spring-data 将使用注释中的查询为您处理实现。

【讨论】:

  • 但是这是在扩展接口里面。是否可以在我的自定义存储库实现中使用@Query
  • 很抱歉,我不明白,为什么您还需要使用此解决方案的自定义存储库 impl?
  • 好的,你是对的,根据所述的问题,这就足够了。但是假设我只想实现存储库并添加一些查询?
  • 然后在 spring 的界面中使用 @Query 并像你一样在你的 impl 中做你的事情。
【解决方案2】:

您需要在类中为您的查询注入 entitymanager

public class CustomerCustomImpl implements CustomerCustom {

    //This is my tip, but not a must...
    @PersistenceContext
    private EntityManager em;

    public void save(...){
        //do what you need here

       Employee employee = em.find(Employee.class, 1);// example of employye
    }
}

http://www.objectdb.com/java/jpa/persistence/retrieve

【讨论】:

    猜你喜欢
    • 2017-02-09
    • 2018-01-05
    • 2017-03-26
    • 2017-06-18
    • 2015-05-10
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 2015-08-17
    相关资源
    最近更新 更多