简体   繁体   English

使用Hibernate和MySQL更新具有主键和唯一列的表

[英]Update table with primary key and unique columns using Hibernate and mySQL

I have a table containing four columns: 我有一个包含四列的表:

CREATE TABLE `participants` (
 `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
 `name` VARCHAR(128) NOT NULL,
 `function` VARCHAR(255) NOT NULL,
 `contact` VARCHAR(255) NOT NULL,
 PRIMARY KEY (`id`),
 UNIQUE INDEX `name_function_contact` (`name`, `function`, `contact`)
)

From the application I get participants -objects, which might have values for name , function and contact which are already in that exact matter in the database. 从应用程序中,我得到participants对象,这些对象可能具有namefunctioncontact值,而这些值已经在数据库中确切存在。 In this case I want Hibernate to get me the id of that object, otherwise I want to save the object. 在这种情况下,我希望Hibernate为我获取该对象的id ,否则我想保存该对象。

Using saveOrUpdate() I just get an: 使用saveOrUpdate()我得到一个:

org.hibernate.exception.ConstraintViolationException: Duplicate entry 'NAME-FUNCTION-CONTACT: NAME' for key 'name_function_contact'

How can I accomplish this? 我该怎么做? Thanks a lot! 非常感谢!

Since the answers suggested that Hibernate cannot do it on its own (bummer!) I solved it the "native sql" way: 由于答案表明Hibernate不能自己完成(bummer!),所以我以“本地sql”方式解决了它:

Participants tempParti = ((Participants) session.createQuery("FROM Participants WHERE name = '" + p.getName() + "' AND function = '" + p.getFunction() + "' AND contact = '" + p.getContact() + "'").uniqueResult());
if (tempParti != null) {
    p = tempParti;
} else {
    session.save(p);
}

Works like a charm! 奇迹般有效! Thanks to all of you! 感谢大家!

I am no expert in Hibernate. 我不是休眠专家。 But from Mysql perspective, you do the following. 但是从Mysql的角度来看,您可以执行以下操作。

use INSERT IGNORE INTO... to add the value in the table. 使用INSERT IGNORE INTO...将值添加到表中。 If the number of rows inserted is 0, then you can manually get the ID of the row by a SELECT statement. 如果插入的行数为0,则可以通过SELECT语句手动获取该行的ID。

EDIT: LAST_INSERT_ID() was wrong here. 编辑:LAST_INSERT_ID()在这里是错误的。 I have edited the answer. 我已经编辑了答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM