gpt4 book ai didi

java - 使用复合主键的 SELECT 查询

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:10:24 25 4
gpt4 key购买 nike

在使用 hibernate 和 jpa 的 spring mvc 应用程序中,我最近使用 @Embeddable 切换到复合主键类(class)。因此,我需要更新 JPA 查询,该查询根据其唯一 ID 返回给定对象。以下是曾经有效但不再返回结果的 JPA 代码:

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

如何更改上述查询,以便它返回具有最新 effectiveTime 的概念对于给定的 id ? 注意 ideffectiveTimeConceptPK 的两个属性复合主键,因此是 id 的属性定义以及 getter 和 setter和 effectiveTimeConceptPK类而不在 Concept 中类(class)。

上面抛出的错误是:

Caused by: java.lang.IllegalArgumentException:  
Parameter value [786787679] did not match expected type [myapp.ConceptPK]

这就是现在在 Concept 中定义主键的方式类:

private ConceptPK conceptPK;  

这是 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;
}
}

最佳答案

要在 JPA 查询中使用部分复合主键,您必须使用其变量名来解决它们:

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

我使用 Concept 作为实体名称,假设带有 @Entity 注释的类也被命名为 Concept

This question包含有关类似问题的信息,您可能会发现它很有用。

关于java - 使用复合主键的 SELECT 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23480307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com