3

我想将用户持久保存到数据库和使用 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;
}

}

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

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

4

1 回答 1

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(){..}

  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.

        }
    }
}
于 2013-08-12T10:29:47.963 回答