gpt4 book ai didi

java - Hibernate 仅插入数据库新记录

转载 作者:行者123 更新时间:2023-11-29 02:12:36 25 4
gpt4 key购买 nike

我正在尝试将一些对象写入数据库,我编写了以下工作正常的代码,但问题是因为我正在使用 while 循环,hibernate 将每个对象都视为一个新记录,这导致数据库填充已经存在的值

我的问题是,我可以使用哪种注解或技术只将新记录(新对象的值)写入数据库,而无需再次写入相同的对象,以防它之前被写入(仅在不存在时插入)

这是我的代码

public class Parser {
public static void logParser() throws IOException {
// Creating the configuration object
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
// Ccreating the session factory object
SessionFactory factory = cfg.buildSessionFactory();
String fileName = "example.txt";
File logfile = new File("fileName");
Scanner scanner = new Scanner(new File(fileName), "UTF-8");
while (scanner.hasNext()) {
String s = scanner.nextLine();
if (s.startsWith("Start")) {
String[] logArray = s.split("\\|");
System.out.println(Arrays.toString(logArray));
// here is the session object
Session session = factory.openSession();
// transaction
Transaction t = session.beginTransaction();
// here is where the object is being written into the DB
NetGroup ng = new NetGroup();
ng.setNetGroup(logArray[2]);
session.persist(ng);
session.saveOrUpdate(ng);
t.commit();
session.close();
System.out.println("Successfully created an object and wrote its values into database ");
System.out.println();
}
}
scanner.close();
System.out.println("Successfully updated the Data Base");
}
}

最佳答案

你的问题发生是因为在每个循环中你创建一个新实体并持久化它,然后你提交并关闭 session ,所以当在第二个循环中开始一个新事务时,已经持久化的实体和第二个实体之间没有引用,因此将创建新实体。

您需要重新找到您的实体,然后更新它(如果存在),否则创建新实体并保留它。

该代码将解决您的问题

 public class Parser {
public static void logParser() throws IOException {
// Creating the configuration object
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
// Ccreating the session factory object
SessionFactory factory = cfg.buildSessionFactory();
String logFileName = "example.txt";
File logfile = new File("fileName");
Scanner scanner = new Scanner(new File(fileName), "UTF-8");
// here is the session object
Session session = factory.openSession();
// transaction
Transaction t = session.beginTransaction();

while (scanner.hasNext()) {
String s = scanner.nextLine();
if (s.startsWith("Start")) {
String[] logArray = s.split("\\|");
System.out.println(Arrays.toString(logArray));
Query query = session.createQuery("FROM " + getTableName() + " Where your condition "); // use unique filed
List<NetGroup> list = query.list();
if(list.size()==0){
NetGroup ng =new NetGroup();
}else{
ng =list.get(0);
}
ng.setNetGroup(logArray[2]);

session.saveOrUpdate(ng);
System.out.println("Successfully created an object and wrote its values into database ");
System.out.println();
}
}
session.close();
t.commit();
scanner.close();
System.out.println("Successfully updated the Data Base");
}
}

确保输入有效条件而不是“您的条件”

关于java - Hibernate 仅插入数据库新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47714785/

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