如何在jpa查询上传递参数?

时间:2013-08-11 13:13:04

标签: java sql-server jpa-2.0

我有两个实体,如 SmsOut SmsIn 。两个实体之间的关系包含 OneToMany ,其中 smsIn.id 主键 smsOut.sms_in_id 外键

现在我想在查询

上传递 smsIn.mobileNumber smsIn.smsText 之类的参数等等
SELECT so FROM SmsOut so order by id desc

以下是我的数据库图表:

enter image description here

被修改

以下是我的代码:

String sql = "SELECT so FROM SmsOut so WHERE so.smsInId.mobileNumber =:mobileNumber AND so.smsInId.smsText =:smsText AND so.smsInId.shortCode =:shortCode between so.smsOutDate =:startDate and so.smsOutDate =:endDate order by id desc";
    Query query = em.createQuery(sql);
    query.setParameter("mobileNumber", mobileNumber);
    query.setParameter("smsText", smsText);
    query.setParameter("shortCode", shortCode);
    query.setParameter("smsOutDate", startDate);
    query.setParameter("smsOutDate", endDate);
    smsOutList = query.getResultList();

,例外是:

SEVERE: line 1:188: expecting "and", found '='
java.lang.IllegalArgumentException: org.hibernate.hql.ast.QuerySyntaxException: expecting "and", found '=' near line 1, column 188 [SELECT so FROM     com.f1soft.SMSC.entities.SmsOut so WHERE so.smsInId.mobileNumber =:mobileNumber AND so.smsInId.smsText =:smsText AND so.smsInId.shortCode =:shortCode between so.smsOutDate =:startDate and so.smsOutDate =:endDate order by id desc]
at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:624)
at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:96)

请帮帮我。 谢谢

3 个答案:

答案 0 :(得分:8)

您尚未解释SmsInSmsOut之间的JPA关系,因此我假设SmsOut的{​​{1}}与getSmsIn()有关系id } field。

如果您有EntityManager em,则可以拨打em.createQuery,类似于SQL prepare,然后setParameter

TypedQuery<SmsOut> q = em.createQuery("SELECT so FROM SmsOut so WHERE so.smsIn.mobileNumber = :number ORDER BY id DESC");
q.setParameter("number", "12345678");
List<SmsOut> results = q.getResultList();

有关指定参数的不同方法,请参阅the Javadoc for Query

答案 1 :(得分:1)

SELECT so FROM SmsOut so WHERE smsIn.mobileNumber = ? AND smsIn.smsText =? order by id desc

更换?签署适当的值。

答案 2 :(得分:0)

之间是问题所在:

between so.smsOutDate =:startDate and so.smsOutDate =:endDate 

尝试

so.smsOutDate between  =:startDate and =:endDate