hibernate 已分离的实体传递给持久化异常

nhaq1z21  于 2023-08-06  发布在  其他
关注(0)|答案(1)|浏览(119)

团队成员:

@Entity
@Table(name = Constants.TEAM_MEMBER)
@ToString
@SuperBuilder(toBuilder = true)
@EqualsAndHashCode(callSuper = true)
public class TeamMember extends BaseEntity implements Serializable {

    private static final String COLUMN_COMPANY_ID_FK = "company_id_fk";

    private static final long serialVersionUID = 413726318355320936L;

    @ManyToOne
    @JoinColumn(name = COLUMN_COMPANY_ID_FK, referencedColumnName = Constants.ID, nullable = false)
    private Company company;

   // Other columns 

}

字符串
公司名称:

@Entity
@Table(name = Constants.COMPANY)
@ToString(callSuper = true)
@SuperBuilder(toBuilder = true)
public class Company extends BaseEntity implements Serializable {

    private static final long serialVersionUID = 6747639319802376867L;

    @Column(name = Company.COLUMN_COMPANY_NAME, nullable = false, unique = true)
    private String name;
    // Other columns

}


测试代码:

@Override
    public Response<Boolean> addTeamMember(Long companyId,
            AddTeamMemberRequest addTeamMemberRequest) {
        try {
            TeamMember teamMember = buildTeamMember(companyId,
                    addTeamMemberRequest);
            teamMemberRepository.save(teamMember);
            return new Response<>(ResponseStatus.SUCCESS, true);
        } catch (Exception ex) {
            log.error("Error has occurred while saving team member {}",
                    ExceptionUtils.getStackTrace(ex));
        }
        return new Response<>(ResponseStatus.SUCCESS, false);
    }
private TeamMember buildTeamMember(Long companyId, AddTeamMemberRequest addTeamMemberRequest) {
        Company company = companyRepository.findById(companyId)
                .orElseThrow(() -> new FeastechException(ResponseStatus.INVALID_REQUEST));
        TeamMember teamMember = new TeamMember();
        teamMember.setCompany(company);
        // Other setters
        return teamMember;
    }

的字符串
错误:
2023-07-06 16:30:23.683 ERROR 28095 --- [ main] c.f.webapp.impl.TeamMemberServiceImpl:保存团队成员org.springframework.dao.InvalidDataAccessApiUsageException时出错:已分离的实体传递到持久化:网站Map_联系我们_网站Map嵌套异常为org.hibernate.PersistentObjectException:已分离的实体传递到持久化:com.feastech.webapp.entities.Company
我尝试在TeamMember上添加cascadeType.MERGE,但它不起作用,cascadeType. ALL也是如此。

axr492tv

axr492tv1#

我在addTeamMember方法上使用了@Transactional,因此它将该方法 Package 在数据库事务中。

相关问题