Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to have a duplicate generator named defined in the JPA persistence unit?

My situation is described here:

eclipse Duplicate generator named "ID_GENERATOR" defined in this persistence unit

However my question is different and the selected answer does not solve it :

"Is it valid to have multiple @SequenceGenerator with the same name even though it is used for this purpose Hibernate : How override an attribute from mapped super class ?"

If not valid, is there an alternative ?

Thank you very much for your answer.

like image 500
fabien7474 Avatar asked Jan 14 '16 12:01

fabien7474


1 Answers

According to section 11.1.48 SequenceGenerator Annotation of the JPA 2.1 specification:

The scope of the generator name is global to the persistence unit (across all generator types).

So you can't have duplicate generators.

If you try to add the following two entities:

@Entity(name = "Post")
public static class Post {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "pooled")
    @GenericGenerator(
        name = "pooled",
        strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
        parameters = {
            @Parameter(name = "sequence_name", value = "sequence"),
            @Parameter(name = "initial_value", value = "1"),
            @Parameter(name = "increment_size", value = "5"),
        }
    )
    private Long id;
}

@Entity(name = "Announcement")
public static class Announcement {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "pooled")
    @GenericGenerator(
            name = "pooled",
            strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
            parameters = {
                @Parameter(name = "sequence_name", value = "sequence"),
                @Parameter(name = "initial_value", value = "1"),
                @Parameter(name = "increment_size", value = "10"),
            }
    )
    private Long id;
}

Hibernate will generate the following error message:

Multiple references to database sequence [sequence] were encountered attempting to set conflicting values for 'increment size'. Found [10] and [5]

That's because the identifier generator is global and those two sequence configurations will be conflicting.

like image 195
Vlad Mihalcea Avatar answered Oct 09 '22 21:10

Vlad Mihalcea