我想在JAVA中使用FOR循环之外的变量

时间:2017-02-07 09:51:27

标签: java

我有一个String,我想在查询中用作参数。我的代码如下:

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();

            String email=em.createQuery("SELECT user_id FROM UserInfo WHERE email_id = "+email1).toString();

我想在查询循环外使用String email1。如何实现这个?

2 个答案:

答案 0 :(得分:0)

email1 位于forloop内部,因此范围缩小到该细分受众群......

声明外部,也将变量的范围设置为可在外部访问...

List<EventPayload> mylist=eventpojo.getEventPayload();
String email1=null;  //HERE!!
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());
    email1=array.getComment_email();
}

EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("jcg-JPA");
EntityManager em = entityManagerFactory.createEntityManager();

String email=em.createQuery("SELECT user_id FROM UserInfo WHERE email_id = "+email1).toString();

答案 1 :(得分:-1)

简短回答:你不能

长答案/进一步的问题: 你想做什么?

为每个EventPayload触发一个SQL - &gt;然后在循环中执行此操作

为一个不同的EventPayload触发SQL - &gt;在列表中查找对象(或过滤列表)并执行该对象的查询