简体   繁体   中英

Hibernate with JPA annotation problem - lazy object

I have a USER table associated with many other tables, in general, star topology.

Like this:

@Entity
@Table(name = "user")
public class User implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @SequenceGenerator(name = "user_USERID_GENERATOR", sequenceName = "user_SEQ")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "userR_USERID_GENERATOR")
    @Column(name = "user_id")
    private long userId;

    @Basic
    @Column(name = "password_hex")
    private String password;

    @Basic
    @Column(name = "language")
    private String language;

    @Temporal(TemporalType.DATE)
    private Date created;

    @Temporal(TemporalType.DATE)
    private Date modyfied;

    @Basic
    @Column(name = "first_name")
    private String firstName;

    @Basic
    @Column(name = "last_name")
    private String lastName;

    @Basic
    @Column(name = "passport")
    private String passport;

    @Basic
    @Column(name = "pesel")
    private String pesel;

    @Basic
    @Column(name = "phone_nr1")
    private String phoneNr1;

    @Basic
    @Column(name = "phone_nr2")
    private String phoneNr2;

    @Column(name = "hash")
    private String hash;


    // uni-directional many-to-one association to DictUserType
    @ManyToOne
    @JoinColumn(name = "status")
    private DictUserStatus status;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "user", cascade = { CascadeType.ALL })
    private Set<Email> emails = new HashSet<Email>(0);

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "user", cascade = { CascadeType.ALL })
    private Set<Address> address = new HashSet<Address>(0);

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "user", cascade = { CascadeType.ALL })
    private Set<ArchivePasswords> archivePasswords = new HashSet<ArchivePasswords>(
            0);

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "user", cascade = { CascadeType.ALL })
    private Set<HostsWhitelist> hostsWhitelist = new HashSet<HostsWhitelist>(0);

.... I have a DAO layer, the method of search by user ID.

public User findUser(long userId) throws UserNotFoundException {
    User user = userDao.findUser(userId);
    if (user == null) {
        throw new UserNotFoundException("Could not find user with id = "
                + userId);
    }

    return user;
}

Why lazy fetching does not work?

If not specified, lazy fet hing will not take place defaults to EAGER.

public @interface Basic The simplest type of mapping to a database column. The Basic annotation can be applied to a persistent property or instance variable of any of the following types: Java primitive types, wrappers of the primitive types, String, java.math.BigInteger, java.math.BigDecimal, java.util.Date, java.util.Calendar, java.sql.Date, java.sql.Time, java.sql.Timestamp, byte[], Byte[], char[], Character[], enums, and any other type that implements java.io.Serializable.

The use of the Basic annotation is optional for persistent fields and properties of these types. If the Basic annotation is not specified for such a field or property, the default values of the Basic annotation will apply.

  Example 1:

    @Basic
    protected String name;

    Example 2:

    @Basic(fetch=LAZY)
    protected String getName() { return name; }

fetch

public abstract FetchType fetch

(Optional) Defines whether the value of the field or property should be lazily loaded or must be eagerly fetched. The EAGER strategy is a requirement on the persistence provider runtime that the value must be eagerly fetched. The LAZY strategy is a hint to the persistence provider runtime. If not specified, defaults to EAGER.

Default:
javax.persistence.FetchType.EAGER
optional

public abstract boolean optional

(Optional) Defines whether the value of the field or property may be null. This is a hint and is disregarded for primitive types; it may be used in schema generation. If not specified, defaults to true. Default: true

You should post the stack trace you are receiving. Where is the LazyLoadingException occurring? On the user Object? Are you trying to access it from another Object?

Is this the notorious LazyInitializationException? If so, then you need to either traverse the Object graph manually in the service (assuming you DAO code snippet is actually a Service method and not the DAO itself), or research the OpenSessionInViewFilter (assuming you are using Spring).

If you want to fetch the user with emails.

    @Transactional
    public List getUserWithEmails(long userId){
        User user = userDao.findUser(userId);
        if (user == null) {
            throw new UserNotFoundException("Could not find user with id = "
                    + userId);
        }
        for(Email email:user.getEmails()){
            email.getId();
        }
        return user;
    }

The same procedure apply to other one-to-many sets. Just like others have stated, you need to add OpenSessionInView (Hibernate) filter or OpenEntityManagerInView (JPA)filter in web.xml

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM