我有一个包含3个主键的合约类,id为auto_inctement,约定和组织是外国主键
@Entity
@IdClass(ContractIdentity.class)
@Table(name = "contract")
public class contract implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;
@Id
@ManyToOne
private Convention convention;
@Id
@ManyToOne
private Organization organization;
//getter and setter
}
public class ContractIdentity implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private Long convention;
private Long organization;
//getter and setter
//hashCode and equals
}
首先我添加一个新的约定,然后我添加一个新的组织,然后当我添加一个新的合同时,我只需输入约定的id和组织的id
这是我添加新约定时的结果
{
"id": 50,
"shortname": "string",
"fullname": "string"
}
这是我添加新约定时的结果:
{
"id": 100,
"name": "string"
}
Json添加新合同:
{
"conventionId": 50,
"organizationId": 100
}
在此步骤中显示了此错误:
传递给persist的分离实体:com.back.domain.Convention;嵌套 异常是org.hibernate.PersistentObjectException:分离的实体 传递给持续:com.back.domain.Convention
用于映射我使用的mapstruct,下面是契约映射类
@Mapper(uses = { ConventionMapper.class, OrganizationMapper.class })
public interface ContractMapper extends EntityMapper<ContractDTO, Contract> {
@Override
@Mapping(source = "convention.id", target = "conventionId")
@Mapping(source = "organization.id", target = "organizationId")
ContractDTO toDto(Contract contract);
@Override
@Mapping(source = "conventionId", target = "convention")
@Mapping(source = "organizationId", target = "organization")
Contract toEntity(ContractDTO contractDTO);
default Contract fromId(Long id) {
if (id == null) {
return null;
}
Contract contract = new Contract();
contract.setId(id);
return contract;
}
}
这是在服务中添加新合约的方法:
@Override
public ContractDTO save(ContractDTO contractDTO) {
Contract contract = ContractMapper.toEntity(contractDTO);
contract = ContractRepository.save(contract);
return ContractMapper.toDto(contract);
}
这是github
中项目的链接