简体   繁体   中英

hibernate query involving foreign key

I am trying to write a hibernate query which selects a number of records from a table based on some criteria.

I have two relevant tables in my database

tbleventattendees which has the following fields - eventAttendeeRecord tblevent, tblmembers, and memberComments;

tblevent which has the following fields relevant field eventID which is the tblevent foreign key in tbleventattendees

What I am trying to do is write a HQL query which shows the attendees the attendees at specific event eg something like this SQL query select * from tbleventattendees where tblevent = 1

However, whilst this works as an SQL query in MySQL workbench when I try from tbleventattendees where tblevent = 1 in Netbeans run HQL Query I get the following error

org.hibernate.QueryException: Incorrect query syntax [ FROM
Society.Tbleventattendees as attendees where Tblevent =1
]
    at org.hibernate.hql.internal.classic.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:259)
    at org.hibernate.hql.internal.classic.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:209)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:126)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:88)
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:190)
    at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:301)
    at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236)
    at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1796)
Caused by: java.lang.NullPointerException
    at org.hibernate.sql.QuerySelect.appendTokens(QuerySelect.java:185)
    at org.hibernate.sql.QuerySelect.setWhereTokens(QuerySelect.java:103)
    at org.hibernate.hql.internal.classic.QueryTranslatorImpl.renderSQL(QueryTranslatorImpl.java:625)
    at org.hibernate.hql.internal.classic.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:243)
    ... 9 more

I think this is because I am using the value in the database in the query rather than the object reference as when I remove the =1 criteria I get the following value in that column

Society.Tblevent@6a2437ae

Can someone please help, I have read through lots of posts on here but struggling to work out the answer

You can write somthing like this:

Query query = session.createQuery("from Tbleventattendees attendees where attendees.tblevent.eventID  = :tbleventId ");
query.setParameter("tbleventId", "1");
List list = query.list();

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