I want to use custom id generator in hibernate. This is my model:
@Entity(name="Poli")
@Table(name="POLI")
public class Poli extends DefaultEntityImpl implements Serializable{
@Id
@GenericGenerator(
name = "string-sequence",
strategy = "id.rekam.medis.service.generator.IdGenerator",
parameters = {
@org.hibernate.annotations.Parameter(
name = "sequence_name",
value = "pol_seq"),
@org.hibernate.annotations.Parameter(
name = "sequence_prefix",
value = "POL-")
})
@GeneratedValue(
generator = "string-sequence",
strategy = GenerationType.SEQUENCE)
@Basic(optional = false)
@Column(name = "ID",nullable = false)
private String id;
@Column(name = "NAMA", length = 10)
private String nama;
//getter setter
}
And my IdGenerator Class is :
public class IdGenerator implements IdentifierGenerator, Configurable {
private static final Log logger = LogFactory.getLog(IdGenerator.class);
private String sequenceName;
private String sequencePrefix;
public static final String SEQUENCE_PREFIX = "sequence_prefix";
@Override
public Serializable generate(SessionImplementor session, Object obj) throws HibernateException {
Connection con = session.connection();
Long nextValue = null;
try {
PreparedStatement p = con.prepareStatement(" SELECT POL_SEQ.NEXTVAL FROM DUAL ");
ResultSet rs = p.executeQuery();
while(rs.next()) {
nextValue = rs.getLong("nextVal");
}
} catch (SQLException e) {
e.printStackTrace();
}
if(logger.isDebugEnabled()) logger.debug("new id is generated:" + nextValue);
return "POL-" + nextValue;
}
@Override
public void configure(Type type, Properties params, Dialect dlct) throws MappingException {
sequencePrefix = ConfigurationHelper.getString(SEQUENCE_PREFIX, params,"SEQ_");
}
}
My Goal is, I want that my IdGenerator Class can be used for all Entities/Models. Just need to change the paramters in entity.
My Question: How to catch the parameters in the IdGenerator Class? I want to get "pol_seq" and "POL-" in IdGenerator Class.
Hot Regard,
Tarmizi