gpt4 book ai didi

java - 从数据库中删除一个简单的行

转载 作者:行者123 更新时间:2023-11-30 21:44:18 25 4
gpt4 key购买 nike

我有 2 个表,testInputtestCases 并且在 testInput 中我有一个 FK 和另一个表的 id。

所以基本上我要删除的行是输入的 id、testCase 的 id、名称和描述。

'43', '21', 'USERNAME', 'USERNAME'
'44', '21', 'PASSWORD', 'PASSWORD'

我试图删除该行,但我得到了

java.sql.SQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (mydb.testInput, CONSTRAINT fk02 FOREIGN KEY (testCase) REFERENCES testCases (idtestCase) ON DELETE NO ACTION ON UPDATE NO ACTION)

我不想删除testCase的记录。我只想删除那个测试用例的输入。我该怎么办?

代码如果你想要...

  List<TestInput> previousInputs = TestInput.getInputs(testCaseName);
for(TestInput in : previousInputs) {
Database.deleteObject(in);
}



//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();
}
}

xml 测试用例

   <hibernate-mapping>
<class name="TestCase" table="testCases">
<meta attribute="class-description">
This class contains the testCases details.
</meta>
<id name="id" type="int" column="idtestCase">
<generator class="native"/>
</id>
<property name="name" column="name" type="string"/>
<many-to-one name="type" class="TestType" column="type" fetch="select" lazy="false"/>
<property name="data" column="data" type="binary"/>
<property name="amountOfInputs" column="amountOfInputs" type="int"/>
<property name="creationDate" column="creationDate" type="string"/>
<property name="createdBy" column="createdBy" type="string"/>
<many-to-one name="tellerConfig" class="TellerConfiguration" column="tellerConfig" fetch="select" lazy="false"/>
</class>
</hibernate-mapping>

xml 测试输入

<hibernate-mapping>
<class name="TestInput" table="testInput">
<meta attribute="class-description">
This class contains the testCases input details.
</meta>
<id name="id" type="int" column="idtestInput">
<generator class="native"/>
</id>
<property name="name" column="name" type="string"/>
<property name="description" column="description" type="string"/>
<many-to-one name="testCase" class="TestCase" column="testCase" fetch="select" cascade="all" lazy="false" />
</class>

最佳答案

将外键 fk02 的约束从“NO ACTION”更改为“SET NULL”

FOREIGN KEY (idtestcase)
REFERENCES testCases(idtestCase)
ON DELETE SET NULL

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

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