我有一个奇怪的问题。我在数据库中有一些记录:
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 工作台中存在该记录。我不知道为什么会失败。我认为这可能与刷新会话或某些事务问题有关......?但我看到记录...