Roberto Roberto - 4 days ago 5
Java Question

Cheapest way to retrieve/record multiple entities on GAE

I have this specific case that bring me some doubts:
My class A have a one-to-many relationship with B:

A 1----->* B


Which, as far as I know, makes their related instances belong to the same entity group.
I have to retrieve one particular A instance and one of its B, so I search for A and iterate through its B List to find the particular B (always searching by Id). After that, I change one attribute of A and B and commit my changes by merging A. So here are my questions:


  1. Knowing that I must retrieve A and B (because I have to modify both), should I make 2 searches instead of iterating the B List?

  2. Making 2 searches, modifications on B will be persisted if I only persist A?

  3. Will question 1 and 2 have the same answer in this case:





A 1----->* C 1----->* B


Complementing the question with some code:

@Entity
public class A
{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Key key;

private int aField;

@OneToMany(cascade={CascadeType.ALL})
private List<B> bList;

//...
}

@Entity
public class B
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Key key;

private int someBField;

// no way to get A from here...

//...
}

public void someService1(Key aKey, Key bKey)
{
//...

// Here, I'm sure that bKey is of an entity son of aKey entity (I trust the client)
A a = entityManager.find(A.class, aKey);
a.setAField(a.getAField()++);

for(B b : a.getBList())
if(b.getKey().equals(bKey))
b.setSomeBField(b.getSomeBField()++);

entityManager.merge(a);

//...
}

public void someService2(Key aKey, Key bKey)
{
//...

// Here, I'm sure that bKey is of an entity son of aKey entity (I trust the client)
A a = entityManager.find(A.class, aKey);
a.setAField(a.getAField()++);

B b = entityManager.find(B.class, bKey);
b.setSomeBField(b.getSomeBField()++);

entityManager.merge(a);

//...
}


Well, both someService1 and someService2 do the same thing, if I did everything right. Which one is better?

Answer

If you know the id (and you say you're searching by id) then just do an em.find for the A, and em.find for the B. Two calls. Sadly the JPA API doesn't have a em.findAll. JDO, on the other hand, does have pm.getObjectsById

Comments