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?
CodePudding user response:
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)
, or Student(name)
(omitting the id)
ID as a Long
@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name= "student")
public class Student {
@Id
@GeneratedValue
@Column(name = "student_id", nullable = false)
private Long studentId;
private String name;
public Student(String name){
this.name = name;
}
}
ID as a UUID
@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name= "student")
public class Student {
@Id
@Column(name = "student_id", nullable = false)
private UUID studentId;
private String name;
public Student(String name){
this.studentId = UUID.randomUUID();
this.name = name;
}
}
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.