我想更新与作为查询对象的同一个表相关联的外键。
我可以像这样插入新数据(问题和外键)
public void insert_question(String question, int left, int right) throws HibernateException
{
try
{
Session session = getSession();
Transaction tx = session.beginTransaction();
Nodes node = new Nodes();
Nodes leftNode = new Nodes();
Nodes rightNode = new Nodes();
node.setQuestion(question);
leftNode.setId_node(left);
node.setLeft(leftNode);
rightNode.setId_node(right);
node.setRight(rightNode);
session.saveOrUpdate(node);
tx.commit();
session.close();
但我无法使用此方法更新现有数据
public void update(int last_left_id, int new_left_id)
{
try
{
Session session = getSession();
Transaction tx = session.beginTransaction();
Nodes leftNode = new Nodes();
Nodes node = new Nodes();
leftNode.setId_node(last_left_id);
node.setLeft(leftNode);
Query query = getSession().createQuery("update Nodes set left_id = :left_id"+" where id = :id" );
query.setParameter("left_id", leftNode);
query.setParameter("id", new_left_id);
int result = query.executeUpdate();
session.close();
使用第一种方法,我的外键被插入到我的表中。 但是使用第二种方法,我无法更新现有的外键
这是我的错误
Grave: Cannot add or update a child row: a foreign key constraint fails (`akinator`.`node`, CONSTRAINT `node_ibfk_1` FOREIGN KEY (`left_id`) REFERENCES `node` (`id`) ON DELETE CASCADE)
Grave: org.hibernate.exception.ConstraintViolationException: could not execute update query
我该怎么做?
非常感谢
答案 0 :(得分:0)
如果您无法通过代码执行任何操作,那么最好运行sql补丁。实际上在我们的应用程序中,我们通过在启动时运行脚本来做同样的事情。所以这种方式可以解决您的问题。
例如,如果要在订单表上添加外键,则编写程序以使用java在启动操作上执行此脚本。
ALTER TABLE Orders
ADD FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
这是我的帮助,但我建议你我们可以用这种方式做到这一点。 :)
感谢。