[英]How to check whether list inside list is empty in hibernate response
我在我的應用程序中使用 @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 從訂閱表中獲取數據。 這是我的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 列表中的訂閱列表是否為空,因為如果列表為空,那么我想為我的訂閱變量設置另一個值。 請建議我如何做到這一點。
提前致謝。
要檢查訂閱列表是否為空,請使用以下代碼:
for(TopArtists artist : topArtists) {
if(artist.getSubs.isEmpty()) {
//List is empty.
} else {
//List is not empty.
}
}
您還可以使用 for 循環而不是 for each 循環:
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");
}
}
}
您可以使用迭代器迭代List<TopUsers>
並檢查每個List<Subscribe>
的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");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.