我正在尝试添加一个Generator
,package-info.java
这样我就不必在每个@Entity
类的顶部重新编写相同的代码。但是当我尝试运行程序应用程序时,我得到一个错误。
Session Factory could not be created.org.hibernate.AnnotationException:
Unknown Id.generator: ID_GENERATOR
如果我@GenericGenerator
在课堂上名列前茅,@Entity
它就可以了。我是否在这里遗漏了一些关键点。
我找到了这个踏板,但是那里发布的答案对我不起作用。
配置
package-info.java
@org.hibernate.annotations.GenericGenerator(
name = "ID_GENERATOR",
strategy = "enhanced-sequence",
parameters = {
@org.hibernate.annotations.Parameter(
name = "sequence_name",
value = "JPA_SEQUENCE"
),
@org.hibernate.annotations.Parameter(
name = "initial_value",
value = "1"
)
}
)
package com.example.hibernate.model;
Student.java
package com.example.hibernate.model;
@Entity
@Table(name = "student")
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Student implements Serializable {
@Id
@GeneratedValue(generator = "ID_GENERATOR")
private int id;
@Column(name = "first_name", nullable = false)
private String firstName;
@Column(name = "last_name", nullable = false)
private String lastName;
}
persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0">
<persistence-unit name="persistence" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.example.hibernate.model.Student</class>
<properties>
<property name="hibernate.archive.autodetection" value="class" />
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
<property name="hibernate.connection.driver_class" value="org.h2.Driver" />
<property name="hibernate.connection.url" value="jdbc:h2:mem:test_mem" />
<property name="hibernate.connection.user" value="sa" />
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.flushMode" value="FLUSH_AUTO" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
</properties>
</persistence-unit>
</persistence>