Well the first problem with the code is the wrong string comparison, you should use equals()
method instead of ==
when comparing strings. See How do I compare strings in Java? for details.
Having said that your code could be highly improved as follows:
public String insert(Object obj, String idGen) {
if ("auto".equals(idGen) || "manual".equals(idGen)) {
try {
entityManager.getTransaction().begin();
entityManager.persist(obj);
entityManager.getTransaction().commit();
return "Inserted row";
} catch (Exception ex) {
e.printStackTrace();
return String.format("Insertion failed: %s", ex.toString());
}
}
return String.format("Object not inserted because of idGen value: %s", idGen);
}
In this way you do not create transactions at least you are completely positive you have to insert the object in database, saving the cost of transaction management. You have also tested the two positive cases in just one if instead of having an if-else if
block.
Now, back to the original question, the code presented above should be enough to test if an object has been inserted on database. But you always can test it yourself with a local database connection.
Hint
Catching a generic exception is not a good practice, we should catch specific ones instead. For instance looking at EntityManager#persist() we can see that this method can throw EntityExistsException
, IllegalArgumentException
or TransactionRequiredException
. So catching these exceptions makes much more sense than the generic Exception
type.