Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I persist a superclass variables from child class in hibernate?

Tags:

java

hibernate

I want to persist all variables in a superclass only from childclass

Example:

//This class is from an API, I cannot touch or change
class SuperClass {
    private String name;
    private String info;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info;
    }
}

@Entity
class ChildClass extends SuperClass {
    @id
    private long id;
}

I want the table to have these columns (id, name, info)

Is it doable? If yes, How?

like image 716
kdureidy Avatar asked Jan 28 '16 01:01

kdureidy


1 Answers

If the accessors are not set as final in the super class, you can override them in the child classes and add JPA annotations to the overridden accessor methods.

Example 1


class SuperClass { public String getName() { ... } public String getInfo() { ... }

@Entity
class ChildClass extends SuperClass {
  @Id
  private long id;

  public Long getId() { return id; }

  @Access(AccessType.PROPERTY)
  @Column(name = "name")
  public String getName() { return super.getName(); }

  @Access(AccessType.PROPERTY)
  @Column(name = "info")
  public String getInfo() { return super.getInfo(); }
}

Example 2


class SuperClass { public String getName() { ... } public String getInfo() { ... }

@MappedSuperClass
class NamedModel extends SuperClass {
  @Access(AccessType.PROPERTY)
  @Column(name = "name")
  public String getName() { return super.getName(); }

  @Access(AccessType.PROPERTY)
  @Column(name = "info")
  public String getInfo() { return super.getInfo(); }
}

@Entity
class ChildClass extends NamedModel {
  @Id
  private long id;
}

I have created a sample application using your code. Download the application and run the integration tests as mvn clean test and check the generated SQL to see the desired result.

like image 175
manish Avatar answered Sep 19 '22 14:09

manish