JPA / Hibernate Native Queries无法识别带有EmbeddedId的参数

时间:2014-11-05 06:21:33

标签: java mysql hibernate jpa

我正在使用Hibernate / JPA来执行本机MySql查询。我想得到柜台的价值。

例如以下查询崩溃:

"SELECT sizeList FROM myCounter WHERE myColA=?1 AND myColB=?2 AND LIMIT 1"

错误:

java.lang.IllegalArgumentException: Parameter with that name [1] did not exist

来源:

方法:

@Override
public Long getSizeList(String myColA, String myColB) {
    Query q = em.createNativeQuery("MyCounter.getSizeList");
    q.setParameter(1, myColA);
    q.setParameter(2, myColB);
    return (Long) q.getSingleResult();
}

实体:

@Entity
@Table(name = "myCounter")
@XmlRootElement
@NamedNativeQueries({
@NamedNativeQuery(name = "MyCounter.getSizeList", query = "SELECT sizeList FROM myCounter WHERE myColA=?1 AND myColB=?2 AND LIMIT 1", resultClass = MyCounter.class)})
public class MyCounter implements Serializable {

private static final long serialVersionUID = 1L;
@EmbeddedId
protected MyCounterPK myCounterPK;
@Column(name = "sizeList")
private BigInteger sizeList;

public PostListCounterPTTESLTTT() {
}

...

public BigInteger getSizeList() {
    return sizeList;
}

}

嵌入式:

@Embeddable
public class MyCounterPK implements Serializable {
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 255)
@Column(name = "myColA")
private String myColA;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 50)
@Column(name = "myColB")
private String myColB;

public MyCounterPK() {
}

...

}

在这种情况下有谁知道如何使用setParameter()?

我尝试过:

//case 1:
"SELECT sizeList FROM myCounter WHERE myColA=?1 AND myColB=?2 AND LIMIT 1"
q.setParameter(1, myColA); //the same error

//case 2:
"SELECT sizeList FROM myCounter WHERE myColA=?1 AND myColB=?2 AND LIMIT 1"
q.setParameter("1", myColA); //the same error

//case 3:
"SELECT sizeList FROM myCounter WHERE myColA=:myColA AND myColB=:myColB AND LIMIT 1"
q.setParameter("myColA", myColA); //the same error

1 个答案:

答案 0 :(得分:-2)

而不是

Query q = em.createNativeQuery("MyCounter.getSizeList");

试试这个:

Query q = em.createNamedQuery("MyCounter.getSizeList");