gpt4 book ai didi

Hibernate HQL 使用 和 删除

转载 作者:行者123 更新时间:2023-12-02 04:36:51 24 4
gpt4 key购买 nike

Hibernate 不会删除我的行:

public boolean deleteVote(Login user, int pid){

Session session = getSession();

try{
String hql = "delete from Vote where uid= :uid AND pid= :pid";
Query query = session.createQuery(hql);
System.out.println(user.getUid() + " and pid: " + pid);
query.setString("uid", user.getUid());
query.setInteger("pid", pid);
System.out.println(query.executeUpdate());
}catch(Exception e){

输出:

uid: 123 and pid: 1
Hibernate: delete from votes where uid=? and pid=?
1

当我直接在 SQL 中尝试时,SQL 语法有效。直接 SQL 语法:

 delete from votes where uid= '123' AND pid= 1

映射:

<class name="package.model.Vote" table="votes">
<id name="vid" column="vid" >
<generator class="increment"/>
</id>
<property name="pid" column="pid" />
<property name="uid" column="uid" />
<property name="tid" column="tid" />
<property name="votes" column="votes" />
</class>

表:

CREATE TABLE IF NOT EXISTS `votes` (
`vid` int(11) NOT NULL
`pid` int(11) NOT NULL,
`uid` varchar(20) NOT NULL,
`tid` int(11) NOT NULL,
`votes` int(11) NOT NULL DEFAULT '1',
PRIMARY KEY (`vid`),
KEY `pcid` (`pid`,`uid`),
KEY `uid` (`uid`),
KEY `tid` (`tid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=10 ;

ALTER TABLE `votes`
ADD CONSTRAINT `votes_ibfk_3` FOREIGN KEY (`pid`) REFERENCES `poll` (`pid`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `votes_ibfk_4` FOREIGN KEY (`uid`) REFERENCES `user` (`uid`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `votes_ibfk_5` FOREIGN KEY (`tid`) REFERENCES `teams` (`tid`) ON DELETE CASCADE ON UPDATE CASCADE;

INSERT INTO `votes` (`vid`, `pid`, `uid`, `tid`, `votes`) VALUES
(20, 1, '123', 1, 1);

我想这很简单,因为到目前为止对我来说一切看起来都很好。我没有收到错误或其他任何信息,只是没有发生删除。

感谢任何帮助。

最佳答案

您需要开始并提交事务。

Transaction transaction = session.beginTransaction();
try {
// your code
String hql = "delete from Vote where uid= :uid AND pid= :pid";
Query query = session.createQuery(hql);
System.out.println(user.getUid() + " and pid: " + pid);
query.setString("uid", user.getUid());
query.setInteger("pid", pid);
System.out.println(query.executeUpdate());
// your code end

transaction.commit();
} catch (Throwable t) {
transaction.rollback();
throw t;
}

您也可能需要关闭 session ,然后更改才会在数据库中可见。

关于Hibernate HQL 使用 和 删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13489281/

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