我想在休眠状态下使用自定义ID生成器。这是我的模型:
@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
}
我的IdGenerator类是:
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_");
}
}
我的目标是,我希望IdGenerator类可用于所有实体/模型。只需更改实体中的参数即可。
我的问题:如何在IdGenerator类中捕获参数? 我想在IdGenerator类中获取“ pol_seq”和“ POL-”。
热烈问候
塔米兹
答案 0 :(得分:1)
这就是您实现的Configurable接口的作用。
configure()
方法在Properties
参数中具有这些参数。 Look at its JavaDoc,它基本上是HashMap,所以只需
params.getProperty("sequence_prefix");
也许您想将这些名称转换为常量,或者是公共静态最终字符串,或者更好的是枚举。