1

I have a UserAuthenticationEntity extending from BaseEntity.

@MappedSuperclass
public class BaseEntity implements Serializable {

  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_seq_generator")
  @SequenceGenerator(name = "user_seq_generator", sequenceName = "user_seq", allocationSize = 1)
  private Long id;

  public Long getId() {
    return id;
  }

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

@Entity
@Table(name = "user_authentication")
public class UserAuthenticationEntity extends BaseEntity {

  private String username;
  private String password;

  public UserAuthenticationEntity(String username, String password){
    this.username = username;
    this.password = password;
  }
  ...
  ...

}

All future entities will extend BaseEntity class.

Is it possible that all entities inherit id property from BaseEntity class yet have separate sequences to generate primary keys?

I know this is a wired scenario but I think having a base entity class is a great place to define id property for all entity classes but not being able to use different sequences is a kind of deal breaker. Not sure it can be done.

Any alternative/better design for entity classes is also welcome.

Meena Chaudhary
  • 9,909
  • 16
  • 60
  • 94

1 Answers1

0

Is a bad idea to use inheritance with entities id's, i think.

Usually, each entity contains an id attrite with the @Id and @GeneratedValue annotarions and inheritance is used to inherit common attributes. But, if you want to try it, you can take a look to the question below:

Overriding @Id defined in a @MappedSuperclass with JPA

  • https://medium.com/codex/base-entity-and-audit-entity-with-jpa-fe413ad18bda A good article about how to provide a `BaseEntity` using an abstract class to extend from, to avoid instantiation. – nonNumericalFloat Apr 12 '23 at 12:18