请参考custom-id-generator-in-hibernate这可能会对您有所帮助。在此示例中,我通过从名为pk_table的主键表中获取 MAX 号来创建序列号。
员工类如下所示。
@Entity
@Table(name="EMPLOYEE")
public class Employee {
@Id
@GenericGenerator(name = "sequence_emp_id", strategy = "com.supportmycode.model.EmployeeIdGenerator")
@GeneratedValue(generator = "sequence_emp_id")
@Column(name="employee_id")
private String employeeId;
@Column(name="firstname")
private String firstname;
@Column(name="lastname")
private String lastname;
@Column(name="birth_date")
private Date birthDate;
@Column(name="cell_phone")
private String cellphone;
//Getter and Setter methods.
}
EmployeeIdGenerator类如下所示
public class EmployeeIdGenerator implements IdentifierGenerator {
public Serializable generate(SessionImplementor session, Object object)
throws HibernateException {
String prefix = "EMP";
Connection connection = session.connection();
try {
PreparedStatement ps = connection
.prepareStatement("SELECT MAX(value) as value from hibernate_tutorial.pk_table");
ResultSet rs = ps.executeQuery();
if (rs.next()) {
int id = rs.getInt("value");
String code = prefix + new Integer(id).toString();
System.out.println("Generated Stock Code: " + code);
return code;
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
在这里,我们已经实现了IdentifierGenerator
覆盖函数的接口generate(SessionImplementor session, Object object)
。该语句SELECT MAX(value) as value from hibernate_tutorial.pk_table
将从表 pk_table 中获取 MAX 数。然后我们在MAX数字前加上字符串“ EMP ”。
输出如下所示:
员工
------------------------------------------------------------
employee_id | birth_date | cell_phone | firstname | lastname
------------------------------------------------------------
EMP1 | 2014-08-22 | 111 | Nina | Mayers