没有懒惰地初始化一个角色[]的集合,无法初始化代理 - 没有会话

时间:2016-02-22 20:39:05

标签: java spring hibernate spring-mvc jpa

我有一个应用程序(使用注释的Spring 4 MVC + Hibernate 4 + MySQL + Maven集成示例),使用基于注释的配置将Spring与Hibernate集成。

我有这个实体:

@Entity
@Table(name = "application")
@NamedQueries(value = { @NamedQuery(name = "Application.getByKey",
                                    query = "from Application as a where a.key = :key"),
                @NamedQuery(name = "Application.findByUsername",
                            query = "select a from Application as a left join a.users as u where u.username = :username"),
                @NamedQuery(name = "Application.findByCompanyKey",
                            query = "select a from Application as a where a.company.key = :companyKey") })
public class Application implements Serializable {

    /* */
    private static final long serialVersionUID = -2694152171872599511L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Expose
    private Long id;

    @Column(name = "`key`",
            unique = true,
            nullable = false)

    @Expose
    private String key;

    @Column(name = "description")
    @Expose
    private String description;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "type_id",
                nullable = true)
    @Expose
    private DeviceType deviceType;

    @ManyToOne
    @JoinColumn(name = "company_id",
                nullable = false)
    private Company company;

    @ManyToMany(fetch = FetchType.LAZY,
                mappedBy = "applications")
    private List<User> users;

    @OneToMany(fetch = FetchType.LAZY,
               mappedBy = "application")
    private List<ApplicationAlarm> alarms;

    @Version
    @Column(name = "version")
    private Long version = new Long(0);

    /**
     * Gets the id.
     *
     * @return the id
     */
    public Long getId() {
        return id;
    }

    /**
     * Sets the id.
     *
     * @param p_id
     *            the new id
     */
    public void setId(final Long p_id) {
        id = p_id;
    }

    /**
     * Gets the key.
     *
     * @return the key
     */
    public String getKey() {
        return key;
    }

    /**
     * Sets the key.
     *
     * @param p_key
     *            the new key
     */
    public void setKey(final String p_key) {
        key = p_key;
    }

    /**
     * Gets the description.
     *
     * @return the description
     */
    public String getDescription() {
        return description;
    }

    /**
     * Sets the description.
     *
     * @param p_description
     *            the new description
     */
    public void setDescription(final String p_description) {
        description = p_description;
    }

    /**
     * Gets the device type.
     *
     * @return the device type
     */
    public DeviceType getDeviceType() {
        return deviceType;
    }

    /**
     * Sets the device type.
     *
     * @param p_deviceType
     *            the new device type
     */
    public void setDeviceType(final DeviceType p_deviceType) {
        deviceType = p_deviceType;
    }

    /**
     * Gets the company.
     *
     * @return the company
     */
    public Company getCompany() {
        return company;
    }

    /**
     * Sets the company.
     *
     * @param p_company
     *            the new company
     */
    public void setCompany(final Company p_company) {
        company = p_company;
    }

    /**
     * Gets the users.
     *
     * @return the users
     */
    public List<User> getUsers() {
        return users;
    }

    /**
     * Sets the users.
     *
     * @param p_users
     *            the new users
     */
    public void setUsers(final List<User> p_users) {
        users = p_users;
    }

    /**
     * Gets the alarms.
     *
     * @return the alarms
     */
    public List<ApplicationAlarm> getAlarms() {
        return alarms;
    }

    /**
     * Sets the alarms.
     *
     * @param p_alarms
     *            the new alarms
     */
    public void setAlarms(final List<ApplicationAlarm> p_alarms) {
        alarms = p_alarms;
    }

    /**
     * Gets the version.
     *
     * @return the version
     */
    public Long getVersion() {
        return version;
    }

    /**
     * Sets the version.
     *
     * @param p_version
     *            the new version
     */
    public void setVersion(final Long p_version) {
        version = p_version;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(final Object p_obj) {
        boolean isEquals = false;

        try {
            final Application application = (Application) p_obj;
            final EqualsBuilder eb = new EqualsBuilder();

            eb.append(getKey(), application.getKey());

            isEquals = eb.isEquals();
        } catch (final Exception e) {
            isEquals = false;
        }

        return isEquals;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        final HashCodeBuilder hcb = new HashCodeBuilder();
        hcb.append(getKey());

        return hcb.toHashCode();
    }

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        ToStringBuilder tsb = new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE);

        tsb.append("id", getId());
        tsb.append("key", getKey());
        tsb.append("description", getDescription());
        tsb.append("deviceType", getDeviceType());
        tsb.append("version", getVersion());

        return tsb.toString();
    }

}

和此:

@Entity
@Table(name = "user",
       uniqueConstraints = { @UniqueConstraint(columnNames = "username") })
@NamedQueries(value = { @NamedQuery(name = "User.findByUsername",
                                    query = "from User u where u.username = :username") })
@NamedEntityGraph(name = "graph.User.company",
                  attributeNodes = @NamedAttributeNode("company") )
public class User implements Serializable {

    /* */
    private static final long serialVersionUID = 3660379416292251393L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "username",
            nullable = false,
            unique = true,
            length = 50)
    private String username;

    @Column(name = "password",
            nullable = false,
            length = 50)
    private String password;

    @Column(name = "enabled",
            nullable = false)
    private boolean enabled = true;

    @ManyToMany(fetch = FetchType.EAGER,
                cascade = CascadeType.ALL)
    @JoinTable(name = "user_authority",
               joinColumns = { @JoinColumn(name = "user_id",
                                           nullable = false,
                                           updatable = false) },
               inverseJoinColumns = { @JoinColumn(name = "authority_id",
                                                  nullable = false,
                                                  updatable = false) })
    private List<Authority> authorities;

    @ManyToOne
    @JoinColumn(name = "company_id",
                nullable = false)
    private Company company;

    @ManyToMany(fetch = FetchType.LAZY,
                cascade = CascadeType.ALL)
    @JoinTable(name = "user_application",
               joinColumns = { @JoinColumn(name = "user_id",
                                           nullable = false,
                                           updatable = false) },
               inverseJoinColumns = { @JoinColumn(name = "application_id",
                                                  nullable = false,
                                                  updatable = false) })
    private List<Application> applications;

    @Version
    @Column(name = "version")
    private Long version = new Long(0);

    /**
     * Gets the id.
     *
     * @return the id
     */
    public Long getId() {
        return id;
    }

    /**
     * Sets the id.
     *
     * @param p_id
     *            the new id
     */
    public void setId(final Long p_id) {
        id = p_id;
    }

    /**
     * Gets the user name.
     *
     * @return the user name
     */
    public String getUsername() {
        return username;
    }

    /**
     * Sets the user name.
     *
     * @param p_username
     *            the new user name
     */
    public void setUsername(final String p_username) {
        username = p_username;
    }

    /**
     * Gets the password.
     *
     * @return the password
     */
    public String getPassword() {
        return password;
    }

    /**
     * Sets the password.
     *
     * @param p_password
     *            the new password
     */
    public void setPassword(final String p_password) {
        password = p_password;
    }

    /**
     * Checks if is enabled.
     *
     * @return true, if is enabled
     */
    public boolean isEnabled() {
        return enabled;
    }

    /**
     * Sets the enabled.
     *
     * @param p_enabled
     *            the new enabled
     */
    public void setEnabled(final boolean p_enabled) {
        enabled = p_enabled;
    }

    /**
     * Gets the authorities.
     *
     * @return the authorities
     */
    public List<Authority> getAuthorities() {
        return authorities;
    }

    /**
     * Sets the authorities.
     *
     * @param p_authorities
     *            the new authorities
     */
    public void setAuthorities(final List<Authority> p_authorities) {
        authorities = p_authorities;
    }

    /**
     * Gets the company.
     *
     * @return the company
     */
    public Company getCompany() {
        return company;
    }

    /**
     * Sets the company.
     *
     * @param p_company
     *            the new company
     */
    public void setCompany(final Company p_company) {
        company = p_company;
    }

    /**
     * Gets the applications.
     *
     * @return the applications
     */
    public List<Application> getApplications() {
        return applications;
    }

    /**
     * Sets the applications.
     *
     * @param p_applications
     *            the new applications
     */
    public void setApplications(final List<Application> p_applications) {
        applications = p_applications;
    }

    /**
     * Gets the version.
     *
     * @return the version
     */
    public Long getVersion() {
        return version;
    }

    /**
     * Sets the version.
     *
     * @param p_version
     *            the new version
     */
    public void setVersion(final Long p_version) {
        version = p_version;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(final Object p_obj) {
        boolean isEquals = false;

        try {
            final User user = (User) p_obj;
            final EqualsBuilder eb = new EqualsBuilder();

            eb.append(getUsername(), user.getUsername());

            isEquals = eb.isEquals();
        } catch (final Exception e) {
            isEquals = false;
        }

        return isEquals;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        final HashCodeBuilder hcb = new HashCodeBuilder();

        hcb.append(getUsername());

        return hcb.toHashCode();
    }

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        final ToStringBuilder tsb = new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE);

        tsb.append("id", getId());
        tsb.append("username", getUsername());
        tsb.append("password", getPassword());
        tsb.append("enabled", isEnabled());
        tsb.append("authorities", getAuthorities());
        tsb.append("version", getVersion());

        return tsb.toString();
    }

}

和服务中的这个方法:

@Override
    @Transactional(propagation = Propagation.REQUIRED,
                       readOnly = true)
    public List<Application> getApplications(User user) {
        User us = getUserDao().findByUsernameWithCompany(user.getUsername());
        Hibernate.initialize(us.getApplications());
        return user.getApplications();
    }

在控制器中:

List<Application> applications = userAccessorService.getApplications(getLoggedUser(request));

但是我收到了这个错误:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.tdk.toc.model.User.applications, could not initialize proxy - no Session
    org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:567)
    org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:205)
    org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:546)
    org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:133)
    org.hibernate.collection.internal.PersistentBag.toString(PersistentBag.java:509)
    java.lang.String.valueOf(String.java:2847)
    java.lang.StringBuilder.append(StringBuilder.java:128)
    com.tdk.toc.controller.ApplicationController.listApplications(ApplicationController.java:62)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:606)
    org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
    org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:860)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.springframework.web.multipart.support.MultipartFilter.doFilterInternal(MultipartFilter.java:118)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:316)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:122)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:48)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    org.springframework.security.web.session.ConcurrentSessionFilter.doFilter(ConcurrentSessionFilter.java:133)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:205)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:120)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:96)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:91)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:53)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    org.springframework.security.web.access.channel.ChannelProcessingFilter.doFilter(ChannelProcessingFilter.java:152)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213)
    org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176)
    org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)

1 个答案:

答案 0 :(得分:0)

添加OpenSessionInfViewFilter

  • org.springframework.orm.hibernate3.support.OpenSessionInViewFilter,或
  • org.springframework.orm.hibernate4.support.OpenSessionInViewFilter

的web.xml:

<filter>
    <filter-name>OpenSess ionInViewFilter</filter-name>
    <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>OpenSess ionInViewFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
使用OpenSessionInView过滤器的

有时被称为不良做法,但您必须自己决定