Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve record in Hibernate using Unique key instead of Primary Key

Using session.load() or session.get() or any other method of org.hibernate.session, is it possible to get a record in hibernate based on the Unique column rather than the PK column value?

My requirement is that I need to get the records based on the unique column value and not the primary key.

It is like I don want to use the Criteria API. I need to use the session.get or load kind of methods. The answer that you have mentioned is for doing a search. But I am asking for getting a single record based on the unique key. Say for eg. My class Fruit has a PK column ID and a unique column fruitID which is unique key. I want to retrieve a unique record based on the fruitID and not ID. eg. Fruit fruit = (Fruit) session.get(Fruit.class,fruitID); here fruitID is the unique column of Fruit class.

like image 921
ranjani murali Avatar asked Sep 04 '12 07:09

ranjani murali


1 Answers

You mean something like this?

Criteria criteria = session.createCriteria(User.class);  
criteria.add( Restrictions.eqProperty("uniqueField", "value") )
List results = criteria.list();
Object myObj = results.get(0);

Check the hibernate manual for more info about criteria

like image 91
kothvandir Avatar answered Sep 16 '22 14:09

kothvandir