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:
- Add
@GeneratedValue
annotation to the field - not worked - Change the field type to
Integer
- it's not feasible for me - Add a constructor that receives
myId
as parameterpublic MyClass(String myId){ ... }
- not worked - Use UUID - i can't, cause this id is set by a field that comes in with a POST request.
None 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
}
}