Search code examples
javahibernatespring-bootjpaspring-data-jpa

Ids for this class must be manually assigned before calling save on String ID


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
    }
}

Solution

  • 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"
    }