gpt4 book ai didi

java - 简单地从数据库中删除

转载 作者:行者123 更新时间:2023-11-29 10:22:26 25 4
gpt4 key购买 nike

我正在尝试使用通用方法从数据库中删除数据。它适用于添加、更新,但在删除时我得到这个:

java.sql.SQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (mydb.testCases, CONSTRAINT fk03 FOREIGN KEY (type) REFERENCES testType (idtestType) ON DELETE NO ACTION ON UPDATE NO ACTION)

数据库

 //delete the object to the database
public static void deleteObject(Object object) {
SessionFactory factory = HibernateUtil.GetSessionFactory();
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
session.delete(object);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}

我的删除尝试

  List<TestFlow> flow = getFlow(flowName);

//delete the current one
for(TestFlow tf : flow) {
Database.deleteObject(tf);
}

HBM

<hibernate-mapping>
<class name="com.atp.Model.TestCases.TestFlow" table="testFlow">
<meta attribute="class-description">
This class contains the testCases flow details.
</meta>
<id name="id" type="int" column="idtestFlow">
<generator class="native"/>
</id>
<property name="name" column="name" type="string"/>
<many-to-one name="testCase" class="com.atp.Model.TestCases.TestCase" column="testCase" fetch="select" cascade="all" lazy="false"/>
<property name="rowNumber" column="rowNumber" type="int"/>
<property name="testCaseStatus" column="testCaseStatus" type="int"/>
<property name="params" column="params" type="string" />
<property name="creationDate" column="creationDate" type="string"/>
<property name="createdBy" column="createdBy" type="string"/>
<property name="targetType" column="targetType" type="string"/>
<property name="targetName" column="targetName" type="string"/>
<property name="output" column="output" type="string"/>
<property name="completionDate" column="completionDate" type="string"/>
<property name="isCompleted" column="isCompleted" type="int"/>
</class>

最佳答案

似乎您的约会表中的外键具有删除时:限制选项。将约束 Appointments_user_id_foreign 更改为删除时:级联,您应该能够在保留外键的同时删除用户。

你可以通过两种方式做到这一点:

a.首先使用单独的删除语句从约会表中删除关联记录。

b.向appointments_user_id_foreign 外键添加删除级联选项。当您删除用户记录时,此选项将自动从约会表中删除要删除的用户的所有关联记录。

根据您的需要尝试一下

Query q = session.createQuery("from Stock where stockCode = :stockCode ");
q.setParameter("stockCode", "4715");
Stock stock = (Stock)q.list().get(0);
session.delete(stock);

  @OneToMany(cascade=CascadeType.REMOVE) 
List<TestFlow> flow = getFlow(flowName);

//delete the current one
for(TestFlow tf : flow) {
Database.deleteObject(tf);
}

关于java - 简单地从数据库中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48987238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com