简体   繁体   中英

Spring Boot: Set hibernate sequence globally

Currently I define the tables the following way:

The example is in Kotlin, but you can answer in Java if you want.

@Entity
data class Task(@Id @GeneratedValue(strategy = GenerationType.SEQUENCE)
                var id: Int = 0,

                @ManyToOne(optional = false) @OnDelete(action = OnDeleteAction.CASCADE)
                var exercise: Exercise = Exercise(),

                @Column(nullable = false)
                var name: String = "")

@Entity
data class Exercise(@Id @GeneratedValue(strategy = GenerationType.SEQUENCE)
                    var id: Int = 0,

                    @Column(nullable = false)
                    var count: Int = 0)

Using this example all tables are using the same sequence: hibernate_sequence .

If I want to configure it eg setting a custom allocationSize , then I must define it in every table, am I right?

@SequenceGenerator(name = "task_seq", sequenceName = "task_seq", allocationSize = 100)

Is there a Bean or anything else? Because I like the idea of using the same sequence for all tables.

You can have an abstract base class with Id like:

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;

@MappedSuperclass
public abstract class BaseEntity {

    @Id 
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;

    public Long getId() {
        return id;
    }

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

}

and every entity will extend this.

That works but in the case of using hibernate Envers it would create two sequences.

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