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

Tej*_*tel 3 java hibernate

我想将用户持久化到数据库中,以及使用 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;
}

}
Run Code Online (Sandbox Code Playgroud)

但我想Create Id(PK)在以下情况下:1)用户Id(PK)明确设置。2) 如果用户没有设置,Id(PK)那么它会被自动分配并且它必须是唯一的。

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

har*_*bvp 5

您可以为此目的定义自定义 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(){..}
Run Code Online (Sandbox Code Playgroud)

  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.

        }
    }
}
Run Code Online (Sandbox Code Playgroud)