2

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");
  }
  }
3
  • 1
    Your entity should have an id field declared with @Id which would be the primary key in your database table. If you set an existing record id to your object it will be updated, and if it doesn't it will be treated as a new record. Commented Dec 8, 2017 at 12:55
  • why there is session.persist(ng); and session.saveOrUpdate(ng); Commented Dec 8, 2017 at 12:56
  • You should also show the NetGroup class. Commented Dec 8, 2017 at 12:58

2 Answers 2

2

Your issue is happened because in each loop you create a new entity and persist it, then you commit and close the session, so when begin a new transaction in second loop there is no reference between the already persisted entity and second one, so new entity will be created.

You need to re find your entity then update it if existed, else create new one and persist it.

That code will fix your issue

 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");
    }
}

Make sure put valid condition instead of "your condition"

Sign up to request clarification or add additional context in comments.

4 Comments

Hello Ahmad, thank you for your fast reply, I am not sure what do you mean about the condition in "your condition" also the "getTableName()" shouldnät be getNetGroup(), I am not sure, I tried it but itäs not working. lastly ng =list.get(0); } ng.setNetGroup(logArray[2]); session.saveOrUpdate(ng); the ng object is not resolved.
Hello, Just change this line Query query = session.createQuery("FROM " + getTableName() + " Where your condition "); // use unique filed and put you condition to get the value form database if existed
@Hiber did that help you ?
Hey Ahmad, thank you a lot, it didn't actually work, but I learned that I need to include a query in my code, so I took it from there and made some research on that and my code is working fine now, but the code that you included is not 100% accurate, although the idea behind it is the key for the solution, so thank you.
0

I think you can use the primary key concept there to remove the duplicacy of rows and use the saveOrUpdate method.

If we work with hibernate API there should be one PK in the class.

session.saveOrUpdate(ng);

That above method check the record on the basis of primary key, if PK does not exists in the DB then it fire the insert query if exists then it update the same record rather than inserting new one.

public class NetGroup

{

private int primaryKeyId;

public int getprimaryKeyId() {
        return primaryKeyId;
    }

    public void setprimaryKeyId(int primaryKeyId) {
        this.primaryKeyId = primaryKeyId;
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.