设置Id(PK)生成值auto和manual

时间:2013-08-12 08:47:18

标签: java hibernate

我想将用户持久化到数据库以及使用IDENTITY生成类型创建的用户ID(PK)的当前场景。 e.g。

@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),则会自动分配,并且必须是唯一的。

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

1 个答案:

答案 0 :(得分:4)

您可以为此目的定义自定义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.

        }
    }
}