Issue
I have two entities with this kind of relation
EVENT
@Data
@Table(name = "Event", schema = "schema")
public class Event extends Loggable implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
// ....
@OneToMany(cascade = {CascadeType.PERSIST, CascadeType.ALL}, fetch = FetchType.EAGER)
List<RecurringPattern> recurringPatterns;
private void setRecurringPatterns(List<RecurringPattern> children) {
this.recurringPatterns = children;
}
public void addRecurringPattern(RecurringPattern child) {
recurringPatterns.add(child);
child.setEvent(this);
}
RECURRING PATTERN
@Data
@Table(name = "RecurringPattern")
public class RecurringPattern implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(name = "eventId") <-- ManyToOne here has caused problems
private Event event;
}
In a Controller in an "one shot" operation, I try to save at the same time an Event
and his RecurringPattern
child, reading the data from a Json.
event = new Event();
recurringPattern = new RecurringPattern();
event.GetDataFromJson(...);
recurringPattern.GetDataFromJson(...);
event.addRecurringPattern(recurringPattern);
try {
eventRepository.save(event);
}
catch(Exception e) {
System.out.println(e.getMessage());
}
With the debugger everything seems fine and no Exception is thrown during the .save()
method.
But then I get this kind of error in the Stacktrace:
com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Incorrect integer value: '\xAC\xED\x00\x05sr\x00&it.***.checklist.models.calendar.Event\xD9\x09\xD1\x95\xF9\xBF\x05F\x02\x00\x0FL\x00\x09createdByt\x00\x1' for column `schema`.`recurringpattern`.`eventId` at row 1
I really don't get it, is it something related to my annotations or the Utf encoding of the DB?
Solution
You should correct this:
@Column(name = "eventId") <-- ManyToOne here has caused problems
private Event event;
to this:
@ManyToOne
@JoinColumn(name = "eventId")
private Event event;
and this:
@OneToMany(cascade = {CascadeType.PERSIST, CascadeType.ALL}, fetch = FetchType.EAGER)
List<RecurringPattern> recurringPatterns;
to this:
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "event")
List<RecurringPattern> recurringPatterns;
See also this section of hibernate documentation.
Answered By - SternK
Answer Checked By - Marie Seifert (JavaFixing Admin)