如何在自定义spring存储库中实现自定义方法?

时间:2015-12-21 16:48:19

标签: java spring spring-data-jpa

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

我有Customer类:

@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);
}

它扩展了CrudRepositoryCustomerCustom

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

我写了

public class CustomerCustomImpl implements CustomerCustom {

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


}

bot不知道,在实施中写些什么。如何联系客户?

2 个答案:

答案 0 :(得分: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将使用注释中的查询来处理您的实现。

答案 1 :(得分:1)

您需要在类中为您的查询注入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