我将数据从JSF中的select多个框传递到mySQL数据库。当我运行调试器并通过循环遵循代码时,代码按预期执行。但是,只有for循环的最后一次迭代中的数据实际上才会传递给数据库。如果有人能解释为什么会发生这种情况,那将非常感激!
public String addLocation(ArrayList<String> countyList) {
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);
Query myQuery2=em.createQuery("SELECT c FROM County c WHERE c.id=:id");
for (int i=0; i<countyList.size(); i++){
String nextCounty=countyList.get(i);
myQuery2.setParameter("id", Integer.parseInt(nextCounty));
List<County> myCounties=myQuery2.getResultList();
String countyFromList=myCounties.get(0).getName();
locations.setBusinessAccount(account);
locations.setCountyName(countyFromList);
account.getLocations().add(locations);
}
em.persist(locations);
em.getTransaction().commit();
em.close();
return "success";
}
答案 0 :(得分:0)
注意你的界限:
locations.setBusinessAccount(account);
locations.setCountyName(countyFromList);
}
account.getLocations().add(locations);
em.persist(locations);
修改强>
根据我的评论:移动你的
Query myQuery2=em.createQuery("SELECT c FROM County c WHERE c.id=:id");
就在之前的声明
for
循环
(后
BusinessAccount account =accounts.get(0);
语句)
再次思考最后4行代码的作用 这里发生了什么?
locations.setBusinessAccount(account);
locations.setCountyName(countyFromList);
locations
实际上是一个误导性的名称。
在这里?
account.getLocations().add(locations);
最后你的上一个陈述是做什么的?
em.persist(locations);