简体   繁体   中英

How to avoid autogenerated values check on id with Hibernate

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?

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM