设置Id(PK)生成值自动和手动

  • 本文关键字:Id PK 设置 java hibernate
  • 更新时间 :
  • 英文 :


我想将用户持久化到DB和使用IDENTITY生成类型创建的用户的ID(PK)的当前场景中。例如

@Entity
@Table(name = "USER_PROFILES", uniqueConstraints = @UniqueConstraint(columnNames = "USERNAME"))
public class UserProfiles implements java.io.Serializable {
private Long id;
private String username;
private String password;

public UserProfiles() {
}

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "ID", unique = true, nullable = false, precision = 20, scale = 0)
public Long getId() {
    return this.id;
}
public void setId(Long id) {
    this.id = id;
}
@Column(name = "USERNAME", unique = true, nullable = false, length = 32)
public String getUsername() {
    return this.username;
}
public void setUsername(String username) {
    this.username = username;
}
@Column(name = "PASSWORD", nullable = false, length = 32)
public String getPassword() {
    return this.password;
}
public void setPassword(String password) {
    this.password = password;
}
}

但我想在以下场景中CCD_ 1:1) 用户显式设置Id(PK)。2) 如果用户未设置Id(PK),则会自动分配它,并且它必须是唯一的。

请给我一些可用的选项,这样我就可以解决它。谢谢

您可以为此目的定义自定义id生成器,如本SO Answer 中所述

以下是其代码的样子:-

@Id
@Basic(optional = false)
@GeneratedValue(strategy=GenerationType.IDENTITY, generator="IdOrGenerated")
@GenericGenerator(name="IdOrGenerated",strategy="....UseIdOrGenerate")
@Column(name = "ID", unique = true, nullable = false, precision = 20, scale = 0)
public Long getId(){..}

  public class UseIdOrGenerate extends IdentityGenerator {    
    @Override
    public Serializable generate(SessionImplementor session, Object obj) throws HibernateException {
        if (obj == null) throw new HibernateException(new NullPointerException()) ;
        if ((((EntityWithId) obj).getId()) == null) {//id is null it means generate ID
            Serializable id = super.generate(session, obj) ;
            return id;
        } else {
            return ((EntityWithId) obj).getId();//id is not null so using assigned id.
        }
    }
}

最新更新