'Bi-directional relation in hibernate is failing to be cascadelly saved
I am using a Spring-Boot (2.3.3) application with Hibernate (5.4.20) and JPA repository on MySql DB, and I have a Bi-directional relationship between an entity:
@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@SuperBuilder
@EqualsAndHashCode(callSuper = true)
@DynamicUpdate(DBConfig.dynamicUpdate)
@Table(name = "entity")
public class Entity implements Serializable {
@GeneratedValue(strategy = IDENTITY)
@Column(updatable = false, columnDefinition = "BIGINT UNSIGNED NOT NULL")
@Id
private Long id;
...
@ManyToOne
@JoinColumn(name = "entity_group_id")
private EntityGroup entityGroup;
}
which is connected "many to one" to a group entity
@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@SuperBuilder
@EqualsAndHashCode(callSuper = true)
@DynamicUpdate(DBConfig.dynamicUpdate)
@Table(name = "entity_group")
public class EntityGroup implements Serializable {
@GeneratedValue(strategy = IDENTITY)
@Column(updatable = false, columnDefinition = "BIGINT UNSIGNED NOT NULL")
@Id
private Long id;
...
@OneToMany(cascade = {CascadeType.ALL})
@JoinColumn(name = "entity_group_id")
private Set<Entity> entities;
}
I am trying to save them both in 1 transaction, something like:
EntityGroup group = EntityGroup.builder().entities(getEntities()).build();
jpaRepository.save(group);
For some reason, Hibernate always fails to save the entities to the DB with this root error:
Column 'entity_group_id' cannot be null
I've tried all day to tweak the annotations but nothing is working, and I also saw this: Save child objects automatically using JPA Hibernate , but couldn't make it work. Can anyone tell me what am I doing wrong here?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|