使用Interfaces而不是Concrete类在Hibernate中映射HashMap

时间:2015-08-23 10:41:59

标签: java hibernate jpa orm hibernate-mapping

我有一个名为Person的界面,如下所示

public interface Person {
    String getName();}

我有一个抽象类,AbstractPerson实现Person。 Abstar

@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="PERSON_TYPE")
@Table(name="PERSON")
public class AbstractPerson implements Person{

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;

private String firstName;
private String lastName;
.....
@Override
public String getName() {

    return firstName + " " + lastName;
}

我的具体课程是会员,所以它扩展了AbstractPerson。

@Entity
@DiscriminatorValue(value="MEMBER")
public class Member extends AbstractPerson{ 

@OneToMany(mappedBy="commentOwner")
@MapKey(name="id" )
private Map<Long, CommentImpl> commentList;
 ....

在CommentImpl中创建ManyToOne关系的代码位于

之下
public class CommentImpl implements Comment, Serializable{
@ManyToOne
private Member commentOwner;
....

我的问题是我想编写针对接口而不是具体类的代码。因此,HashMap中的值类型将是Member类中的Comment,而commentOwner将是CommentImpl类中的Person类型。 当我这样做时,我得到一个unknowm映射异常。如何设置与接口和具体类的关系?

1 个答案:

答案 0 :(得分:1)

one-to-many方变为:

@OneToMany(mappedBy="commentOwner", targetEntity = "CommentImpl.class")
@MapKey(name="id" )
private Map<Long, Comment> commentList;

并且many-to-one方应该是:

@ManyToOne(targetEntity = "Member.class")
private Person commentOwner;