I'm creating an app using Java Spring. I have two entities - User and Machine.
@Getter
@Setter
@Entity
@Table
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@NotNull
private Long id;
// etc.
}
@Getter
@Setter
@Entity
@Table
public class Machine {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@NotNull
private Long id;
@ManyToOne
@JoinColumn(name = "created_by")
@NotNull
private User createdBy;
}
When I'm saving a new User, I'm not passing the id, and it gets saved successfully. When I'm saving a new Machine and I don't pass the id, I get an error that validation failed. When I pass the id or remove the @NotNull, it gets saved successfully. Why is that? It's defined the same way, and both entities get saved the same way.
The error I'm getting: ConstraintViolationImpl{interpolatedMessage='must not be null', propertyPath=id, rootBeanClass=class raf.edu.rs.nwpbackend.model.Machine, messageTemplate='{javax.validation.constraints.NotNull.message}'}
CodePudding user response:
@NotNull
means that data member is compulsory and need to set in that object
Because you are using @Genratedvalue()
this means it saves the id in the increment order in the database
@Id
means primary key it has the condition not null explicitly you don't need to mention it
if you mention it then you have set id the object which you are passing
that why you are getting errors.
CodePudding user response:
You may remove @NotNull from both ids. This annotation is a bean validation, made before database insert.
See the exception message: javax.validation.constraints.NotNull.message