在我的项目中,我必须连接到现有数据库并执行更新两个表的逻辑。
我的设置如下:
@Entity
@Table(name = "DOCUMENTCONTENT")
@Getter
public class DocumentContent {
@Id
@Column(name = "ID", insertable = false, updatable = false)
private Long id;
@OneToOne
@JoinColumn(name = "DOCUMENT_ID", insertable = false, updatable = false)
private Document document;
@Lob
@Column(name = "CONTENT")
@Setter
private byte[] content;
}
@Entity
@Table(name = "DOCUMENT")
@Getter
public class Document {
@Id
@Column(name = "ID", insertable = false, updatable = false)
private Long id;
@OneToOne(mappedBy = "document")
private DocumentContent documentContent;
@OneToMany(mappedBy = "document", fetch = EAGER)
private List<Attachment> attachments;
}
@Entity
@Table(name = "ATTACHMENT")
@Getter
public class Attachment {
@Id
@Column(name = "ID")
private Long id;
@ManyToOne
@JoinColumn(name = "DOCUMENT_ID", insertable = false, updatable = false)
private Document document;
@ManyToOne
@JoinColumn(name = "CONTRACT_ID",updatable = false, insertable = false)
private Contract contract;
}
@Entity
@Table(name = "CONTRACT")
@Getter
public class Contract {
@Id
@Column(name = "ID", insertable = false, updatable = false)
private Long id;
@Column(name = "STATUS")
@Setter
private String status;
@ManyToOne
@JoinColumn(name = "CUSTOMER_ID", insertable = false, updatable = false)
private Customer customer;
@OneToMany(mappedBy = "contract", fetch = EAGER)
private List<Attachment> attachments;
}
@Service
public class MyServiceImpl implements MyService {
@Autowired
private DocumentContentRepository documentContentRepository; // spring data Crud Repository
@Override
@Transactional
public void updateDocumentContent(SomeDto someDto) {
DocumentContent documentContent = documentContentRepository.findByDocumentId(someDto.getDocumentId());
documentContent.setContent(someDto.getBytes());
List<Contract> contracts = documentContent.getDocument().getAttachments()
.stream().map(Attachment::getContract).collect(toList());
contracts.forEach(contract -> contract.setStatus("SIGNED"));
documentContentRepository.save(documentContent);
}
}
当我从上述服务中触发方法时,我可以在控制台输出中注意到那些SQL:
休眠:更新documentcontent集合content =?其中id =?
休眠:更新合同集状态=? id =?
我了解为什么jpa在documentcontent表中执行第一次更新,但是我也不知道为什么在contract表中也进行更新。如您所见,我没有在任何实体中使用CascadeType.MERGE
。
您能解释一下为什么执行第二个更新而不声明级联类型吗?