开发者

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. Tr开发者_运维知识库y 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...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜