没有ID字段的弹簧构造器
我想为更多实体创建一个构造函数,但没有ID字段。您建议我做什么? @AllargSconstructor注释不好,因为将包括ID字段,@noargsconstructor不会为此目的做它的作业,并且@requiredargsconsstructor仅在您拥有Final或@nonull字段的情况下才是不错的。我应该设置其他列,而没有ID为@nonull或Final?另外,哪种方法更好?我应该使用@generatedValue注释将我的ID作为UUID字符串类型或长时间?
I want to create a constructor for more entities, but without the Id field. What do you recommend me to do? @AllArgsConstructor annotation is not good because then Id field would be included, @NoArgsConstructor doesn't do it's job for this purpose and @RequiredArgsConstructor is good only if you have final or @NoNull fields. Should I set my other columns, without the Id as @NoNull or final? Also, which approach is better? Should I make my Id as UUID String type or Long with @GeneratedValue annotation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要回答有关Lombok构造函数注释的第一个问题,您是对的,
@requiredargsconstructor
,@allargsconstructor
和@noargsconstructor
不适合省略ID的构造函数。但是,只要您的ID实例化,您就可以手动创建自己的构造函数,以忽略ID属性。
以下示例是用
student()
,student> studentId,name)
或student(name)
构建的(省略ID)< strong> id作为长
id作为uuid
作为
studentId
在任何一种情况下都会生成,当将其持续到数据库时,它将收到一个值无论如何,我们不需要分配一个。关于您的问题,哪种方法更好?我应该用@generatedValue注释将我的ID作为UUID字符串类型或长时间吗?,这完全取决于您,并取决于应用程序和预期用途,但是如果您结帐有关UUID vs GUID的讨论我认为这将帮助您确定UUID是否适合您的需求。
To answer your first question regarding the Lombok constructor annotations, you are right that
@RequiredArgsConstructor
,@AllArgsConstructor
, and@NoArgsConstructor
will not be appropriate for a constructor that omits the id.However as long as your id is going to be instantiated you can just create your own constructor manually that leaves out the id attribute.
The following example is constructed with either
Student()
,Student(studentId, name)
, orStudent(name)
(omitting the id)ID as a Long
ID as a UUID
As
studentId
is generated in either case, it is going to receive a value when it is persisted to the database anyway, so we don't need to assign one.Regarding your question Also, which approach is better? Should I make my Id as UUID String type or Long with @GeneratedValue annotation?, that's completely up to you and depends on the application and it's intended use, but if you checkout this discussion about UUID vs GUID I think it will help you decide whether UUID fits your needs.