I am using 2 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 its spring data jdbc one to one will work without any extra annotations.
CodePudding user response:
@OneToOne( cascade = CascadeType.PERSIST)
private Address address;
CodePudding user response:
do OneToOne Mapping with Address entity and than try
Example of a one-to-one relationship, in this case between user and address entities.
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
//...
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "address_id", referencedColumnName = "id")
private Address address;
// ... getters and setters
}
@Entity
@Table(name = "address")
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
//...
@OneToOne(mappedBy = "address")
private User user;
//... getters and setters
}