2

I have two object Person and Student Mapped with hibernate in my database and another object ObjectPR which brings together the two for showing values of two objects in same view

and this is my code java for getting list of ObjectPR

StringBuffer sql = new StreingBuffer();  
  sql.append("select p.name as name, s.level as level from 
    person p
        join student s on s.pk_seq = p.fk_student ; ");
    

    SQLQuery query = getSession().createSQLQuery(sql.toString());
    query.addEntity(ObjectPR.class);
   
    List results = query.list();

and this is my ObjectPR Class

public class ObjectPR {

private String name;
private int level;

//getters setters ...
}

and I got this error

org.hibernate.MappingException: Unknown entity: model.ObjectPR

1 Answer 1

1

I think the NEW operator syntax would be adequate here. And also as Student and Person are mapped classes, do not use the native SQL but a normal HQL query:

StringBuffer sql = new StringBuffer();  
sql.append("select NEW model.ObjectPR(p.name as name, s.level as level)
from 
Person p join p.student s");


Query query = getSession().createQuery(sql.toString());

List<ObjectPR> results = query.list();

Remeber to add a proper constructro to the ObjectPR class.

Update

With native sql you would need to use an additional transformer like this:

StringBuffer sql = new StreingBuffer();  
sql.append("select p.name as name, s.level as level from 
person p
    join student s on s.pk_seq = p.fk_student ; ");


SQLQuery query = getSession().createSQLQuery(sql.toString());
query.setResultTransformer(Transformers.aliasToBean(ObjectPR.class));

List<ObjectPR> results = query.list();
Sign up to request clarification or add additional context in comments.

3 Comments

I think it's correct but I wouldn't use HQL I want solution with SQL and thank u very Much
the Transformers object is from with API ?
org.hibernate.transform.Transformers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.