简体   繁体   中英

Common JPA base entity separate primary key sequences

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM