@Embeddable and @EmbeddedId consists only of complex classes

狂风中的少年 提交于 2019-12-24 03:13:01

问题


I have the following problem:

One of my entities has to use a complex class as ID. (To solve this I use @EmbeddedId)

The complex class has a combined primary key of 2 other complex classes [I got the following error: Caused by: org.hibernate.AnnotationException: model.IElementKey has no persistent id property: model.impl.Element.id].

The problem is how to solve this without adding a non complex type to the ID-class.

Edit: I have to user JPA only [javax.persistence.*]

Edit2: Small Code Example (getters/setters are left out for simplicity)

@Embeddable
public class EntityKey implements IEntityKey, Serializable {

    private static final long   serialVersionUID    = 1L;

    @ManyToOne(targetEntity = Entity1.class, optional = false)
    private IEntity1                entity1             = null;

    @ManyToOne(targetEntity = Entity2.class, optional = false)
    private IEntity2                entity2             = null;

}

@Entity
public class MixEntity implements IMixEntity {

    @EmbeddedId
    private IEntityKey  id              = null;

}


@Entity
public class Entity1 implements IEntity1 {

    @Id
    private Long id = null;

    @OneToMany(targetEntity = MixEntity.class, mappedBy = "id.entity1")
    private List<IMixEntity>    mixEntities = new ArrayList<IMixEntity>();

}

@Entity
public class Entity2 implements IEntity2 {

    @Id
    private Long id = null;

    @OneToMany(targetEntity = MixEntity.class, mappedBy = "id.entity2")
    private List<IMixEntity>    mixEntities = new ArrayList<IMixEntity>();

}

回答1:


The my advice in this case is to use concrete class and not abstract class or interface. The reason is that JPA , Hibernate and so on use reflection behind the scenes and in this case need of concrete class for instance this and retrive the information for auto generate the query. If you use abstract class when the framekork call clazz.instance() you get an exception.

For this reason you should use concrete class.

I hope the t this can help




回答2:


It maybe is a little late. But maybe it will still help others:

I know it seems pretty straight forward to write @EmbeddedId(targetEntity = SomeClass.class)

But as it has no effect on your error just try @Target Annotation.

It will do the job.

@Entity
public class MixEntity implements IMixEntity {

    @EmbeddedId
    @Target(EntityKey.class)
    private IEntityKey  id              = null;

}


来源:https://stackoverflow.com/questions/15821439/embeddable-and-embeddedid-consists-only-of-complex-classes

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