There are two things I notice about the code.
First, the code should work with entities and ignore the id
fields for the particular entities. So when you fetch the account, it should grab the entity instead of the id:
//Don't do this
List<BusinessAccount> accounts=myQuery.getResultList();
int sessionContractorId=accounts.get(0).getId();
//Instead do this
List<BusinessAccount> accounts=myQuery.getResultList();
BusinessAccount account =accounts.get(0); //hopefully an account exists
Second, in JPA you are responsible for managing both sides of an association. So you must add the Account
to the Project
and on the other side of the relationship set the Project
for the Account
. I never see this occur in the code, I only see the projects
(not sure of its origin) being persisted. Assuming projects
is a List<Project>
it would look something like this:
public String addProject() {
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
String sessionEmail=Util.getEmail();
Query myQuery = em.createQuery("SELECT u FROM BusinessAccount u WHERE u.email=:email");
myQuery.setParameter("email", sessionEmail);
List<BusinessAccount> accounts=myQuery.getResultList();
BusinessAccount account =accounts.get(0);
projects.setBusinessAccount(account); //managing both sides
account.getProjects().add(projects); //managing both sides
em.persist(projects);
em.getTransaction().commit();
em.close();
return "success";
}
On a side note, you may want to change the class name to Project
and use the variable name project
since it more accurately depicts the relationship. Also since you are creating a new Project
you will need to instantiate the List<BusinessAccount>
:
List<BusinessAccount> projects = new ArrayList<BusinessAccount>();
Hopefully this will solve your issues, I would recommend watching a this video tutorial I created on Bidirectional One To Many Relationships.