Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA entity extends class contain @Id

Tags:

java

jpa

i have entities classes all contains id as primary key, can i create abstract class which contains all common fields and allow all classes extends this class as the following :

public abstract class CommonFields{
    @Id
@Column(name = "ID")
private long id;

public void setId(long id) {
    this.id = id;
}

public long getId() {
    return id;
}
}

@Entity
    @Table
    public class B extends CommonFields{
    String carModel;
}




@Entity
    @Table
    public class A extends CommonFields{
    String name;
}

Thank You All

like image 635
Hazim Avatar asked Jun 12 '14 06:06

Hazim


1 Answers

You can annotate the class with the common fields with @MappedSupperclass

@MappedSuperclass
public abstract class CommonFields{
    @Id
    @Column(name = "ID")
    private long id;

    public void setId(long id) {
        this.id = id;
    }

    public long getId() {
        return id;
    }
}

From the @MappedSuperclass doc:

Designates a class whose mapping information is applied to the entities that inherit from it. A mapped superclass has no separate table defined for it.

like image 141
Gabriel Ruiu Avatar answered Sep 17 '22 14:09

Gabriel Ruiu