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

时间:2011-06-27 05:13:00

标签: hibernate jpa foreign-keys

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

公司

  • id = 1,Name = Microsoft
  • id = 2,Name = Sun

现在我有另一个实体,Event有一个对公司的外键引用:

@Entity
public class Event {

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

    @ManyToOne
    private Company company;
}

在我的网络服务层,我使用作为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);
    }
}

这是stacktrace的相关部分:

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工作台中存在记录。我不知道为什么会失败。我认为这可能与刷新会话或某些交易问题有关...?但我看到了记录......

2 个答案:

答案 0 :(得分:3)

你必须提到@JoinColumn

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

这是负责在事件表上创建company_id。

答案 1 :(得分:2)

我把问题缩小了,并在这里发布了另一个问题:

JPA/Hibernate - Entity name seems to be important. If I rename to "Bob" works fine

我在这里找到了解决方案:

http://developmentality.wordpress.com/2011/05/23/hibernate-mysql-mac-foreign-key-nightmares-a-painless-solution-to-a-painful-problem/

由于mysql,hibernate和mac os x的结合,你需要在hibernate中使用小写命名策略。 Hibernate默认使用驼峰式命名策略。

相关问题