我有一个列表,我想添加以将从列表中获取的数据添加到数据库中。
我的代码是:
List<EventPayload> mylist=eventpojo.getEventPayload();
for(EventPayload array : mylist)
{
System.out.println("Comment Text :"+array.getCommentText());
System.out.println("Comment Type :"+array.getCommentType());
System.out.println("Comment Id :"+array.getCommentId());
System.out.println("Email id :"+array.getComment_email());
String email1=array.getComment_email();
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("jcg-JPA");
EntityManager em = entityManagerFactory.createEntityManager();
List email=em.createQuery("SELECT usrinfo.user_id FROM UserInfo usrinfo WHERE usrinfo.email_id = :id").setParameter("id", email1).getResultList();
String userid=email.get(0).toString();
System.out.println("User id:"+userid);
Date date = new Date();
PageInfo pageinfo=new PageInfo();
pageinfo.setComment_id(array.getCommentId());
pageinfo.setComment_text(array.getCommentText());
pageinfo.setComment_type(array.getCommentType());
String date1=sdf.format(date);
pageinfo.setCreation_date(sdf.parse(date1));
pageinfo.setModification_date(sdf.parse(date1));
pageinfo.setRetrospective_id(eventpojo.getEventRetrospectiveId());
int user_id = Integer.parseInt(userid);
pageinfo.setUser_id(user_id);
em.persist(pageinfo);
}
我已经用POJOS映射了所有表,并且工作正常,我只想添加
CommentText
Comment type
comment Id
Email Id
Creation Date
Modification date
和RetrospectiveID
。我有一个表PAGEINFO和也是一个名为PageInfo的POJO,具有这7个字段。请帮助 最佳答案
在事务中运行持久代码。
List<EventPayload> mylist=eventpojo.getEventPayload();
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("jcg-JPA");
for(EventPayload array : mylist)
{
System.out.println("Comment Text :"+array.getCommentText());
System.out.println("Comment Type :"+array.getCommentType());
System.out.println("Comment Id :"+array.getCommentId());
System.out.println("Email id :"+array.getComment_email());
String email1=array.getComment_email();
EntityManager em = entityManagerFactory.createEntityManager();
List email=em.createQuery("SELECT usrinfo.user_id FROM UserInfo usrinfo WHERE usrinfo.email_id = :id").setParameter("id", email1).getResultList();
String userid=email.get(0).toString();
System.out.println("User id:"+userid);
Date date = new Date();
PageInfo pageinfo=new PageInfo();
pageinfo.setComment_id(array.getCommentId());
pageinfo.setComment_text(array.getCommentText());
pageinfo.setComment_type(array.getCommentType());
String date1=sdf.format(date);
pageinfo.setCreation_date(sdf.parse(date1));
pageinfo.setModification_date(sdf.parse(date1));
pageinfo.setRetrospective_id(eventpojo.getEventRetrospectiveId());
int user_id = Integer.parseInt(userid);
pageinfo.setUser_id(user_id);
EntityTransaction trans= entityManager.getTransaction();
trans.begin();
em.persist(pageinfo);
trans.commit();
em.close();
}
entityManagerFactory.close();
关于java - 如何使用Entitymanager(Hibernate)将列表中的数据插入数据库?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42105279/