"FROM Gadget g " + "WHERE g.template.id =:sourceTabTemplateId "
+ "AND g.zoneNumber =:sourceZoneNumber AND g.deleted = false ORDER BY g.zoneIndex")
.setParameter("sourceTabTemplateId", sourceTabTemplateId).setParameter("sourceZoneNumber",
sourceZoneNumber).getResultList();
Gadget movingGadget = null;
for (int i = 0; i < sourceGadgets.size(); i++)
{
if (sourceGadgets.get(i).getId() == gadgetId)
{
movingGadget = sourceGadgets.get(i);
sourceGadgets.remove(i);
}
}
// Target
List<Gadget> targetGadgets = (List<Gadget>) entityManager.createQuery(
"FROM Gadget g " + "WHERE g.template.id =:targetTabTemplateId "
+ "AND g.zoneNumber =:targetZoneNumber AND g.deleted = false ORDER BY g.zoneIndex")
.setParameter("targetTabTemplateId", targetTabTemplateId).setParameter("targetZoneNumber",
targetZoneNumber).getResultList();
// Remove from target as well
for (int i = 0; i < targetGadgets.size(); i++)
{
if (targetGadgets.get(i).getId() == gadgetId)
{
targetGadgets.remove(i);
}
}
if (targetZoneIndex < targetGadgets.size())
{
targetGadgets.add(targetZoneIndex, movingGadget);
}
else
{
targetGadgets.add(movingGadget);
}
// Renumber Source gadgets
for (int i = 0; i < sourceGadgets.size(); i++)
{
Gadget g = sourceGadgets.get(i);
entityManager.createQuery(
"UPDATE versioned Gadget g SET g.zoneIndex = :newZoneIndex WHERE g.id = :gadgetId").setParameter(
"newZoneIndex", i).setParameter("gadgetId", g.getId()).executeUpdate();
}
// Renumber target gadgets
for (int i = 0; i < targetGadgets.size(); i++)
{
Gadget g = targetGadgets.get(i);
entityManager.createQuery(
"UPDATE versioned Gadget g SET g.zoneIndex = :newZoneIndex, "
+ "g.template.id =:targetTabTemplateId, g.zoneNumber =:targetZoneNumber "
+ "WHERE g.id = :gadgetId").setParameter("newZoneIndex", i).setParameter("gadgetId",
g.getId()).setParameter("targetTabTemplateId", targetTabTemplateId).setParameter(
"targetZoneNumber", targetZoneNumber).executeUpdate();
}
}