Issue
I am using two entities, Employee and Address, where Employee has the controller to do CRUD operations. So for both the entities I am using lifecycle events where Employee events are working fine but not the Address events. So I am trying to save Employee which has Address in it (one to one relations) and expecting Employee and Address both lifecycle events to get trigger.
Please help me.
Am I doing wrong anywhere?
Here is my code.
@Table("EMPLOYEE")
@Builder // these are lombok code
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
@Data
public class Employee {
@LastModifiedBy
private String updatedBy;
@CreatedBy
private String createdBy;
private Date dob;
@Size(max = 10)
private String name;
@Id
private Integer id;
@LastModifiedDate
private Date updatedOn;
@Version
private Long version;
@CreatedDate
private Date createdOn;
private Integer age;
@Valid
private Address address;
}
@Table("ADDRESS")
@Builder
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
@Data
public class Address {
private Integer zip;
@Id
private Integer id;
@Size(max = 10)
@NotNull
private String line1;
}
@RestController
public class EmployeeController
{
//CRUD APIs code
}
@Component
public class EmployeeEvents
extends AbstractRelationalEventListener<Employee>
{
@Override
protected void onBeforeSave(BeforeSaveEvent event) {
System.out.println("........"+ event.getEntity());
}
}
@Component
public class AddressEvents
extends AbstractRelationalEventListener<Address>
{
@Override
protected void onBeforeSave(BeforeSaveEvent event) {
System.out.println("........"+ event.getEntity());
}
}
EDIT 1:
Data getting saved properly. All I want is events to get trigger. And since it's Spring Data JDBC one to one will work without any extra annotations.
Solution
Lifecycle events and callbacks only get fired for aggregates.
Part of the design rule for aggregates says that you should access entities internal to an aggregate only by the aggregate. This would be violated when Spring Data JDBC hands out references to such entities to a listener or callback.
So the correct solution is to listen to BeforeSaveEvent
for the aggregate root, i.e. Employee
and access the Address
via the Employee
.
Answered By - Jens Schauder
Answer Checked By - Gilberto Lyons (JavaFixing Admin)