2

我有以下问题:

我的一个实体必须使用一个复杂的类作为 ID。(为了解决这个问题,我使用@EmbeddedId)

复杂类具有其他 2 个复杂类的组合主键 [我收到以下错误:原因:org.hibernate.AnnotationException:model.IElementKey 没有持久 id 属性:model.impl.Element.id]。

问题是如何在不向 ID 类添加非复杂类型的情况下解决这个问题。

编辑:我必须只使用 JPA [javax.persistence.*]

Edit2:小代码示例(为简单起见,省略了获取器/设置器)

@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>();

}
4

2 回答 2

0

可能有点晚了。但也许它仍然会帮助其他人:

我知道写起来似乎很简单 @EmbeddedId(targetEntity = SomeClass.class)

但由于它对您的错误没有影响,请尝试 @TargetAnnotation。

它会完成这项工作。

@Entity
public class MixEntity implements IMixEntity {

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

}
于 2018-03-29T16:23:26.067 回答
0

在这种情况下,我的建议是使用具体类而不是抽象类或接口。原因是 JPA 、 Hibernate 等在幕后使用反射,在这种情况下需要具体的类,例如 this 并检索信息以自动生成查询。如果在 framekork 调用 clazz.instance() 时使用抽象类,则会出现异常。

出于这个原因,您应该使用具体类。

我希望这可以帮助

于 2016-03-25T16:10:57.020 回答