Issue
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.
Solution
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.
}
}
}
Answered By - harrybvp
Answer Checked By - Senaida (JavaFixing Volunteer)