000000000000000000000
000000000000000000000

Reputation: 880

Turn existing entries on table into Hibernate entity objects

I want to eliminate duplication in the data I receive (I turn the data into Objects (Company.java) and store them in table through Hibernate).

Whenever a new data comes in, I want to check it against all the entries through query. In this case I am using the uniquiResult() method to check if data is already in the table.

Then, if the data doesn't exist already, create a new Company object with the data and save the Company object to the session.

However, if the data already exists, how do I grab the existing entry and turn it into an object?

My code is below:

            Company company;
            if(session
                    .createQuery("from company where company_name=:placeholder")
                    .setParameter("placeholder", data.getCompanyName())
                    .uniqueResult()
                    !=null){
                company = ????;
            } else {
                company = new Company(data.getCompanyName());
                session.save(company);
            }

Thanks.

Upvotes: 0

Views: 103

Answers (2)

old-monk
old-monk

Reputation: 931

If you look into the documentation of Hibernate Session object

 Object uniqueResult() 
      Convenience method to return a single instance that matches the query, or null if the query returns no results.

i.e it executes your query, fetch the record from database and turn it into object for you.

The code you looking for is:

Company company = session.createQuery("from company where company_name=:placeholder")
                .setParameter("placeholder", data.getCompanyName())
                .uniqueResult()
                !=null;
if(company == null) {
  company = new Company(data.getCompanyName());
  session.save(company);
}

Upvotes: 1

Maciej Kowalski
Maciej Kowalski

Reputation: 26552

Company company = session
                    .createQuery("from company where company_name=:placeholder")
                    .setParameter("placeholder", data.getCompanyName())
                    .uniqueResult();


if(company == null) {
    company = new Company(data.getCompanyName());
    session.save(company);
}

Upvotes: 1

Related Questions