Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java JPA: Performant check if Entity is already in DB

Tags:

java

jpa

entity

What is the best way / best practice to check if an entity is already in a database using JPA?

I am writing a client that adds hostinformation to a db. For example the attached storage luns, hba etc...

If I want to add a Lun for a host, I have to check if the lun is already in the database. (The Lun can be attached to another host already).

I see 2 possibilites:

  1. I make a select for the Lun, to check if it is already in the db
  2. Try to insert the Lun and check for an exception (unique constraint)

Does someone have experience with that.

BR, Rene

like image 833
reen Avatar asked Jan 03 '11 13:01

reen


2 Answers

entityManager.find(SomeEntity.class, id)

Returns: the found entity instance or null if the entity does not exist

This will do a simple select in the DB. Just make sure your collections (if any) are lazy.

like image 111
Bozho Avatar answered Nov 10 '22 23:11

Bozho


I think checking for the unique constraint exception is a better way. Think about the cost for every insert...

like image 41
zinan.yumak Avatar answered Nov 11 '22 00:11

zinan.yumak