0

I'm trying to use a foreign key in Hibernate/Spring Boot with the @OneToMany and @ManyToOne annotations, but I keep getting this error:

java.sql.SQLException: Field 'note_id' doesn't have a default value

My code:

Note.java

@Entity
@Table(name = "notes")
@EntityListeners(AuditingEntityListener.class)
public class Note {

public Note() {
}

public Note(String name, String content) {
    this.name = name;
    this.content = content;
}

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "note_id")
private Integer id;

@ManyToOne
@JoinColumn(name = "user_id")
private User user;

@NotBlank
private String name;

@NotBlank
@Column(columnDefinition="LONGTEXT")
private String content;

User.java

@Entity
@Table(name  = "user")
@EntityListeners(AuditingEntityListener.class)
public class User implements Serializable {

public User() {
}

public User(String username, String password) {
    this.username = username;
    this.password = password;
}

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_id")
private Integer id;

@OneToMany(mappedBy = "user", cascade = ALL)
private Set<Note> notes;

@NotEmpty
@Column(nullable = false, unique = true)
private String username;

@NotEmpty
private String password;

The error occurs whenever I try to create a note. Thanks in advance!

myst02
  • 13
  • 1
  • 4
  • 1
    Possible duplicate of [java.sql.SQLException: Field 'supplier\_id' doesn't have a default value](https://stackoverflow.com/questions/26336520/java-sql-sqlexception-field-supplier-id-doesnt-have-a-default-value) – The Head Rush May 16 '19 at 13:16
  • What kind of database are you using? If it's a MySQL do you have auto_increment on the note_id field? – Simon Martinelli May 16 '19 at 13:30
  • You should definitly make `note_id` an identity column. Even more so since you already annotate it like that – XtremeBaumer May 16 '19 at 13:33
  • Finally solved this by removing `@Column(name = "note_id")`, thanks for your help! – myst02 May 16 '19 at 18:13

0 Answers0