JPAController getReference problem with BigDecimal
I have one JPAController Class that having create method to save record in Parent and Detail Table. The Primary key is of BigDecimal type with 8 scale and 15 precision in both the tables. Now my Question is When i call the create method i get the error in public T getReference(Class entity Class, Object primary Key) as BigDecimal with 3 scale and 5 Precision,if take 42.20112012 as reference key then i got error as,
Caused by: javax.persistence.EntityNotFoundException: Could not find entitiy for id: 42.201
My create method in JPAC开发者_开发百科ontroller Class is as below , in which i want to insert record in RuleApplGroupMst(Parent Table) and RuleGroupRelation(Detail Table) Tables,
Collection<RuleGroupRelation> attachedRuleGroupRelationCollection = new ArrayList<RuleGroupRelation>();
for (RuleGroupRelation RuleGroupRelationCollectionRuleGroupRelationToAttach : RuleApplGroupMst.getRuleGroupRelationCollection()) {
RuleGroupRelationCollectionRuleGroupRelationToAttach = em.getReference(RuleGroupRelationCollectionRuleGroupRelationToAttach.getClass(),RuleGroupRelationCollectionRuleGroupRelationToAttach.getRgrSrgKey());
attachedRuleGroupRelationCollection.add(RuleGroupRelationCollectionRuleGroupRelationToAttach);
}
Thanks for any help.....
EntityManager.getReference
relies on the equality of primary keys to fetch the corresponding entity from the database. When you choose BigDecimal
s as your primary key, then you must use the exact representation of the BigDecimal
to obtain a reference to an entity. You cannot use an appromixation. In simpler words, going by the definition of the equals()
method of BigDecimal:
Compares this BigDecimal with the specified Object for equality. Unlike compareTo, this method considers two BigDecimal objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method).
the primary key values used as the argument in EntityManager.getReference
must match the stored primary key values in scale and in value, in order to allow the JPA provider to return the reference.
Therefore, you ought to use the same representation for 42.201 as originally stored in the database, in order to retrieve the entity successfully.
I got the answer,
In My Case, i have created the user defined method in JPAController Class as below,
public void create_custom(RuleApplGroupMst RuleApplGroupMst) {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
em.persist(RuleApplGroupMst);
utx.commit();
} catch (Exception ex) {}
and then declare OneToMany Relationship in Entity Bean as,
@OneToMany(cascade = CascadeType.ALL,mappedBy = "ragmSrgKey")
and then i call create_custom method by managed bean.
It works with all type(including BigDecimal) of Primary/Reference Key.
精彩评论