简体   繁体   中英

Java JPA: Performant check if Entity is already in DB

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM