简体   繁体   English

Hibernate:将类持久化为接口

[英]Hibernate: Persist class as Interface

We have a class Phone which uses Role s, ie.我们有一个使用Role的类Phone ,即。

@Entity
public class Phone{
  @Id...
  private Integer id;

  @Column(name="role_id")
  private IRole role;
  ...

and the interface和界面

public interface IRole extends Serializable {
    public abstract Integer getId();
    ...

So when I try to persist Phone in my package the IRole isn't any longer abstract it is already a concrete entity.因此,当我尝试将Phone保留在我的包中时, IRole不再是抽象的,它已经是一个具体的实体。 The reason why I cannot use the concrete class directly is that we implemented the Role differently in projects.之所以不能直接使用具体类,是因为我们在项目中对Role实现方式不同。

When I try to start Hibernate I get an Exception:当我尝试启动 Hibernate 时,出现异常:

org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: wrong column type encountered in column [role_id
] in table [phone]; found [int4 (Types#INTEGER)], but expecting [bytea (Types#VARBINARY)]

I think the IRole causes the problem.我认为IRole导致了这个问题。 It should store the id of the Role - which is available in all our implementations.它应该存储Roleid - 这在我们所有的实现中都是可用的。 How to tell Hibernate that it should use type Integer instead of some interface interpolation?如何告诉 Hibernate 它应该使用Integer类型而不是某些interface插值?

Looking for a solution which would work in Postgres as well in MariaDB .寻找一个可以在Postgres以及MariaDB工作的解决方案。

You can implement an attribute converter for each your particular implementation of IRole interface and then use them.您可以为每个特定的IRole接口实现实现一个属性转换器,然后使用它们。

  @Convert(converter=RoleA.class)
  @Column(name="role_id_a")
  private IRole roleA;

  @Convert(converter=RoleB.class)
  @Column(name="role_id_b")
  private IRole roleB;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM