6

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:

  1. Add @GeneratedValue annotation to the field - not worked
  2. Change the field type to Integer - it's not feasible for me
  3. Add a constructor that receives myId as parameter public MyClass(String myId){ ... } - not worked
  4. 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
    }
}
Matheus
  • 3,058
  • 7
  • 16
  • 37

2 Answers2

4

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"
}
Piotr Rogowski
  • 3,642
  • 19
  • 24
1

I faced this problem, turns out I was missing the setter for the id field. Make sure the setter method for the ID is defined in the entity class.

  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 01 '22 at 11:05