简体   繁体   中英

Hibernate - Fetching entity having a composite primary key using any one of the primary key

I have an entity which has composite primary key. So i created primary class for the entity class with @EmbeddedId annotation.

I need help. While fetching that entity, is it possible to fetch the one of the primary key?

I tried to pass one of primary key to fetch that entity, other primary keys are set to zero and no result obtained.

Is there any way to fetch an entity (which has composite primary key) by specifying one of the primary key for that entity?

Sample code:

EmbeddedRiskDetailPK riskDetailPK = new EmbeddedRiskDetailPK ();
riskDetailPK.setRiskId(riskId);

Criteria criteria = hibernateDBSession.createCriteria(RiskDetail.class, "riskDetail")
                                .add(Restrictions.eq("riskDetail.embeddedRiskDetailPK ",riskDetailPK ));
isRecordCount = criteria.uniqueResult() != null ? ((Number)criteria.uniqueResult()).longValue() : 0;

1) You can have only one primary key for entity

2) If you compare by primary key, you compare by whole primary key, so you must give complete entity

3) If you specify ID by @IdClass annotation, you have fields on entity representing each component of primary key, and you can refer them in HQL or Criteria, so maybe you should consider redeign? I've made an example in that answer: Why is my EmbeddedId in hibernate not working?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM