Already read lots of questions about the same issue, but I still not be able to solve this problem.
I need to have a String
primary key on my database.
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class MyClass {
@Id
private String myId;
private String name;
// getters and setters..
}
The problem is that, if I use String
type in a @Id
annotated field, Hibernate throws an exception when I try to save the object.
ids for this class must be manually assigned before calling
And yes, I'm setting a value to the field.
Workarounds I found:
@GeneratedValue
annotation to the field - not workedInteger
- it's not feasible for memyId
as parameter public MyClass(String myId){ ... }
- not workedNone of these workarounds worked for me.
UPDATE
I'm using Spring Boot and Spring Data JPA.
How do I insert:
I have an @PostMapping
annotated method which handles POST request and call a service that do some business logic and call my repository for persisting.
The request I post:
{
"myId": "myId",
"name": "myName"
}
MyService.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class MyService {
@Autowired
private MyRepository myRepository;
public MyClass save(MyClass myClass) {
return myRepository.save(myClass); // save() should persist my object into the database
}
}
try this approach
@Entity
public class MyClass{
@Id
@GeneratedValue(generator = “UUID”)
@GenericGenerator(
name = “UUID”,
strategy = “org.hibernate.id.UUIDGenerator”,
)
@Column(name = “id”, updatable = false, nullable = false)
private UUID id;
…
}
======================================
I invoke like this and in my envirenment all work fine:
@Autowired
private EntityManager entityManager;
@PostMapping("")
@Transactional
public void add(@RequestBody MyClass myClass){
entityManager.persist(myClass);
}
and requst send by post with body:
{
"myId" : "213b2bbb1"
}