问题描述
我有一个映射为实体的类将其保存在数据库中。我有一个id字段作为主键,因此每次持久对象时,id的值都会从序列myClass_pk_seq中检索,类似于下面的代码。
@Entity
@Table(name =myObjects)
public class MyClass {
@Id
@GeneratedValue(strategy = GenerationType .SEQUENCE,generator =sequence)
@SequenceGenerator(name =sequence,sequenceName =myClass_pk_seq,allocationSize = 1)
@Column(name =myClassId)
private整数ID;
私人整数代码;
...
}
我需要在code属性中做类似于id的东西。我需要一个序列,以便我可以指定序列的下一个值(以保留该值,以防用户想要保留该值但不保留数据)。我的意思是用户会看到该字段,如果他不知道该输入什么内容,他可以按下按钮并在屏幕上接收下一个可能的值(他可以接受或不接受)。我怎样才能获得在JPA中定义的序列的下一个值(并增加它的值),而不需要保存非主键字段的数据?
我只想拥有调用与代码字段相关的序列的nextval并返回该值的方法。
谢谢。
在JPA中使用注释执行此操作的最佳方式是什么? >
- 使用原生SQL获取下一个序列当用户按下按钮时的值。要么手动创建序列,要么使用假实体让JPA为您创建它。
- 如果您不想使用原生SQL,请插入依赖序列的实体并获得它的ID。
这两个解决方案听起来有点难看。也许你可以简单地使用像UUID生成器那样的随机生成器。实际上,你没有提及任何有关代码
的唯一性(并且JPA注释不包含任何关于代码
表明它必须是唯一的)。你为什么不返回一个随机int?
I have a class mapped as an Entity to persist it in a database. I have an id field as the primary key so every time the object is persisted the value of the id is retrieved from the sequence "myClass_pk_seq", a code like the following one.
@Entity
@Table(name="myObjects")
public class MyClass {
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="sequence")
@SequenceGenerator(name="sequence", sequenceName="myClass_pk_seq", allocationSize=1)
@Column(name="myClassId")
private Integer id;
private Integer code;
...
}
I need to make in "code" attribute something similar to id. I need to have a sequence so I can assign to code the next value of the sequence (to reserve that value in case the user wants to reserve it but without persisting data). I mean the user will see the field, if he doesn't know what to enter he can push a button and receieve in the screen the next possible value (and he can or not accept it). How can I get the next value of a sequence defined in JPA (and increment its value) without persisting the data for a non primary key field?
I just want to have a method which call nextval on a sequence associated with "code" field, and returns the value. What's the best way to do it in JPA with annotations?
Thanks.
- Use native SQL to get the next sequence value when the user pushes the button. Either create the sequence manually or use a "fake entity" to have JPA create it for you.
- If you don't want to use native SQL, insert an entity relying on the sequence and gets its id.
Both solutions sounds a bit ugly. Maybe you could simply use a random generator like a UUID generator.
Actually, you didn't mention anything about the uniqueness of the code
(and the JPA annotations don't show it must be unique). Why don't you return a random int?
这篇关于在jpa中调用序列的下一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!