I'm trying to add a Generator
on package-info.java
so that I don't have to re-write same code on top of every @Entity
class. But when I try to run the program Application I get an error.
Session Factory could not be created.org.hibernate.AnnotationException:
Unknown Id.generator: ID_GENERATOR
If I apply @GenericGenerator
on top on @Entity
class it works just fine. Am I missing some key point here.
I found this tread but the answer posted there didn't work for me.
Configurations
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>