Java 如何在具有复合 PK (Hibernate JPA) 的实体中使用“findBy”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35054372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use "findBy" in an Entity with a Composite PK (Hibernate JPA)
提问by dmorar
I am learning with bootspring.
我正在用 bootspring 学习。
findByDate(int date);
used to work until I've moved int Date
into the inner class.
findByDate(int date);
以前一直工作,直到我int Date
进入内部课程。
Now I can save new entries but I can't retrive them byDate
现在我可以保存新条目,但不能按日期检索它们
What do I need to change?
我需要改变什么?
@Transactional
public interface ExpirationDAO extends JpaRepository<ExpirationDTO, Long> {
public ExpirationDTO findByDate(int date);
}
and
和
@Embeddable
public static class IdKey implements Serializable{
@NotNull
int date;
@ManyToOne
ProductDTO product;
public IdKey(){
}
//setters and getters
}
@EmbeddedId
private IdKey id;
@NotNull
int units;
public ExpirationDTO(){
}
//setters and getters
}
throws this exception:
抛出这个异常:
org.springframework.data.mapping.PropertyReferenceException: No property date found for type ExpirationDTO!
采纳答案by Javasick
You should include name of embedded key class in repository instead of Long. Try this one (not tested):
您应该在存储库中包含嵌入式密钥类的名称而不是 Long。试试这个(未测试):
public interface ExpirationDAO extends JpaRepository<ExpirationDTO, IdKey> {
public List<ExpirationDTO> findByIdDate(int date);
}
There after findBy
Id
is yours EmbeddedId
and Date
is attribute of embeddable class. And one more thing: if you use only part of embedded key, you can't expect only one result...
之后findBy
Id
是你的EmbeddedId
,Date
是可嵌入类的属性。还有一件事:如果您只使用嵌入式密钥的一部分,您不能期望只有一个结果......
回答by Alifia
You should include name of embedded key class in repository and also add an underscore (_)
您应该在存储库中包含嵌入式密钥类的名称,并添加一个下划线 (_)
Tested below:
测试如下:
public interface ExpirationDAO extends JpaRepository<ExpirationDTO, IdKey> {
public List<ExpirationDTO> findByIdKey_Date(Date date);
}