Is Hibernate ManyToMany self-join possible for non-key columns? getting mappingException

耗尽温柔 提交于 2020-02-02 10:08:12

问题


I am having following problem. I have a user entity that has a many to many relationship with other user entities. Hence I want to make a self-join with manytomany annotation. This relation is based on already existing table that is used across the system so I cannot make changes to the DB at all. So we have 2 tables User(Id, ShortName) and UserLink(ParentId, ChildId).

The annotation of ID is assigned to ShortName, but the actual keys in both User and UserLink are ID from User and ParentId and ChildId from UserLink.

I am trying to handle this the following way from the User entity:

@Id
@Column(name = "ShortName")
private String shortName;

@Column(name = "Id")
private long id;

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "UserLink",
    joinColumns = { @JoinColumn(name = "ParentId", referencedColumnName = "Id") },
    inverseJoinColumns = { @JoinColumn(name = "ChildId", referencedColumnName = "Id") })
private Collection<UserEntity> children;

Since the key in the User entity is on the ShortName field, I have to specify the "Id" as referenced column name param. If I don't do that, it takes the ShortName as the key and doesn't fetch any data.

When I try to do this the way I showed above, I get the following exception:

Caused by: org.hibernate.MappingException: Duplicate property mapping of **_entity_UserEntity_children found in **.entity.UserEntity
        at org.hibernate.mapping.PersistentClass.checkPropertyDuplication(PersistentClass.java:486)
        at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:476)
        at org.hibernate.mapping.RootClass.validate(RootClass.java:268)
        at org.hibernate.cfg.Configuration.validate(Configuration.java:1287)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1729)
        at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:84)
        at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:904)
        ... 81 more

Do you have any idea how this could be fixed? One idea is that I could change the @Id in the entity and move it to the Id property that is used for joins, but this would need a lot of effort to rewrite bad existing code.

Anyway, is it possible to make a self-join manytomany on columns that are not keys?

Cheers Adam

来源:https://stackoverflow.com/questions/25660565/is-hibernate-manytomany-self-join-possible-for-non-key-columns-getting-mappinge

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