简体   繁体   中英

Hibernate: Persist class as Interface

We have a class Phone which uses Role s, ie.

@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. The reason why I cannot use the concrete class directly is that we implemented the Role differently in projects.

When I try to start Hibernate I get an Exception:

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. It should store the id of the Role - which is available in all our implementations. How to tell Hibernate that it should use type Integer instead of some interface interpolation?

Looking for a solution which would work in Postgres as well in MariaDB .

You can implement an attribute converter for each your particular implementation of IRole interface and then use them.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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