开发者

Hibernate returns null unitilzed Collection

I have two tables, users and images which need to be joined. there is exactly one user row in the users table to many images in the images table.

In my users bean I have a private Set variable with a @OneToMany relationship it looks like this

//Users.java
@Entity
@Table(name = "users")
@NamedQueries ({
@NamedQuery(name = "Users.getUserImage",
query("from Users as users INNER JOIN fetch users.images as image WHERE users.userId image.userId AND users.userId =: passedId")
})
public class Users
   private Set<UserImages> images;

   @OneToMany(mappedBy = "userId", fetch = FetchType.LAZY, casc开发者_运维技巧ade=CascadeType.ALL)
   public Set<UserImages> getImages() {
        return images;
   }

   public void setImages(Set<UserImages> images) {
        this.images = images;
  }
}

Then I have a UserImages bean which stores a bunch of data but has the fk userId which looks like so.

//UserImages.java

private Integer userId;

@Column(name = "user_id", updatable=true, nullable=false)
public Integer getUserId() {
    return userId;
}

public setUserId(Integer userId) {
    this.userId = userId;
}

I am calling the getUserImage namedQuery from within my DAO to get the resultSet.

So this works well except for when a user has NO images in the UserImages table. (User has not uploaded any images yet). I have set up a test to test everything and if a user has an image it works great I can call the getImages() method on a User and it will return a set and I can iterate through that. But if the User does not have any images it gives me a null pointer exception right away.

I have tried to set the Set to null in the setUserImages() method if variable this.images = null but that does not seem to work. Any help would be great. Thanks!


That's not the way you do things in Hibernate. The whole point of using an ORM is that you don't have to deal with foreign keys, but with object references:

@Entity
public class UserImage{

    @ManyToOne
    private User user;

    public User getUser(){return user;}
    public setUser(User user){this.user = user;}

}

@Entity
public class User{

    @OneToMany(mappedBy="user")
    private Set<UserImage> images;

    public void setImages(Set<UserImage> images){this.images=images;}
    public Set<UserImage> getImages(){return this.images;}

}

About queries: don't use join. Use something like this (I only use JPA, so I'm not sure about HQL):

Select i from UserImage i where user = :user and filename like :pattern

Pass the user object and the pattern as parameter and let hibernate do the join internally. There's no use in using an ORM, if you're going to do the leg work yourself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜