开发者

Can @TableGenerator save the last used id in the table instead of the next available?

I need to connect to a vendor db and insert customer data. The sequence table used to generate new customer ids stores the last used id (not the next available). I couldn't find开发者_如何转开发 anything in the jpa or hibernate docs that would indicate a way to tell hibernate to treat the id in the seq table as last used instead of next available (when using @TableGenerator).

Do I need to write a custom generator that will behave essentially the same as @TableGenerator with the only difference being the way the value in the sequence table is treated?

My Customer entity is defined as follows:

@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;
}

    ...

}

Thanks!


I had the same problem. Fixed it this way: Use Hibernate org.hibernate.annotations.GenericGenerator instead of persistance TableGenerator like this:

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;

And create your own generator (I used name 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;
    }
}

A little bit tricky but it works ;)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜