英文:
Spring Boot: Set hibernate sequence globally
问题
@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)
使用这个示例,所有的表都使用相同的序列:hibernate_sequence
。
如果我想进行配置,例如设置自定义的 allocationSize
,我必须在每个表中都定义,对吗?
@SequenceGenerator(name = "task_seq", sequenceName = "task_seq", allocationSize = 100)
是否有一个 Bean 或其他内容?因为我喜欢为所有表使用相同的序列的想法。
英文:
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 e.g. 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.
答案1
得分: 1
您可以拥有一个带有Id的抽象基类:
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;
}
}
每个实体将会继承这个基类。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论