I am trying to write some object into the database, I wrote the following code which is working fine but the problem is that because I am using a while loop, hibernate is treating every object as a new record, which causing the database to be filled with already existed value
My question is, which annotation or technique that I can use to only write the new records (new object's value) into the database, without writing the same object again incase it was written before (Insert only if not exists)
Here is my code
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.persist(ng);andsession.saveOrUpdate(ng);