D
D
DarkByte20152017-08-09 15:38:11
Java
DarkByte2015, 2017-08-09 15:38:11

Why is there an error when saving?

There is a (simplified) class diagram like this:

@Entity
@Table(name = "my_sub_model")
public class MySubModel {

    @Id
    @GeneratedValue
    @Column
    public Long id;

    @Version
    private Integer version;

    @Basic(optional = false)
    @Column
    public String name;
}

@Entity
@Table(name = "my_model")
public class MyModel {

    @Id
    @GeneratedValue
    @Column
    public Long id;

    @Version
    private Integer version;

    @Basic(optional = false)
    @OneToOne
    @JoinColumn(name = "sub_model_id")
    public MySubModel subModel;
}

Communication is one to one. But it is important for me that MySubModel never changes (this is a reference). I do in DAO:
public void addMyModel(MyModel model) {
  em.persist(model);
}

And I get an error like "ohejdbc.spi.SqlExceptionHelper - NULL value is not allowed for field SUB_MODEL_ID". The question is why is this happening? I debugged everything - the model has the subModel field initialized, but this field only has an id - it is not NULL 100%, but the rest of the fields are NULL (as it should be). How can I make sure this error doesn't happen? (just don't suggest fully initializing the subModel - it shouldn't).
An example of a model that is fed into a function (its fullness):
{
  "id": null,
  "subModel": {
    "id": 1,
    "name": null
  }
}

upd. Again, the error looks like this:
org.h2.jdbc.JdbcSQLException: NULL value is not allowed for field "SUB_MODEL_ID"
NULL not allowed for column "SUB_MODEL_ID"; SQL statement:
insert into my_model (id, sub_model_id, version) values ​​(null, ?, ?)
Help!!!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
DarkByte2015, 2017-08-12
@DarkByte2015

After I did this in DAO
The problem was finally solved and everything was added!

A
Alexander Kosarev, 2017-08-11
@jaxtr

You need to add cascading on save:

@Basic(optional = false)
@OneToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "sub_model_id")
public MySubModel subModel;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question