我有两个实体,例如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)
请帮我。
谢谢
最佳答案
您尚未解释SmsIn
和SmsOut
之间的JPA关系,所以我假设SmsOut
具有getSmsIn()
且在id
字段上具有关系。
拥有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
。