File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Object Relational Mapping and the fly likes Hibernate mapping Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Hibernate mapping" Watch "Hibernate mapping" New topic
Author

Hibernate mapping

jaisai vijay
Ranch Hand

Joined: Dec 17, 2009
Posts: 70
Hi,

I am new to hibernate.

Right now I am doing a simple project on hibernate. I have a simple question

I have two tables for example: TableA and TableB.
TableA has TableId and TableAName.
TableB has TableId, UserId and TableBScore.

Both TableIds are primary keys. Now I would like to retrieve TableAName, TableBScore based on UserId from TableB. I have a basic idea that how to write in SQL.
Select A.TableAName, B.TableBScore from TableA A,TableB B where A.TableId=B.TableB and B.UserId=1;

I was trying to do this using HQL I couldn't understand how to do this scenario. Can anyone help me in this?

Thanks for your help in advance.
Mark Spritzler
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 17249
    
    6

It depends on your mapping between the two objects. If you have mapped the association then it is very simple

Select A.TableAName, B.TableBScore from TableA A,TableB B where A.TableId=B.TableB and B.UserId=1;

in HQL it would be

"SELECT a.tableAName, b.tableBScore FROM ObjectA a JOIN ObjectB b WHERE b.userId=1"

tableAName and tableBScore are the attributes of your Objects, not field names here.

Hope that helps.

Also note that a projection query in Hibernate returns an Object[] for the records. If you want the full ObjectA with reference to ObjectB then just do

in HQL

"FROM ObjectA a JOIN FETCH ObjectB b WHERE b.userId=1"

Mark


Perfect World Programming, LLC - Two Laptop Bag - Tube Organizer
How to Ask Questions the Smart Way FAQ
xsunil kumar
Ranch Hand

Joined: Dec 14, 2009
Posts: 129
You need to join both entities. As per your code, we are assuming that A.TableId=B.TableB are same. Means both tables have same primary key. So this is one to one mapping and you can use primaryKey join annotation to map both entity. In that case you need to pass userId only in find method for table B and you will get data from Table A also.

Make sure table B is the owner of the relationship.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Hibernate mapping
 
Similar Threads
Hibernate 3.1
Hibernate one-to-on id mapping issue
FOREIGN KEY
Legacy and Hibernate1-2-M Mapping
Hibernate Composite & foreign key, please help