2

I have 2 Object A and B, which have same attributes, but different table.

@Entity
@Table(name = "A")
public class A {

    @Id
    private Integer id;
    ...
}

and

@Entity
@Table(name = "B")
public class B {

    @Id
    private Integer id;
    ...
}

it will cause duplicate code because every attributes are same. What is best practice to do this kind of problem?

Predrag Maric
  • 23,938
  • 5
  • 52
  • 68
first_time_user
  • 417
  • 1
  • 5
  • 16
  • Possible duplicate of [Do you have a common base class for Hibernate entities?](http://stackoverflow.com/questions/156689/do-you-have-a-common-base-class-for-hibernate-entities) – alexander Sep 15 '16 at 20:06

1 Answers1

3

I'd create a @MappedSupperclass for this, and extend from it. It would look like this

@MappedSuperclass
public class Common {
    @Id
    private Integer id;
}

@Entity
@Table(name = "A")
public class A extends Common {
    ...
}

@Entity
@Table(name = "B")
public class B extends Common {
    ...
}

This doesn't create an entity hierarchy, but only moves common entity attributes in a super class. Often used for id, version, createdBy etc.

Predrag Maric
  • 23,938
  • 5
  • 52
  • 68
  • 1
    Just wondering if this is not a duplicate to http://stackoverflow.com/questions/156689/do-you-have-a-common-base-class-for-hibernate-entities ... – Tobias Liefke Nov 27 '15 at 23:05