5

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;
Neil Stockton
  • 10,922
  • 3
  • 30
  • 28
hellzone
  • 5,076
  • 21
  • 77
  • 133
  • The JPA spec doesn't allow for a user wanting to set under some situation and generate under others (since the definition of `GeneratedValue` is static). Some JPA providers do support it (DataNucleus does IIRC) but non-portable if relying on it – Neil Stockton Jul 14 '17 at 12:45

4 Answers4

3

Using

@GeneratedValue(strategy = GenerationType.IDENTITY)

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

Bugs
  • 4,456
  • 9
  • 32
  • 40
Quockhanh Pham
  • 306
  • 2
  • 8
2

@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.

TheHound.developer
  • 376
  • 1
  • 3
  • 15
2

you can initialize it manually.

        @Id
        @Column(name= "id")
        @GeneratedValue
        private Long id = Long.parseLong(UUID.randomUUID().toString(), 16);
dhyanandra singh
  • 961
  • 1
  • 14
  • 35
0

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;
memoricab
  • 365
  • 5
  • 23