简体   繁体   中英

JPA/Hibernate Native Queries do not recognize Parameters with EmbeddedId

I am using Hibernate/JPA to execute native MySql queries. I want to get the value of the counter.

For example the following query crash:

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

Error:

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

Sources:

Method:

@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:

@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:

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

...

}

Does anyone know how to use setParameter() in this case ?

I tried with:

//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

Instead of

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

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM