I am trying to work on an example for #Subselect using Hibernate documentaion.
I have created entities for Bid and Item as follows:
#Entity
public class Bid {
#Id
private int id;
#Column(name="item_id")
private int itemId;
#Column
private int amount;
//getters & setters
}
#Entity
public class Item {
#Id
private int id;
#Column
private String name;
//getters and setters
}
I have inserted some records in database tables for Bid and Item. Now I have created another entity to test the #Subselect as:
#Entity
#Subselect("select item.name name, max(bid.amount) amount, count(*) count " + "from item "
+ "join bid on bid.item_id = item.id " + "group by item.name")
#Synchronize({ "item", "bid" })
// tables impacted
public class Summary {
#Id #GeneratedValue
private int id;
#Column
private String name;
#Column
private String amount;
#Column
private String count;
//getters & setters
}
I am new to Hibernate so trying to create a sample program to test the feature of #Subselect.
public class AppTest {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
//createItemsAndBids(session);
Summary summary = new Summary();
session.save(summary);
session.getTransaction().commit();
HibernateUtil.getSessionFactory().close();
}
When I run this program I am getting below errors:
Hibernate: select hibernate_sequence.nextval from dual Hibernate:
insert into ( select item.name name, max(bid.amount) amount, count(*)
count from item join bid on bid.item_id = item.id group by item.name )
(amount, count, name, id) values (?, ?, ?, ?) Aug 10, 2014 1:24:31 PM
org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions WARN:
SQL Error: 904, SQLState: 42000 Aug 10, 2014 1:24:31 PM
org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions ERROR:
ORA-00904: "ID": invalid identifier
Caused by: java.sql.SQLSyntaxErrorException: ORA-00904: "ID": invalid
identifier
Please help me how to test the feature of #Subselect of hibernate
Also I tried using HQL, even then I am getting same error:
public class AppTest {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
//createItemsAndBids(session);
Query query = session.createQuery("from Summary");
List result = query.list();
System.out.println(result);
session.getTransaction().commit();
HibernateUtil.getSessionFactory().close();
}
Update:
The error I am getting with this HQL query is :
Aug 11, 2014 12:35:07 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Hibernate: select summary0_.id as id1_2_, summary0_.amount as amount2_2_, summary0_.count as count3_2_, summary0_.name as name4_2_ from ( select item.name name, max(bid.amount) amount, count(*) count from item join bid on bid.item_id = item.id group by item.name ) summary0_
Aug 11, 2014 12:35:07 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 904, SQLState: 42000
Aug 11, 2014 12:35:07 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: ORA-00904: "SUMMARY0_"."ID": invalid identifier
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:80)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:91)
at org.hibernate.loader.Loader.getResultSet(Loader.java:2065)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1862)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1838)
at org.hibernate.loader.Loader.doQuery(Loader.java:909)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
at org.hibernate.loader.Loader.doList(Loader.java:2553)
at org.hibernate.loader.Loader.doList(Loader.java:2539)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2369)
at org.hibernate.loader.Loader.list(Loader.java:2364)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:496)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:387)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:231)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1264)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:103)
at org.hibernate.tutorials.hibernate5.one.AppTest.main(AppTest.java:19)
Summary is supposed to be an immutable, read-only entity. It makes no sense to create a Summary. What you can do is create Items, create Bids, then query Summary instances.
EDIT: the error is pretty clear. Look at the generated SQL:
select summary0_.id as id1_2_, summary0_.amount as amount2_2_, summary0_.count as count3_2_, summary0_.name as name4_2_ from ( select item.name name, max(bid.amount) amount, count(*) count from item join bid on bid.item_id = item.id group by item.name ) summary0_
and at the error:
ORA-00904: "SUMMARY0_"."ID": invalid identifier
Your entity defines an id property:
#Id #GeneratedValue
private int id;
but the query of the Subselect annotation doesn't select any property named id:
select item.name name, max(bid.amount) amount, count(*) count from item
join bid on bid.item_id = item.id
group by item.name
You probably want your query to be
select item.id id, item.name name, max(bid.amount) amount, count(*) count from item
join bid on bid.item_id = item.id
group by item.id, item.name
Also note that the #GeneratedValue annotation doesn't make sense, since you can't persist instances of Summary, and Hibernate will thus never have to generate an ID for this entity.
Related
When running the method to get a patient address the hibernate says the table does not exist
For the relationship address to patient;
OneToMany(
targetEntity = Address.class,
cascade = CascadeType.ALL,
orphanRemoval = true
)
private Set<Address> addresses = new HashSet<Address>();
Join column in the address class
#ManyToOne
#JoinColumn (name = "Patient_Id", nullable = false)
private Patient patient;
When running a query to fetch the patient and then print out many address it says that the table does not exist.
Query to fetch patient
#NamedQuery(
name = "findPatientByFullName",
query = "select p from Patient p where p.firstName = :firstName AND p.lastName = :lastName"
)
System.out.println(sM.getPatientByFullName("Tom", "Test").get(0).getFirstName());
List<Patient> patients = sM.getPatientByFullName("Tom", "Test");
Get Patients by full name method
public List<Patient> getPatientByFullName(String firstName, String lastName) {
List patientsName = null;
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
TypedQuery query = session.getNamedQuery("findPatientByFullName");
query.setParameter("firstName", firstName);
query.setParameter("lastName", lastName);
patientsName = query.getResultList();
}catch (HibernateException e){
e.printStackTrace();
}return patientsName;
}
Getting a list of the patients, But then when I want to find a list of the address it errors.
Apr 29, 2019 10:58:38 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1146, SQLState: 42S02
Apr 29, 2019 10:58:38 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Table 'KYMb02vi2Z.Patient_PatientEmailAddress' doesn't exist
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:69)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.getResultSet(AbstractLoadPlanBasedLoader.java:419)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeQueryStatement(AbstractLoadPlanBasedLoader.java:191)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:121)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:86)
at org.hibernate.loader.collection.plan.AbstractLoadPlanBasedCollectionInitializer.initialize(AbstractLoadPlanBasedCollectionInitializer.java:87)
at org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:691)
at org.hibernate.event.internal.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:75)
at org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:2286)
at org.hibernate.collection.internal.AbstractPersistentCollection$4.doWork(AbstractPersistentCollection.java:585)
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:263)
at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:581)
at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:148)
at org.hibernate.collection.internal.AbstractPersistentCollection$1.doWork(AbstractPersistentCollection.java:177)
at org.hibernate.collection.internal.AbstractPersistentCollection$1.doWork(AbstractPersistentCollection.java:162)
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:263)
at org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:161)
at org.hibernate.collection.internal.PersistentSet.size(PersistentSet.java:168)
at SessionManager.main(SessionManager.java:45)
Caused by: java.sql.SQLSyntaxErrorException: Table 'KYMb02vi2Z.Patient_PatientEmailAddress' doesn't exist
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:970)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1020)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:60)
... 18 more
The stack trace error
See the error carefully. It shows you for the Patient_PatientEmailAddress,which is not found. so please check again your things in code and tell me. Also check your mapper that what you pass in it.
Thanks
I have a JPA entity MyEntity which includes a composite primary key in a #Embeddable class MyEntityPK.
I am using a native sql query in method getThreeColumnsFromMyEntity():
public List<MyEntity> getThreeColumnsFromMyEntity() {
List<MyEntity> results = em.createNativeQuery("select pid,name,dateofbirth from (select pid,name, dateofbirth,max(dateofbirth) "
+ "over(partition by pid) latest_dateofbirth from my_entity_table) where"
+ " dateofbirth = latest_dateofbirth;","myEntityMapping").getResultList();
return results;
My #SqlResultSetMapping:
#SqlResultSetMapping(
name = "myEntityMapping",
entities = {
#EntityResult(
entityClass = MyEntityPK.class,
fields = {
#FieldResult(name = "PID", column = "pid"),
#FieldResult(name = "NAME", column = "name")}),
#EntityResult(
entityClass = MyEntity.class,
fields = {
#FieldResult(name = "dateofbirth", column = "dateofbirth")})})
My JPA columns are named : #Column(name="DATEOFBIRTH"), "PID" and "NAME".
I tested my sql statement straight on the db and it works fine.
When i run it on Eclipse I get an Oracle error:
ORA-00911 and "Error code 911 , Query: ResultSetMappingQuery [..]
My guess is there is something wrong with the mapping but I cannot find out what it is.
I assume you get this error because you are missing the alias name for the subquery, so instead you can try this :
select
pid,
name,
dateofbirth
from
(
select
pid,
name,
dateofbirth,
max(dateofbirth) over(partition by pid) AS latest_dateofbirth
from
my_entity_table
) second_result
-- ^--------------- use an aliase name to the subquery
where
second_result.dateofbirth = latest_dateofbirth
-- ^----use the aliase name to reference to any of its fields, in your case 'dateofbirth'
Take a look about the error meaning here ORA-00911: invalid character tips
I am using JPA's eclipseLink to perform CRUD operations on my entities. I am facing following problem:
I have two tables in DB:
CREATE TABLE User (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(30) NOT NULL UNIQUE,
email VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
signUpDate timestamp NOT NULL DEFAULT NOW()
);
CREATE TABLE Friendship (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
friendsSince timestamp NOT NULL DEFAULT NOW(),
user1_Id INTEGER NOT NULL REFERENCES User(id),
user2_Id INTEGER NOT NULL REFERENCES User(id)
);
The corresponding Entities
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String email;
private String password;
#Temporal(value = TemporalType.DATE)
private Date signUpDate;
// constructors & setters & getters ...
}
#Entity
public class Friendship {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne
#JoinColumn(name="user1_Id", referencedColumnName = "id")
private User user1;
#ManyToOne
#JoinColumn(name="user2_Id", referencedColumnName = "id")
private User user2;
#Temporal(value = TemporalType.DATE)
private Date friendsSince;
// constructors & setters & getters ...
}
If I want to retrieve a list of some entities, according to "WHERE" clause of a query I get this "unknown state or association field [user1_Id] of class [com.filip.xxx.Friendship]" error.
Specifically:
I try to build this query:
Query query = mgr.createQuery("select f.id ,f.friendsSince, f.user1_Id, f.user2_Id from Friendship f where f.user1_Id = :user1Id and f.user2_Id = :user2Id or f.user1_Id = :user11Id and f.user2_Id = :user12Id");
and recieve this exception:
java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:
Exception Description: Error compiling the query [select f.id ,f.friendsSince, f.user1_Id, f.user2_Id from Friendship f where f.user1_Id = :user1Id and f.user2_Id = :user2Id or f.user1_Id = :user11Id and f.user2_Id = :user12Id], line 1, column 31: unknown state or association field [user1_Id] of class [com.filip.xxx.Friendship].
It seems like there is a problem with mapping attributes back to the entities, because I have no problem with persisting these two entities.
And interesting is that, if I run this query:
Query query = mgr.createQuery("select f from Friendship f");
It returns me the correct list of all friendships entities.
Notice that the reference variable's name in friendship entity(user1, user2) are not the same as corresponding table's variables (user1_Id, user2_Id). Before I have used the same variable names in entity as in table, but recieved this error at persisting friendship entity:
javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461):
org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'USER1_ID' in 'field list'
Error Code: 1054
Call: INSERT INTO FRIENDSHIP (FRIENDSSINCE, USER1_ID, USER2_ID) VALUES (?, ?, ?)
bind => [3 parameters bound]
Basically I don't understand, why eclipse link renames the entity's reference variables (user1 -> USER1_ID, user2 -> USER2_ID) when creating sql query, when it has than problems to map it back to the entities.
I have already tried these solutions:
Build query and return user1_Id column as user1 and user2_Id as user2
select f.id ,f.friendsSince, f.user1_Id as user1, f.user2_Id as user2 from Friendship f where f.user1_Id = :user1Id and f.user2_Id = :user2Id or f.user1_Id = :user11Id and f.user2_Id = :user12Id
but recieved the same IllegalArgumentException as above.
Could you help me solve this problem ?
Thanks
The exception
unknown state or association field [user1_Id] of class [com.filip.xxx.Friendship]
is received because you are using user1_Id name which is a database column name.
From the other hand ElementManager.createQuery() method expects JPQL string which accepts the entity's field name user1. Try to replace your query string with:
select f.id, f.friendsSince, f.user1, f.user2
from Friendship f
where f.user1 = :user1Id and
f.user2 = :user2Id or
f.user1 = :user11Id and
f.user2 = :user12Id
I have a problem with a Hibernate query that looks as follows:
List persons = getList("FROM creator.models.Person p WHERE p.lastName="+userName);
(the getList(String queryString) method just executes the query using a session factory.)
This is my person class:
#Entity
#Table(name="persons")
public class Person{
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name = "id")
private Long id;
#Column(name="first_name", nullable=false, updatable=true)
private String firstName;
#Column(name="last_name", nullable=false, updatable=true)
private String lastName;
/// etc
And this is the table:
CREATE TABLE persons(
id INTEGER NOT NULL AUTO_INCREMENT,
first_name CHAR(50),
last_name CHAR(50),
abbreviation CHAR(4),
PRIMARY KEY (id)
);
Searching for a person with the name TestName, I get an exception with this message:
org.hibernate.exception.SQLGrammarException: Unknown column 'TestName' in 'where clause'
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:82)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
//etc
The query created by Hibernate looks like this:
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select person0_.id as id8_, person0_.abbreviation as abbrevia2_8_, person0_.first_name as first3_8_, person0_.last_name as last4_8_ from persons person0_ where person0_.last_name=TestName
Dec 10, 2012 5:14:26 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
Searching for the id (...WHERE p.id="3") works fine, by the way!
I hope somebody knows what is going wrong because for me the query looks right and I can't find out why the lastName is seen as a column name suddenly.
You need to put userName in quotes:
"FROM creator.models.Person p WHERE p.lastName='"+userName+"'";
Or (which is much better) to use parameters
replace your hql with:
Query query = session.createQuery("from creator.models.Person p where p.lastName = ?")
.setParameter(0, userName);
List persons = query.list();
that way you also prevent sql-injection.
you need to wrap your parameter with single quotes:
List persons = getList("FROM creator.models.Person p WHERE p.lastName='"+userName+"'");
but much better with a parameterized query:
String hql = "FROM creator.models.Person p WHERE p.lastName= :userName";
Query query = session.createQuery(hql);
query.setString("userName",userName);
List results = query.list();
I am using Hibernate and I have this query:
List<Person> list = sess.createQuery("from Person").list();
With this statement, I get all persons from the database.
But now, I only want some persons.
My database scheme:
Project <- Project_Person -> Person
So I only want Persons which are a member of a project.
With the SQL statement on the database I get the desired result:
select * from Person inner join Project_Person
on person_id = id
where project_id = 1;
So I thought, I can write this with Hibernate:
List<Person> list =
sess.createQuery(
"from Person inner join Project_Person
on person_id = id
where project_id = "+projectId).list();
But here I get an error:
SERVE: Servlet.service() for servlet myproject3 threw exception
org.hibernate.hql.ast.QuerySyntaxException: unexpected token: on near line 1, column 65 [from com.mydomain.myproject.domain.Person inner join Project_Person on person_id = id where project_id = 1]
at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:54)
at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:47)
at org.hibernate.hql.ast.ErrorCounter.throwQueryException(ErrorCounter.java:82)
at org.hibernate.hql.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:284)
at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:182)
at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:101)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:124)
at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:156)
at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:135)
at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1770)
at sun.reflect.GeneratedMethodAccessor33.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:344)
at $Proxy26.createQuery(Unknown Source)
...
Does anyone has an idea what's wrong here?
Best Regards.
New Error:
SERVE: Servlet.service() for servlet myproject3 threw exception
org.hibernate.QueryException: could not resolve property: project of: com.mydomain.myproject.domain.Person [from com.mydomain.myproject.domain.Person p where p.project.id = :id]
n:m relation:
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "Project_Person",
joinColumns = {#JoinColumn(name="project_id", referencedColumnName="id")},
inverseJoinColumns = {#JoinColumn(name="person_id", referencedColumnName="id")}
)
private Set<Person> persons = new HashSet<Person>();
#ManyToMany(mappedBy="persons")
private Set<Project> projects = new HashSet<Project>();
Full Error
Hibernate: select project0_.id as id1_, project0_.createDate as create2_1_, project0_.description as descript3_1_, project0_.name as name1_ from Project project0_ where project0_.id=1
Hibernate: select person0_.id as id0_0_, project2_.id as id1_1_, person0_.email as email0_0_, person0_.firstName as firstName0_0_, person0_.lastName as lastName0_0_, project2_.createDate as create2_1_1_, project2_.description as descript3_1_1_, project2_.name as name1_1_ from Person person0_ inner join Project_Person projects1_ on person0_.id=projects1_.person_id inner join Project project2_ on projects1_.project_id=project2_.id where project2_.id=?
15.12.2010 16:42:26 org.apache.catalina.core.ApplicationDispatcher invoke
SERVE: Servlet.service() for servlet myproject3 threw exception
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.mydomain.myproject.domain.Person
HQL queries are written against the object model, not against the database schema.
Therefore your query depends on how you mapped the relationship between persons and projects. For example, in Person has a many-to-one relationship to Project via project property, the query will look like this:
List<Person> list = sess.createQuery(
"from Person p where p.project.id = :id")
.setParameter("id", projectId)
.list();
EDIT: In the case of many-to-many relationship you need
select p from Person p join p.projects proj where proj.id = :id
Also not that passing parameters via string concatenation is a bad practice, use setParameter() instead.