1

Is there a way to check if the instance you're trying to save to table already exists in that table, but you don't know the ID like this :

MyObject instance = (MyObject) session.get(MyObject.class, new Integer(5));

Is there alternative way to check whether your object is in the db without using id?

1 Answer 1

3

You must first decide when you consider two MyObject instances to be equal, in terms of their properties, and then execute a query.

For example, let's say you have a Country entity with an ID, a name, and a currency. Two countries can be considered equal if they have the same name. But if you have a Person entity, it could be the combination of their name, firstName, date of birth and place of birth that make them functionnally equal.

To continue with my Country example, here's how to perform a query :

String hql = "select Country c where c.name = :theName";
Query q = session.createQuery(hql);
q.setString("theName", theCountryIWantToSave.getName());
Country c = query.uniqueResult();
if (c != null) {
    // a country with the same name as theCountryIWantToSave already exists
}

That's pretty basic stuff, really. You should read the Hibernate user guide.

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

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.