JPA/hibernate - 无法添加或更新子行:外键约束失败 - 但记录存在

2024-01-29

我有一个奇怪的问题。我在数据库中有一些记录:

Company

  • ID = 1,名称 = Microsoft
  • id = 2,名称 = 太阳

现在我有另一个实体 Event,它具有对 Company 的外键引用:

@Entity
public class Event {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    @ManyToOne
    private Company company;
}

在我的 Web 服务层中,我使用作为 URL 参数传递的公司 ID 创建一个事件:

@GET
@Path("addEvent")
public String addEvent(@QueryParam("cid") long companyId) {
    Company alreadyInDB = new Company();
    alreadyInDB.setId(companyId);

    Event event = new Event();
    event.setCompany(alreadyInDB);
    eventService.addEvent(event);
}

这将调用 EventService。我最初使用的是注释掉的代码行。但是,当由于外键约束失败而失败时,我添加了代码以确保公司记录存在。果然,代码打印出了正确的 ID。但它仍然因违反外键约束而失败。

@Service("eventService")
public class EventService {

    @Autowired
    EventDAO eventDAO;

    @Autowired
    CompanyDAO companyDAO;

    @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) 
    public void addEvent(Event event) throws Exception
    {
        System.out.println("Company ID: " + event.getCompany().getId());

        Company ensureRecordExists = companyDAO.findById(event.getCompany().getId());
        System.out.println("ensureRecordExists: " + ensureRecordExists.getId());
        event.setCompany(ensureRecordExists);
        //event.setCompany(companyDAO.getReferenceById(event.getCompany().getId()));
        eventDAO.persist(event);
    }
}

这是堆栈跟踪的相关部分:

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`blah`.`event`, CONSTRAINT `FKE7E9BF09F9DCA789` FOREIGN KEY (`company_id`) REFERENCES `Company` (`id`))
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)

知道发生了什么事吗?我可以实际看到 mysql 工作台中存在该记录。我不知道为什么会失败。我认为这可能与刷新会话或某些事务问题有关......?但我看到记录...


你必须提到@JoinColumn

@ManyToOne
@JoinColumn(name = "company_id")
private Company company;

它负责在事件表上创建company_id。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JPA/hibernate - 无法添加或更新子行:外键约束失败 - 但记录存在 的相关文章

随机推荐