java 使用 JPA 保存到数据库中的键“PRIMARY”的重复条目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15643732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Duplicate entry for key 'PRIMARY' using JPA to persist into database
提问by user1694873
I have an error with JPA persisting into my database, the error occurs when i persist a second file into the DB. I have a requirement to import numerous datasets, with 5 sheets each. There is a requirement to update each table even if some of the same data is already in there. At the moment i get the following error
JPA 持久化到我的数据库时出现错误,当我将第二个文件持久化到数据库中时发生错误。我需要导入大量数据集,每个数据集有 5 张。即使某些相同的数据已经存在,也需要更新每个表。目前我收到以下错误
Error
错误
17:26:35,315 WARN [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost-127.0.0.1-8080-1) SQL Error: 1062, SQLState: 23000
17:26:35,316 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http-localhost-127.0.0.1-8080-1) Duplicate entry '0' for key 'PRIMARY'
Database Script
数据库脚本
My script to create the DB is as follows:
我创建数据库的脚本如下:
CREATE DATABASE IF NOT EXISTS sampleDB;
use sampleDB;
CREATE TABLE IF NOT EXISTS `Table1`(`mcc` int(10) NOT NULL,`mnc` int(10) NOT NULL,`operator` varchar(50) DEFAULT NULL,`country` varchar(50) DEFAULT NULL,
PRIMARY KEY (`mcc`,`mnc`))ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `Table2`(`tac` int(10) NOT NULL,`marketingName` varchar(50) DEFAULT NULL,`manufacturer` varchar(50) DEFAULT NULL,
`accessCapability` varchar(200) DEFAULT NULL,`model` varchar(50) DEFAULT NULL,`vendorName` varchar(50) DEFAULT NULL,
`ueType` varchar(20) DEFAULT NULL,`os` varchar(20) DEFAULT NULL,`inputMode` varchar(20) DEFAULT NULL,PRIMARY KEY (`tac`))ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `Table3`(`causeClass` varchar(10) NOT NULL,`description` varchar(255) NOT NULL,PRIMARY KEY (`causeClass`))ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `Table4`(`causeCode` int(5) NOT NULL,`eventId` int(5) NOT NULL,`description` varchar(255) DEFAULT NULL,
PRIMARY KEY (`causeCode`,`eventId`) ON UPDATE NO ACTION))ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `Table5`(`baseDataTableId` int(11) NOT NULL AUTO_INCREMENT,`dateTime` DATETIME NOT NULL,`eventId` int(5) NOT NULL,`causeClass` varchar(10) NOT NULL,
`ueType` int(15) NOT NULL,`market` int(10) NOT NULL,`operator` int(10) NOT NULL,`cellId` tinyint(2) DEFAULT NULL,`duration` smallint(7) DEFAULT NULL,
`causeCode` int(5) NOT NULL,`neVersion` varchar(7) DEFAULT NULL,`imsi` varchar(255) DEFAULT NULL,`hier3Id` varchar(255) DEFAULT NULL,`hier32Id` varchar(255) DEFAULT NULL,
`hier321Id` varchar(255) DEFAULT NULL,PRIMARY KEY (`baseDataTableId`))ENGINE=InnoDB;
Java Hibernate properties
Java 休眠属性
My Hibernate properties are as follows:
我的 Hibernate 属性如下:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="primary">
<jta-data-source>java:jboss/datasources/MySqlDS</jta-data-source>
<properties>
<!-- Properties for Hibernate -->
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.format_sql" value="false" />
</properties>
</persistence-unit>
</persistence>
Java
爪哇
Entity Class example:
实体类示例:
@Entity
@Table(name = "Table3")
public class Table3 {
@Id
private int causeClass;
private String description;
public Table3(){}
public Table3(int causeClass, String description) {
super();
this.causeClass = causeClass;
this.description = description;
}
// getters & setters
}
Any ideas how to solve this problem?
任何想法如何解决这个问题?
回答by Berto
Be sure you are using the good EntityManager's method to update existing entities. It seems that your trying to do a persist operation instead of a merge for existing entities. When persisting antity, try to catch EntityExistsException or PersistenceException and in the catch block, call merge method. For example :
请确保您正在使用良好的 EntityManager 方法来更新现有实体。您似乎试图对现有实体执行持久操作而不是合并。持久化antity时,尝试捕获EntityExistsException或PersistenceException,并在catch块中调用merge方法。例如 :
save(Enity item){
try{
//Try to insert your entity by calling persist method
}
catch(EntityExistsException e){
//Entity you are trying to insert already exist, then call merge method
}
}
回答by akash777.sharma
This error occurs when you try to update a domain object that already exists, like
当您尝试更新已存在的域对象时会发生此错误,例如
User user=UserDao.getUserById(1);
session.save(user);
Hibernate will treat it like saving a new object and it will find that a duplicate object exists.
Hibernate 会将其视为保存新对象,并且会发现存在重复的对象。
Before updating your object first load it from hibernate, like
在更新您的对象之前,首先从休眠状态加载它,例如
User updatedUser=(User)session.load(User.class, 1);
updatedUser.setName("user name");
session.saveOrUpdate(updatedUser);