如何在hibernate响应中检查列表内的列表是否为空

时间:2015-07-29 11:17:27

标签: java hibernate

我在我的应用程序中使用@oneToMany注释来从另一个表中获取数据。有两个实体类TopArtists.java和Subscribe.java。这是 TopArtists.java

@Id
@GeneratedValue
@Column(name="id")
private long id;

@Column(name="full_name")
private String fullName;

@Column(name="username")
private String uname;


@OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name="subscriber_id")
private List<Subscribe> subs;  

//Getters and setters

这是 Subscribe.java

@Id
@GeneratedValue
@Column(name="id")
private long id;
//private String status;

@Column(name="subscribed_id")
private String subID;

@Column(name="subscriber_id")
private long subrID;

//Gettes and setters

这里我基于subscribed_id从subscribe表中获取数据。这是我的 DAO

    @SuppressWarnings({ "unchecked", "rawtypes" })
public List<TopUsers> getTopArtists() throws Exception {
    session = sessionFactory.openSession();
        Criteria cr = session.createCriteria(TopUsers.class);
        cr.addOrder(Order.asc("rank"));
        List topArtists = cr.list();
        tx = session.getTransaction();
        session.beginTransaction();
        tx.commit();
        return topArtists;
    }

这里的结果将进入List topArtists。现在我想检查一下订阅表是否有与subscribed_id相对应的数据,所以我想检查topArtist列表中的订阅列表是否为空,因为如果列表为空,那么我想为我的订阅变量设置另一个值。请建议我怎么做。

提前致谢。

2 个答案:

答案 0 :(得分:1)

要检查订阅列表是否为空,请使用以下代码:

for(TopArtists artist : topArtists) {
    if(artist.getSubs.isEmpty()) {
        //List is empty.
    } else {
        //List is not empty.  
    }
}

你也可以使用for循环代替每个循环:

for(int i = 0; i < topArtists.size(); i++) {
    if(topArtists.get(i).getSubs.isEmpty()) {
        //List is empty.
    } else {
        //List is not empty.  
    }
}

假设订阅列表不为空,那么我们可以访问或修改值:

    for(int i = 0; i < topArtists.size(); i++) {
        if(topArtists.get(i).getSubs.isEmpty()) {
            //List is empty.
        } else {
            //To fetch the List of Subscribe
            List<Subscribe> subList = topArtists.get(i).getSubs();

            //Iteration on Subscribe List
            for(int j = 0; j < subList.size(); j++) {
                //Changing the value of subID
                subList.get(j).setSubID("Any String");
            }
        }
    }

答案 1 :(得分:1)

您可以使用 iterator 来迭代List<TopUsers>并检查每个List<Subscribe>的列表,这是您需要的代码:

List<TopUsers> usersList = getTopArtists();

Iterator<TopUsers> iter = usersList.iterator();
while(iter.hasNext()){
    //Getb the iterated element
    TopUsers user = (TopUsers) iter.next();

    //Check for the subs 
    //use the getSubs() getter to get the list of subs
    if(user.getSubs().isEmpty()) {
      System.out.println("No subs found");
    }
}