我需要连接到供应商数据库并插入客户数据。用于生成新客户ID的序列表存储最后使用的ID(不是下一个可用的ID)。我在jpa或hibernate文档中找不到任何可以指示hibernate将seq表中的id视为最后使用而不是下一个可用的方法(当使用@TableGenerator时)。
我是否需要编写一个与@TableGenerator基本相同的自定义生成器,唯一不同的是处理序列表中的值的方式?
我的客户实体定义如下:
@Entity
public class Customer {
@Id
@TableGenerator(name = "cust_gen", table = "SEQUENCE", pkColumnName = "target",
pkColumnValue = "customer", valueColumnName = "id", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.TABLE, generator = "pat_gen")
public long getCustomer_id() {
return customer_id;
}
public void setCustomer_id(Long id) {
this.customer_id = id;
}
...
}
谢谢!
答案 0 :(得分:3)
我遇到了同样的问题。以这种方式修复它: 使用Hibernate org.hibernate.annotations.GenericGenerator代替persistant TableGenerator,如下所示:
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name = "name")
public class Name implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "names")
@GenericGenerator(name = "names", strategy = "com.ourpackage.SybaseTableGenerator", parameters = {
@Parameter(name = "table_name", value = "new_key_numbers"),
@Parameter(name = "value_column_name", value = "key_number"),
@Parameter(name = "segment_column_name", value = "name"),
@Parameter(name = "segment_value", value = "names_key") })
@Column(name = "names_id")
private Long id;
创建自己的生成器(我使用名称com.ourpackage.SybaseTableGenerator):
import java.io.Serializable;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.id.enhanced.TableGenerator;
@SuppressWarnings("UnusedDeclaration")
public class SybaseTableGenerator extends TableGenerator {
@Override
public synchronized Serializable generate(SessionImplementor session, Object obj) {
return (Long) super.generate(session, obj) + 1;
}
}
有点棘手,但它确实有效;)