我已经为我的应用程序实现了一个自定义生成器,并且我想将字符串作为第二个参数发送到IdentifierGenerator接口,但是我不知道如何执行此操作。不幸的是,由于下面的代码,它会将null2设置为生成的密钥。请帮忙。
我想发送一个字符串,它是来自客户端的“日期”作为第二个参数。
谢谢。
public class CourierTransImpl implements IdentifierGenerator{ private String appendString; @Override public Serializable generate(SessionImplementor session, Object arg1) throws HibernateException { Connection connection = session.connection(); int id=0; try { PreparedStatement ps = connection .prepareStatement("SELECT MAX(TRANS_ID) as value from SecurePass.COURIER_TRANSACTIONS_SER_TABLE"); ResultSet rs = ps.executeQuery(); if (rs.next()) { id = rs.getInt("value"); id++; } ps = connection .prepareStatement("INSERT INTO SecurePass.COURIER_TRANSACTIONS_SER_TABLE VALUES("+id+")"); ps.execute(); } catch (SQLException e) { e.printStackTrace(); } return appendString+id; } public String getAppendString() { return appendString; } public void setAppendString(String appendString) { this.appendString = appendString; } }
您可以实现可配置接口,并根据需要覆盖配置。这样,您只能将静态值作为参数传递给CourierTransImpl类
CourierTransImpl
如果要传递一些动态值,则可以@Transient在实体中定义一个属性,然后在CourierTransImpl类中访问该属性。
@Transient
详细说明:
例如,让我们说有一个名为的实体Employee,它有一个名为的瞬时属性,empType然后您可以像这样定义该实体。
Employee
empType
@Entity public class Employee { @Id @GeneratedValue(generator = "UniqueIdGenerator") @GenericGenerator(name = "UniqueIdGenerator", strategy = "com.CourierTransImpl", parameters = { @Parameter(name = "appendString", value = "Emp") }) private String id; private String name; @Transient private String empType; // Getters & Setters }
在上面的代码中,您可以看到我们设置了参数appendString,这是一个静态值,在此处将其设置为“ Emp”。
appendString
现在CourierTransImpl,实现Configurable接口的类:
public class CourierTransImpl implements IdentifierGenerator, Configurable { private String appendString; @Override public Serializable generate(SessionImplementor session, Object object) throws HibernateException { Connection connection = session.connection(); int id = 0; try { Employee emp = (Employee) object; id = ..; // your logic to get the id from database // Now you can use the parameter appendString which is static value set to "Emp" // You can also access any of the employee properties here, so in your code you can set the required value dynamically. return appendString + emp.getEmpType()+id; } catch (Exception e) { e.printStackTrace(); } return appendString + id; } @Override public void configure(Type type, Properties params, Dialect d) throws MappingException { setAppendString(params.getProperty("appendString")); // Here we are setting the parameters. } // Setters & Getters
}
在此示例中,如果我创建的对象Employee并将其设置empType为某个值,例如“ Manager”,则hibernate将生成和ID,例如“ Emp1Manager”。