spring data jpa 懒加载异常处理记录

manytomany关系中,使用 fetch = FetchType.LAZY 来做懒加载,加快些性能。一直出错,原因是session被关闭,多方查找才解决,主要是保持session,需要事务。
web.xml

<!--在页面开启session,解决懒加载异常的问题-->
    <filter>
        <filter-name>OpenEntityManagerInViewFilter</filter-name>
        <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>OpenEntityManagerInViewFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


    <!-- 字符集编码 -->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>    
        <filter-name>characterEncodingFilter</filter-name>    
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  

user.java

 @ManyToMany(cascade={CascadeType.ALL},targetEntity = com.csair.entity.Rights.class,fetch = FetchType.LAZY)
    @JoinTable(name="user_rights",
            joinColumns = {@JoinColumn(name ="user_id",referencedColumnName = "userId" )},
            inverseJoinColumns = {@JoinColumn(name = "rights_id",referencedColumnName = "rightsId")})
    private List<Rights> rights=new ArrayList<Rights>();

@JoinColumn(name =”user_id”,referencedColumnName = “userId” )},user_id是数据库字段,userId是类字段。
joinColumns是主表,inverseJoinColumns 是从表。

rights.java

@ManyToMany(mappedBy = "rights",targetEntity = com.csair.entity.User.class)
    private Set<User> users=new HashSet<User>();

mappedBy 值是user.java中的字段rights

UserServiceImpl.java

    @Override
    @Transactional
    public List<User> getUsers() {
        return repository.findAll();
    }

在获取列表的时候使用@Transactional标记为事务,就可以实现懒加载,不会出现错误:org.hibernate.LazyInitializationException: could not initialize proxy - no Session

你可能感兴趣的:(jpa,懒加载)