在调用String ID上的save之前,必须手动分配此类的ID [英] 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.
我的数据库上需要有一个String
主键.
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..
}
问题在于,如果我在@Id
带注释的字段中使用String
类型,则当我尝试保存对象时,Hibernate会引发异常.
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.
我发现的解决方法:
- 在字段中添加
@GeneratedValue
注释-无效 - 将字段类型更改为
Integer
-对我来说不可行 - 添加一个将
myId
作为参数public MyClass(String myId){ ... }
接收的构造函数-不起作用 - 使用UUID-我不能,因为该ID是由POST请求随附的字段设置的.
- 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.
更新
我正在使用Spring Boot和Spring Data JPA.
I'm using Spring Boot and Spring Data JPA.
如何插入:
我有一个带注释的@PostMapping
方法,该方法处理POST请求并调用执行某些业务逻辑的服务,并调用我的存储库以进行持久化.
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.
我发布的请求
{
"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
}
}
推荐答案
尝试这种方法
@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"
}
这篇关于在调用String ID上的save之前,必须手动分配此类的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!