在调用String ID上的save之前,必须手动分配此类的ID
已经阅读了许多有关同一问题的问题,但我仍然无法解决此问题。
我需要String在数据库上有一个主键。
import javax.persistence.Entity;import javax.persistence.Id;
@Entity
public class MyClass {
    @Id
    private String myId;
    private String name;
    // getters and setters..
}
问题是,如果我String在带@Id注释的字段中使用type ,则当我尝试保存对象时,Hibernate会引发异常。
ids for this class must be manually assigned before calling是的,我正在为该字段设置一个值。
我发现的解决方法:
@GeneratedValue向该字段添加注释-不起作用- 将字段类型更改为
Integer-这对我来说不可行 - 添加接收
myId作为参数的构造函数public MyClass(String myId){ ... }-不起作用 - 使用UUID-我不能,因为此ID是由POST请求随附的字段设置的。
 
这些变通办法都不适合我。
我正在使用Spring Boot和Spring Data JPA。
如何插入:
我有一个带@PostMapping注释的方法,该方法处理POST请求并调用执行一些业务逻辑的服务,并调用我的存储库以进行持久化。
我发布的请求:
{    "myId": "myId",
    "name": "myName"
}
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
    }
}
回答:
试试这个方法
@Entitypublic class MyClass{
    @Id
    @GeneratedValue(generator = “UUID”)
    @GenericGenerator(
        name = “UUID”,
        strategy = “org.hibernate.id.UUIDGenerator”,
    )
    @Column(name = “id”, updatable = false, nullable = false)
    private UUID id;
    …
}
=====================================
我这样调用,在我的环境中,一切正常:
@Autowiredprivate EntityManager entityManager;
@PostMapping("")
@Transactional
public void add(@RequestBody MyClass myClass){
        entityManager.persist(myClass);
}
并要求通过邮件与正文一起发送:
{    "myId" : "213b2bbb1"
}
以上是 在调用String ID上的save之前,必须手动分配此类的ID 的全部内容, 来源链接: utcz.com/qa/408220.html

