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

怎甘沉沦 提交于 2019-12-19 05:51:34

问题


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.


回答1:


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




回答2:


You might find this helpful if using a existing table where you need only lookup the row, maybe do simple edits and you do not require the primary key

Move the @Id annotation to the unique key field and leave out the the primary key or make it a normal column

This work if your only doing lookups or editing that table, issue would arise will more complex operations, however you could define a second entity just to do the lookup and if you later need to do primary key operations re-lookup by primary key

@Entity 
class RealEntity implements Serializable {
    @Id
    private int id;

    @Column(...)
    private String uniqueSecondKey;

    ...
}


@Entity
class LookupEntity implements Serializable {
    @Column()
    private int id;

    @Id
    @Column(...)
    private String uniqueSecondKey;

    ...
}


来源:https://stackoverflow.com/questions/12258556/how-to-retrieve-record-in-hibernate-using-unique-key-instead-of-primary-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!