Java – select query using composite primary key
•
Java
In the spring MVC app using hibernate and JPA, I recently used the @ embeddable class to switch to the composite primary key Therefore, I need to update the JPA query that returns a given object based on its unique ID The following is the JPA code that worked in the past, but no results will be returned:
@SuppressWarnings("unchecked") public Concept findConceptById(BigInteger id) { Query query = this.em.createQuery("SELECT conc FROM Concept conc WHERE conc.id =:cid"); query.setParameter("cid",id); return (Concept) query.getSingleResult(); }@H_419_12@如何更改上面的查询,以便返回具有给定id的最新有效时间的Concept?请注意,id和effectiveTime是ConceptPK复合主键的两个属性,因此id和effectiveTime的属性定义和getter以及setter在ConceptPK类中,而不在Concept类中.
上面抛出的错误是:
Caused by: java.lang.IllegalArgumentException: Parameter value [786787679] did not match expected type [myapp.ConceptPK]@H_419_12@这是现在在Concept类中定义主键的方式:
private ConceptPK conceptPK;@H_419_12@这是ConceptPK类的代码:
@Embeddable class ConceptPK implements Serializable { @Column(name="id",nullable=false) protected BigInteger id; @Column(name="effectiveTime",nullable=false) @Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime") private DateTime effectiveTime; public ConceptPK() {} public ConceptPK(BigInteger bint,DateTime dt) { this.id = bint; this.effectiveTime = dt; } /** getters and setters **/ public DateTime getEffectiveTime(){return effectiveTime;} public void setEffectiveTime(DateTime ad){effectiveTime=ad;} public void setId(BigInteger id) {this.id = id;} public BigInteger getId() {return id;} @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final ConceptPK other = (ConceptPK) obj; if (effectiveTime == null) { if (other.effectiveTime != null) return false; } else if (!effectiveTime.equals(other.effectiveTime)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } @Override public int hashCode() { int hash = 3; hash = 53 * hash + ((effectiveTime == null) ? 0 : effectiveTime.hashCode()); hash = 53 * hash + ((id == null) ? 0 : id.hashCode()); return hash; } }@H_419_12@Solution
To use parts of a composite primary key in a JPA query, you must resolve them with their variable names:
public Concept findConceptById(BigInteger id) { Query query = this.em.createQuery("SELECT conc FROM Concept conc WHERE conc.conceptPK.id =:cid order by conc.conceptPK.effectiveTime desc"); query.setParameter("cid",id); return (Concept) query.getSingleResult(); }@H_419_12@我使用Concept作为实体名称,假设具有@Entity注释的类也被命名为Concept.
This question包含有关类似问题的信息,您可能会发现它很有用.
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码