Spring JPA/ Hibernate : How to map polymorphic relation on non primary columns

你说的曾经没有我的故事 提交于 2019-12-24 18:32:08

问题


class B{
@Any(metaColumn = @Column(name = "ITEM_TYPE"))
@AnyMetaDef(idType = "long", metaType = "string",
        metaValues = {
                @MetaValue(targetEntity = A.class, value = "A")
        })
@Cascade( { org.hibernate.annotations.CascadeType.ALL})
@JoinColumn(name = "ITEM_ID")
private A a;
...
...
}

I'm trying to Join table A and table B where B.item_type ='A' is constant and B.item_id= A.id.

It is throwing me

Caused by: org.hibernate.MappingException: Foreign key (FKi1uuph2wrvxtx66s7n7i1s09a:B [item_type,item_id])) must have same number of columns as the referenced primary key (A [id])

Any help on How shall i map this using spring jpa and hibernate?


回答1:


Your question is not to clear but below may help

Join table A and table B where B.item_type ='A' is constant and B.item_id= A.id.

1) B.item_type = 'A' : Create A enum and pass it while querying 2) B.item_id=A.id :

lets says it is one to many relation.

Class B{

 @OneToMany
 @Cascade(org.hibernate.annotations.CascadeType.DETACH)
 @JoinColumns(@JoinColumn(name = "id", referencedColumnName = "item_id", insertable = false, updatable = false))
List<A> retunedList;

}

In case when it will be one to one, Change Annotaion to @onetoOne and make return type A instead of list.




回答2:


I was able to fix this by a alternate approach where I made the associated entity as @Transient and then I saved that transient entity on @PostPersist call from parent entity by adding an EntityListener class.



来源:https://stackoverflow.com/questions/49840985/spring-jpa-hibernate-how-to-map-polymorphic-relation-on-non-primary-columns

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