所有环境搭配好之后
package com.zking.uitl;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;
public class MyId implements IdentifierGenerator {
//注意不要继承错了
@Override
public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
// 格式化时间
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String today = sdf.format(new Date());
String s = "AAAAA&";
// 获取第一条数据的id
Connection con = session.connection();
PreparedStatement ps;
try {
ps = con.prepareStatement("SELECT * FROM login LIMIT 1");
ResultSet rs = ps.executeQuery();
if (rs.next()) {
//将你想要的拼接起来
String str = rs.getString("id");
//返回最终的结果
return s + today + "@" + str;
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
然后在映射的实体类下主键的generator 属性将assigned替换为全限定路径名
以我的为例:
<class name="com.zking.entity.Login" table="login" lazy="false">
<id name="id" type="java.lang.String">
<column name="ID" />
<generator class="com.zking.uitl.MyId" />
</id>
</class>