Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA: Override Auto generated ID [duplicate]

I have following definition in Employee class

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "employee_id")
private Integer employeeId;

Now I want to import existing employees with existing employee IDs. Even if I set the employee ID before saving, the assigned ID is ignored and auto incremented ID is stored. How do we override this?

I had similar problem for composite key which has been explained here

like image 855
sidgate Avatar asked Jul 26 '12 11:07

sidgate


2 Answers

I wrote my own generator to solve the issue.

public class UseExistingIdOtherwiseGenerateUsingIdentity extends IdentityGenerator {

    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
        Serializable id = session.getEntityPersister(null, object).getClassMetadata().getIdentifier(object, session);
        return id != null ? id : super.generate(session, object);
    }
}

and use it like this: (replace the package name)

@Id
@GenericGenerator(name = "UseExistingIdOtherwiseGenerateUsingIdentity", strategy = "{package}.UseExistingIdOtherwiseGenerateUsingIdentity")
@GeneratedValue(generator = "UseExistingIdOtherwiseGenerateUsingIdentity")
@Column(unique = true, nullable = false)
protected Integer id;
like image 62
sidgate Avatar answered Sep 21 '22 01:09

sidgate


You cannot override it. First of all JPA do not provide way to do it. Second problem is that GenerationType.AUTO can produce such a column type that will not accept user assigned value via SQL statement.

Perform import of data manually and do not try to use application itself as an import tool.

like image 29
Mikko Maunu Avatar answered Sep 20 '22 01:09

Mikko Maunu