我想在休眠中使用自定义 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-”。
热烈的问候,
塔尔米兹
这就是您实现可配置接口的目的。
该configure()
方法已在这些参数的Properties
参数。看看它的 JavaDoc,它基本上是一个 HashMap,所以就做
params.getProperty("sequence_prefix");
也许你想把这些名字变成常量,要么是 public static final Strings,要么是更好的 Enums。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句