JPA question ?

N

news.t-com.hr

Lets say i have entity Car that has has FK to EngineType entity.

public class Car{

public EngineType type;


}

public class EngineType{

public Long engineTypeId;

}

and I want to persist Car. One way is to do find EngineType entity by ID
entityManager.find(EngineType.class, 999), set that to Car and persist Car,
and
the other way is to do this. Create new instance of engineType EngineType
newInstance = new EngineType(). Set id to it,
newInstance.setEngineTypeId(999),
than set that to Car, and persist ?

Both method works but which is more efficient, better ?

thanks in advance.
 
A

Arved Sandstrom

news.t-com.hr said:
Lets say i have entity Car that has has FK to EngineType entity.

public class Car{

public EngineType type;


}

public class EngineType{

public Long engineTypeId;

}

and I want to persist Car. One way is to do find EngineType entity by ID
entityManager.find(EngineType.class, 999), set that to Car and persist Car,
and
the other way is to do this. Create new instance of engineType EngineType
newInstance = new EngineType(). Set id to it,
newInstance.setEngineTypeId(999),
than set that to Car, and persist ?

Both method works but which is more efficient, better ?

thanks in advance.

Let your database and the ORM worry about ID's.

As for EngineType, if it's really a class (as opposed to an enum), just
construct it, leaving out the ID bit (let the ORM and DB worry about
that part).

AHS
 
J

Jean-Baptiste Nizet

Arved Sandstrom a écrit :
Let your database and the ORM worry about ID's.

As for EngineType, if it's really a class (as opposed to an enum), just
construct it, leaving out the ID bit (let the ORM and DB worry about
that part).

If I understood correctly, the OP wants to create a new Car with an
EngineType that already exists in the database. And he knows the ID of
the EngineType.
I would use the getReference() method (see
http://java.sun.com/javaee/5/docs/a...tReference(java.lang.Class, java.lang.Object))

This has the same effect as find if the EngineType already is already
loaded in the session, and the EM might very well just give you a proxy
to the entity, without going to the database, if it isn't already loaded
and works that way.

JB.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,185
Members
46,736
Latest member
AdolphBig6

Latest Threads

Top