在使用复合外键的@EmbeddedId的情况下,保存@OneToMany实体及其子实体可以按照以下步骤进行:
@Embeddable
public class ParentId implements Serializable {
private Long parentId;
private Long childId;
// getters and setters
// equals and hashCode methods
}
然后,我们创建一个名为Parent的实体类,并使用@EmbeddedId注解来引用ParentId类:
@Entity
public class Parent {
@EmbeddedId
private ParentId id;
// other attributes and relationships
// getters and setters
}
public class ChildId implements Serializable {
private Long parentId;
private Long childId;
// getters and setters
// equals and hashCode methods
}
@Entity
@IdClass(ChildId.class)
public class Child {
@Id
private Long parentId;
@Id
private Long childId;
// other attributes and relationships
// getters and setters
}
@Entity
public class Parent {
@EmbeddedId
private ParentId id;
@OneToMany
@JoinColumn(name = "parentId")
private List children;
// other attributes and relationships
// getters and setters
}
@Repository
public interface ParentRepository extends CrudRepository {
}
@Service
public class ParentService {
@Autowired
private ParentRepository parentRepository;
public void saveParentAndChildren(Parent parent, List children) {
parent.setChildren(children);
parentRepository.save(parent);
}
}
这样,当调用saveParentAndChildren方法时,父实体及其子实体将保存到数据库中。