如何在springboot中自动生成h2数据库中的id?

mzsu5hc0  于 2023-01-26  发布在  Spring
关注(0)|答案(1)|浏览(193)

下面是Entity类。

@Entity
    @Table(name = "STUDENT")
    public class Student {

        @Id
        @GeneratedValue(strategy=GenerationType.IDENTITY)
        @Column(name = "ID",updatable = false, nullable = false)
        private Long id;

        @Column(name = "Name")
        private String name;

        public Long getId() {
            return id;
        }

        public void setId(Long id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

当我提供带有id和name的输入时,它工作正常并正在保存数据库,但当我保存一个没有id的student对象时,我会遇到异常

org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): com.cnx.demo.SpringBoot.model.Student
    at org.hibernate.id.Assigned.generate(Assigned.java:33) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:115) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:185) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:128) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:55) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
    at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:710) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:696) ~[hibernate-core-5.4.12.Final.jar:5.4.12.Final]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_211]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_211]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_211]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_211]
    at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:368) ~[spring-orm-5.2.4.RELEASE.jar:5.2.4.RELEASE]
    at com.sun.proxy.$Proxy102.persist(Unknown Source) ~[na:na]
    at sun
thigvfpy

thigvfpy1#

确保在你的.html文件中你添加了你的有序列表和列表项标签(< ol >,< li >),你在你的〈li(put th:blahhere)〉标签之间有你的thymeleaf模板。

相关问题