I'm trying to develop an application using Google Guice, JPA (EclipseLink) and AngularJS. Basically in this application I have some Employees and more than one Salary for each of them.
public class Employee implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="ID_EMPLOYEE")
private long idEmployee;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "employee",targetEntity = Salary.class,fetch = FetchType.EAGER)
private List<Salary> salaries;
and the Salary object:
public class Salary implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="ID_SALARY")
private long idSalary;
@Column(name="SALARY_PA")
private String salaryPa;
@ManyToOne
@JoinColumn(name="ID_EMPLOYEE", referencedColumnName = "ID_EMPLOYEE")
private Employee employee;
Now, I'm able to insert, using angularJS and REST services, a new employee without any problem. What I can't do is adding a new salary to an existing employee. Basically what I have in my angularJS controller is:
$scope.employee.salaries.push(this.salaryToAdd);
employeeServ.persistSalary(employee);
and then I just save the employee. The salary is saved but when I try to get the Employee sometimes I can see the salary sometime not. What I noticed is that the salary doesn't have any reference to the Employee so maybe when I get the employee JPA doesn't know if the salary is related to that Employee.
This is my dao and the part related to the persistence:
public abstract class GenericDao<E> implements AbstractDao<E> {
@Inject
private EntityManager em;
protected abstract Class<E> getGenericClass();
@Transactional
@Override
public void insert(E entity) {
em.persist(entity);
}
@Transactional
@Override
public void update(E entity) {
em.merge(entity);
}
@Transactional
@Override
public void delete(E entity) {
em.remove(entity);
}
public E findById(Long id) {
Class<E> clazz = getGenericClass();
return em.find(clazz, id);
}
public List<E> findAll() {
Class<E> clazz = getGenericClass();
CriteriaQuery<E> query = em.getCriteriaBuilder().createQuery(clazz);
Root<E> root = query.from(clazz);
query.select(root);
return em.createQuery(query).getResultList();
}
public EntityManager getEntityManager() {
return em;
}
@Path("/employee")
public class EmployeeProvider {
@Inject
EmployeeDao dao;
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/get/{id}")
public String get(@PathParam("id") String id) {
final Gson gson = new GsonBuilder().setPrettyPrinting().create();
if("all".equals(id)) {
return gson.toJson(dao.findAll().toArray());
} else {
return gson.toJson(dao.findById(Long.valueOf(id)));
}
}
@POST
@Path("/post")
public void post(String employee) {
final Gson gson = new GsonBuilder().setPrettyPrinting().create();
Employee entity = gson.fromJson(employee, Employee.class);
dao.update(entity);
}