英文:
How to avoid autogenerated values check on id with Hibernate
问题
以下是翻译好的内容:
我有以下的表声明:
CREATE TABLE `chat_session` (
`session_id` BINARY(36) NOT NULL COMMENT '聊天会话标识',
...
PRIMARY KEY (`session_id`)
以及以下的类:
@ToString()
@EqualsAndHashCode(doNotUseGetters = true)
@Entity
@Table(name = "chat_session")
public class ChatSession {
@Id
@Column(name = "session_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private String sessionId;
然而,当保存时,会出现如下错误:
javax.persistence.PersistenceException: org.hibernate.HibernateException: 数据库未返回任何本地生成的标识值
实际上,我不想改变模式,我需要为我的实体提供正确的值,而不是自动生成的。我能做到吗?
英文:
I have the following table declaration:
CREATE TABLE `chat_session` (
`session_id` BINARY(36) NOT NULL COMMENT 'Chat session identifier',
...
PRIMARY KEY (`session_id`)
and the following class:
@ToString()
@EqualsAndHashCode(doNotUseGetters = true)
@Entity
@Table(name = "chat_session")
public class ChatSession {
@Id
@Column(name = "session_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private String sessionId;
which, when saving, turns into an error like the following:
javax.persistence.PersistenceException: org.hibernate.HibernateException: The database returned no natively generated identity value
actually, I don't want to change the schema, and I need to feed my entities with proper values, not autogenerated. Can I do it?
答案1
得分: 0
如果您无法更改数据库架构,则必须手动生成唯一标识并为新实体分配它。
您可以通过简单地移除 @GeneratedValue
来实现:
@Entity
@Table(name = "chat_session")
public class ChatSession {
@Id
@Column(name = "session_id")
private String sessionId;
}
根据业务要求进行咨询,看是否有关于标识格式的任何规则。如果有,实施它并自行手动生成新的标识并将其设置为新实体。如果没有这样的业务规则,您可以简单地使用Java中的UUID生成器来确保生成的标识是唯一的:
UUID.randomUUID().toString()
英文:
If you cannot change the database schema , you have to manually generate an unique ID and assign it for the new entities.
You can do it by simply removing @GeneratedValue
:
@Entity
@Table(name = "chat_session")
public class ChatSession {
@Id
@Column(name = "session_id")
private String sessionId;
}
Consult with the business requirement to see if there are any rules about the ID format. If yes , implement it and manually generate a new ID and set it for the new entity by yourself. If you do not have such business rule , you can simply use the UUID generator from Java to ensure the generated ID is unique:
UUID.randomUUID().toString()
专注分享java语言的经验与见解,让所有开发者获益!
评论