Hej Guys,这是我的问题。我有一段Java代码,我不知道 NullPointerException的原因是什么?我认为它是由不正确的对象映射引起的 但是我还没有找到解决办法。
ArrayList<Auction> auctionList = auctionDAO.findAll(); /* Works correctly */
for(Auction auction : auctionList) {
System.out.println(auction.getOwner().getEmail()); /* NullPointerException */
}
/* -------------- ENTITIES --------------- */
@Entity
@Table(name="USERS")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
(other properties)
private String email;
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="owner")
@JoinTable(
name="OWNER_AUCTION",
joinColumns = @JoinColumn(name="OWNER_ID"),
inverseJoinColumns = @JoinColumn(name="AUCTION_ID")
)
private Set<Auction> ownedAuctionList = new HashSet<Auction>();
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
(getters & setters)
}
@Entity
@Table(name="AUCTIONS")
public class Auction implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
(other properties)
@ManyToOne(fetch=FetchType.EAGER)
private User owner;
(other properties & getters & setters)
}
答案 0 :(得分:0)
没有你的桌子,很难说。但我想为了调试目的你应该做那样的事情:
for(Auction auction : auctionList) {
if(auction.getOwner()==null){
System.out.println("Null Owner");
}
else if(auction.getOwner().getEmail()==null){
System.out.println("Null mail");
}
else
System.out.println(auction.getOwner().getEmail());
}
这可以帮助您找到问题