小编典典

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

hibernate

我想将用户持久保存到数据库中,并使用IDENTITY生成类型创建的User的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;
}

}

但我想Create Id(PK)在以下情况下进行操作:1)用户Id(PK)明确设置。2)如果未设置用户,Id(PK)则将自动分配它,并且它必须是唯一的。

请建议我一些可用的选项,以便我解决。谢谢。


阅读 851

收藏
2020-06-20

共1个答案

小编典典

您可以为此目的定义您的自定义ID生成器,如本SOAnswer中指出的那样

它的代码如下所示:

@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.

        }
    }
}
2020-06-20