1

I have following model structure:

@Entity
@Table(name = "MY_TEMPLATE")
public class MyTemplate {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", nullable = false, updatable = false)
    private Long id;
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "MY_TEMPLATE_ID")
    private List<MyObject> myobjects = new ArrayList<>();
    ...
}

@Entity
@Table(name = "MY_OBJECT")
public class MyObject implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", nullable = false, updatable = false)
    private Long id;
}

MyDailyResource doesn't have reference to MyTemplate

I have also usual CrudRepository:

public interface MyTemplateRepository extends CrudRepository<MyTemplate, Long> {
}

When I execute:

myTemplateRepo.save(myTemplate) // myTemplate has one element in myObjects collection

I see following error:

    insert 
    into
        MY_TEMPLATE
        (LAST_MODIFIED, LAST_MODIFIED_BY, NAME) 
    values
        (?, ?, ?)


    insert 
    into
        MY_OBJECT
        (BAR, FOO) 
    values
        (?, ?)

java.sql.SQLException: Field 'MY_TEMPLATE_ID' doesn't have a default value
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)

I have no ideas what do I wrong and how to fix it.

Could you, please, recommend me something?

P.S.

Looks like it is because I have not null constraint for that foreign key in database. But I don't like to remove that constraint

gstackoverflow
  • 36,709
  • 117
  • 359
  • 710

1 Answers1

0

Hope your parent table is MY_TEMPLATE and child table is MY_OBJECT

updating you classes

@Entity
@Table(name = "MY_TEMPLATE")
public class MyTemplate {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", nullable = false, updatable = false)
    private Long id;
    @OneToMany(mappedBy="myTemplate", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<MyObject> myObjects = new ArrayList<>();
    ...
}

@Entity
@Table(name = "MY_OBJECT")
public class MyObject implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", nullable = false, updatable = false)
    private Long id;
    @ManyToOne
    @JoinColumn(name = "MY_TEMPLATE_ID")
    private MyTemplate myTemplate;
}
gstackoverflow
  • 36,709
  • 117
  • 359
  • 710
Faiz Akram
  • 559
  • 4
  • 10