在休眠状态下,有什么方法可以生成长类型的自定义ID作为主键吗?我已经阅读过此hibernate ID,但是当Id的类型为String时,它可以工作。我想要的ID看起来像“ yyyymm00001”,例如:20180900001;在这里,下面的方法返回我想要的格式,但是是String类型。如何将其设置为长型?
@Override
public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
Serializable result = null;
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
String year= String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
String month= String.format("%02d",Calendar.getInstance().get(Calendar.MONTH)+1);
try {
connection = session.connection();
statement = connection.createStatement();
try {
statement.executeUpdate("UPDATE " + DEFAULT_SEQUENCE_NAME + " SET next_val=LAST_INSERT_ID(next_val+1)");
resultSet = statement.executeQuery("SELECT next_val FROM " + DEFAULT_SEQUENCE_NAME);
} catch (Exception e) {
System.out.println("In catch, cause : Table is not available.");
statement.executeUpdate("UPDATE " + DEFAULT_SEQUENCE_NAME + " SET next_val=LAST_INSERT_ID(next_val+1)");
resultSet = statement.executeQuery("SELECT next_val FROM " + DEFAULT_SEQUENCE_NAME);
}
if (resultSet.next()) {
int nextValue = resultSet.getInt(1);
String suffix = String.format("%05d", nextValue);
result = year.concat(month).concat(suffix);
System.out.println("Custom generated sequence is : " + result);
}
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
答案 0 :(得分:1)
要更正此问题,必须在实体中添加此注释,并为@Id设置Long或Integer类型。
myData.write.format('jdbc').options(
url='jdbc:%s' % url,
driver='org.postgresql.Driver',
dbtable='pyspark_user',
user='postgres',
password='').mode('append').save()
知道这一点
@Id
@Column(name = Contact.ENCOIDFSYS)
@GeneratedValue(generator = IdfsysGeneratorDefinition.NAME)
@GenericGenerator(name = IdfsysGeneratorDefinition.NAME, strategy = IdfsysGeneratorDefinition.CLASS_NAME, parameters = { })
private Integer id;
在休眠生成器类中,将此转换添加到Long
public static final String CLASS_NAME = "com.sybaway.generators.hibernate.HibernateIdfsysGenerator";
public static final String NAME = "idfsysGenerator";
而不是:
result = Long.parseLong(year.concat(month).concat(suffix));
让我知道一切是否好