Can I use @MappedSuperclass annotation on an interface?
Asked Answered
F

1

5

I want to group common mappings in an interface, but I cannot use an abstract superclass because my entities already extend another class. So I need an interface like below:

@MappedSuperclass
public interface NamedEntity {
    @Column(name = "name")
    String getName();
    void setName(String name);
}

and I want to use it like below:

public class Person {
    private Long id;
    private String name;
    public Long getId(){ return id; }
    public void setId(Long id){ this.id = id; }
    public String getName() { return name; }
    public void setName(String name){ this.name = name; }
}

@Entity
@Table(name = "person_entity")
public class PersonEntity extends Person implements NamedEntity {
    @Id
    @GeneratedValue
    @Column(name = "id")
    @Override
    public Long getId() { return super.getId() }
}

Would this work, I mean;

  1. Can I use @MappedSuperclass annotation on an interface?
  2. Does Hibernate have support for interfaces?
Floatable answered 1/3, 2018 at 7:55 Comment(0)
U
8

No. As stated here:

JPA has no direct support for interfaces or variable relationships.

Utu answered 1/3, 2018 at 8:0 Comment(3)
Thank you. Another question: Does Hibernate have support for interfaces?Floatable
I'm not too familiar myself with ibernate. Perhaps this post tells you what you need to know?Utu
small addition .... In JPA your target is to save something (i.e. entities) ... thus this thing to save should be persistable (i.e. has state) , mapped super class is just a common part of your entity that can be shared among other entities so the same rule applies .... interface is not something to hold a 'state' , it's rather a definition for behaviorViquelia

© 2022 - 2024 — McMap. All rights reserved.