hellzone
hellzone

Reputation: 5236

How to set autogenerated Id manually?

I have an entity called Task and it has taskId field. Problem is I need to create/update some specific tasks and JPA autogenerator doesn't allow me to set taskId manually.(It overrides my taskId)

Is there any way to set taskId manually?

@Id
@Column(name = "task_id")
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "org.hibernate.id.UUIDGenerator")
private String taskId;

Upvotes: 9

Views: 20045

Answers (6)

user22750510
user22750510

Reputation: 1

all of you missing the point.

Sometimes you need to insert a specific Id with identity_insert on especially when perform bulk imports

The tricky part is how to override the default behaviour without reinvent the wheel and do manual queries

Upvotes: 0

Dharmendrasinh Chudasama
Dharmendrasinh Chudasama

Reputation: 1117

Just implement org.springframework.data.domain.Persistable;

After too much finding and frustration i have used this and worked for my R2DBMS entity

@Table(name = "...")
public class .... implements Persistable<String> {

   ...

   public boolean isNew(){
     return id==null; //modify and set your logic
   }

}

Upvotes: 2

Quockhanh Pham
Quockhanh Pham

Reputation: 412

Using

@GeneratedValue(strategy = GenerationType.IDENTITY)

Example: http://www.codejava.net/frameworks/hibernate/java-hibernate-jpa-annotations-tutorial-for-beginners

Upvotes: 2

dhyanandra singh
dhyanandra singh

Reputation: 1141

you can initialize it manually.

        @Id
        @Column(name= "id")
        @GeneratedValue
        private Long id = Long.parseLong(UUID.randomUUID().toString(), 16);

Upvotes: 2

TheHound.developer
TheHound.developer

Reputation: 396

@GeneratedValue annotation doesn't allow the user to set the value manually.Instead of using that annotation you can manually generate some string format like below and mark the taskId column with @Id

String hql = "from MasterCount where itemType=:type";
Query<MasterCount> query = session.createQuery(hql);
query.setParameter("type", "task");
MasterCount count = query.uniqueResult();
int lastId = count.getItemId() + 1;
count.setItemId(lastId);
task.setTaskId("task0"+lastId);

That is create a master table with columns itemId and itemType.Save "task" and 0 in the columns respectively.Check the last entered value ,increment one and save again.

Upvotes: 2

memoricab
memoricab

Reputation: 453

This link may help you.

I would apply a basic solution if I understood your problem correctly.

@Column(name = "task_id", unique = true, nullable = false)
private String taskId;

Upvotes: 1

Related Questions