kostepanych
kostepanych

Reputation: 2619

How to persist many-to-many collection in JPA2 if I have only IDs?

Here is My many-to-many collection:

    @ManyToMany
@JoinTable(name="affiliated_databases",
        joinColumns=
        @JoinColumn(name="database_id", referencedColumnName="id"),
        inverseJoinColumns=
        @JoinColumn(name="affiliated_database_id", referencedColumnName="id")
)
public Set<Database> affiliatedOrgs;

And in my service class method I have only IDs of this collection. Is there any good solution to persist this collection without reading its elements from database?

I'm trying to do something like this:

 for (Long affId: affIds) {
            Database affDatabase = new Database();
            affDatabase.setId(affId);
            target.getAffiliatedOrgs.add(affDatabase);
        }
 dao.save(target);

It's work but 1)it looks for me somehow not elegant; 2) it may potentially create errors if this target object will be somewhere used in future... Or maybe it's a good solution and my doubts are vain?

So is there more elegant way to persist this collection without reading all it's objects from DB and not provoke errors in future.

Upvotes: 2

Views: 41

Answers (1)

SJuan76
SJuan76

Reputation: 24895

You may want to use EntityManager.getReference(). It creates an entity "proxy" object, with all of its properties lazily fetched (if needed).

Get an instance, whose state may be lazily fetched. If the requested instance does not exist in the database, the EntityNotFoundException is thrown when the instance state is first accessed. (The persistence provider runtime is permitted to throw the EntityNotFoundException when getReference is called.) The application should not expect that the instance state will be available upon detachment, unless it was accessed by the application while the entity manager was open.

Upvotes: 2

Related Questions