我有两个实体,如 SmsOut 和 SmsIn 。两个实体之间的关系包含 OneToMany ,其中 smsIn.id 是主键, smsOut.sms_in_id 是外键。
现在我想在查询
上传递 smsIn.mobileNumber , smsIn.smsText 之类的参数等等SELECT so FROM SmsOut so order by id desc
以下是我的数据库图表:
被修改
以下是我的代码:
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)
请帮帮我。 谢谢
答案 0 :(得分:8)
您尚未解释SmsIn
与SmsOut
之间的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