Reputation: 43
I have the following class
@Entity
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "comment_id")
private Long commentId;
@Column(name = "creator_id")
private Long creatorId;
@Column(name = "text")
@ApiModelProperty(value = "Text des Kommentar")
private String text;
@Column(name = "timestamp")
@ApiModelProperty(value = "Zeitstempel der letzten Bearbeitung")
private String timestamp;
protected Comment() {}
public Comment(CommentDto dto) {
this();
updateComment(dto);
}
private void updateComment(CommentDto dto) {
setText(dto.getText());
setCreatorId(dto.getCreatorId());
setTimestamp(UtilService.getTimestampString());
}
I get a CommentDto from my HTTP-Request consisting of a the text and the creatorId.
As far as I understand, the commentId should be generated through the call of the empty constructor.
In my Service I do the following
public void addComment(CommentDto comment) {
Comment commentEntity = new Comment(comment);
commentRepository.save(commentEntity);
}
With commentRepository
being an Autowired JPARepository<Comment, Long>
The problem is, that the ID does not get generated and I get an error for trying to insert an object into my DB with a null id.
Upvotes: 2
Views: 8172
Reputation: 18430
@GeneratedValue(strategy = GenerationType.IDENTITY)
You are using GenerationType.IDENTITY
that means IdentityGenerator
which expects values generated by an identity column in the database, meaning they are auto-incremented. Make the primary key auto-incremented in database to solve this.
Or you can use GenerationType.AUTO
which is the default strategy. During a commit, the AUTO strategy uses the global number generator to generate a primary key for every new entity object. These generated values are unique at the database level and are never recycled.
@Id
@GeneratedValue
@Column(name = "comment_id")
private Long commentId;
Upvotes: 8