Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to persist User into DB and current scenario of ID(PK) of User created with IDENTITY generation type. 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;
}

}

but I want to Create Id(PK) in following scenarios : 1) User sets Id(PK) explicitly. 2) If User does not set Id(PK) then it is be assigned automatically and it must be unique.

Please suggest me some available options so I can resolve it. Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
201 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can define your custom id generator for this purpose as pointed out in this SO Answer

Here is how its code will look like:-

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

and

  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.

        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...