简体   繁体   中英

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;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM