我想在 hibernate 中使用自定义 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-”。
热烈关注,
塔尔米兹
最佳答案
这就是您实现的Configurable接口(interface)。
configure()
方法在 Properties
参数中包含这些参数。 Look at its JavaDoc ,它基本上是一个 HashMap,所以只需这样做
params.getProperty("sequence_prefix");
也许您想将这些名称转换为常量,可以是 public static final Strings,也可以是更好的 Enums。
关于java - 如何将模型的genericgenerator中的参数传递给另一个类(IdGenerator),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52310580/