Java 如何解决lazyinitializationexception不使用fetch=FetchType.EAGER的问题?

Java 如何解决lazyinitializationexception不使用fetch=FetchType.EAGER的问题?,java,hibernate,jpa,spring-mvc,lazy-loading,Java,Hibernate,Jpa,Spring Mvc,Lazy Loading,我仍然收到lazyinitializationexception异常。 是的,我知道这意味着,当我或其他人试图访问集合时,会话已关闭。 否,OpenEntityManager视图筛选器不工作。 是的,@ManyToOne(fetch=FetchType.EAGER)有帮助,但我不想使用它,因为它会一直生育 我还能怎么做呢 注:我正在使用HibernateTityManger和jpa以及带注释的类 UPADATE 首先,这是我的代码 我有4张桌子: 用户(id、名字、姓氏、电子邮件……) 角色(i

我仍然收到lazyinitializationexception异常。 是的,我知道这意味着,当我或其他人试图访问集合时,会话已关闭。 否,OpenEntityManager视图筛选器不工作。 是的,@ManyToOne(fetch=FetchType.EAGER)有帮助,但我不想使用它,因为它会一直生育

我还能怎么做呢

注:我正在使用HibernateTityManger和jpa以及带注释的类

UPADATE 首先,这是我的代码 我有4张桌子: 用户(id、名字、姓氏、电子邮件……) 角色(id、名称、注释……) 用户角色(用户id、角色id) 邮件(id、用户id、主题、消息、收件人id…)

一个用户可以有多个角色。。。。 用户实体

@Entity
@Table(name = "USERS")
public class User implements GenericDomain{

    public static final String  _ID = "id";
private Long    id;
private String  firstName;
private String  lastName;
private String  email;  
private Set<Role> roles = new HashSet<Role>(0);

/* Constructors */  
public User() {
}

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "ID", unique = true, nullable = false)
public Long getId() { return this.id; }
public void setId(Long id) { this.id = id; }

@Column(name="FIRST_NAME", nullable = false, length = 64)
@NotEmpty
@Length(min = 4, max = 45)
public String getFirstName() { return this.firstName;   }
public void setFirstName(String firstname) { this.firstName = firstname; }

@Column(name="LAST_NAME", nullable = false, length = 64)
@NotEmpty
@Length(min = 4, max = 45)
public String getLastName() { return this.lastName; }
public void setLastName(String lastname) { this.lastName = lastname; }

@Column(name="EMAIL", unique = false, length = 64)
@Email
@NotEmpty
@Length(min = 4, max = 45)
public String getEmail() { return this.email; }
public void setEmail(String email) { this.email = email; }

@ManyToMany(fetch=FetchType.EAGER)
@JoinTable(name = "USERS_ROLES"
    , joinColumns = { @JoinColumn(name = "user_id") }
    , inverseJoinColumns = { @JoinColumn(name = "role_id") }
)
public Set<Role> getRoles() {
    return this.roles;
}
public void setRoles(Set<Role> roles) {
    this.roles = roles;
}

/*@Override toString/equals/hascode  */
用户控制器

@Controller
@RequestMapping("/admin/user")
@SessionAttributes("user")
public class UserController {

private UserService userService;
private RoleService roleService;

@Autowired
public UserController(UserService userService, RoleService roleService) {
    this.userService = userService;
    this.roleService = roleService;
}
@RequestMapping(value = "edit", method = RequestMethod.GET)
public String editUser(@RequestParam(value="id", required = true) Long id, ModelMap model) {

    model.addAttribute("allRoles", roleService.getAll());
    model.addAttribute("user", userService.getOne(id));
    return "/admin/user/edit";
}    }
@Controller
@SessionAttributes("mail")
@RequestMapping("/portal/mail")
public class MailController{

@Autowired
private MailService mailService;

@RequestMapping(value = "ajaxLoad", method = RequestMethod.GET)
public @ResponseBody List<Mail> list(@RequestParam(value = "type", required = true) String type){
    return mailService.getUserMails((Long) WebHelper.getPrincipal().getUser().getId(),type);
}   
邮件控制器

@Controller
@RequestMapping("/admin/user")
@SessionAttributes("user")
public class UserController {

private UserService userService;
private RoleService roleService;

@Autowired
public UserController(UserService userService, RoleService roleService) {
    this.userService = userService;
    this.roleService = roleService;
}
@RequestMapping(value = "edit", method = RequestMethod.GET)
public String editUser(@RequestParam(value="id", required = true) Long id, ModelMap model) {

    model.addAttribute("allRoles", roleService.getAll());
    model.addAttribute("user", userService.getOne(id));
    return "/admin/user/edit";
}    }
@Controller
@SessionAttributes("mail")
@RequestMapping("/portal/mail")
public class MailController{

@Autowired
private MailService mailService;

@RequestMapping(value = "ajaxLoad", method = RequestMethod.GET)
public @ResponseBody List<Mail> list(@RequestParam(value = "type", required = true) String type){
    return mailService.getUserMails((Long) WebHelper.getPrincipal().getUser().getId(),type);
}   
@控制器
@会期致辞(“邮件”)
@请求映射(“/portal/mail”)
公共类邮件控制器{
@自动连线
私人邮件服务;
@RequestMapping(value=“ajaxLoad”,method=RequestMethod.GET)
public@ResponseBody列表(@RequestParam(value=“type”,required=true)字符串类型){
返回mailService.getUserMails((长)WebHelper.getPrincipal().getUser().getId(),类型);
}   
}

my web.xml

<filter>
    <filter-name>SpringOpenEntityManagerInViewFilter</filter-name>
    <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>SpringOpenEntityManagerInViewFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>   

SpringOpenEntityManager视图过滤器
org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter
SpringOpenEntityManager视图过滤器
/*
用于用户的my edit.jsp

<select >
<c:forEach items="${allRoles}" var="role">
    <option value="${role.id}" <c:if test="${fn:contains(roleSelected, role)}">selected="selected"</c:if> >${role.name}</option>
</c:forEach>
</select>

${role.name}
有了这些,我edit.jsp for user在lazy=false的情况下运行良好。
有了FetchType.EAGER,我无法收到任何邮件,我进入了一个stackovrflow循环,没有FetchType.EAGER,我遇到了懒惰的异常。

OpenEntityManagerViewFilter
OpenEntityManagerViewInterceptor
工作。你做错了什么

除此之外,您还可以使用
Hibernate.initialize(..)
初始化集合。但手动操作并不可取。请详细说明过滤器/拦截器不工作的原因


更新:不要将过滤器映射到模式,而是将其映射到dispatcher servlet。因此,首先,不要指定
规格

,而是检查您是否确实需要
收集
,而不是
设置
。如果集合中的对象是唯一的,则将变量声明为
Set
,这解决了90%的问题,其中
LazyInitializationException

删除所有的属性并添加此属性可以解决我的问题

    <mvc:interceptors>
    <bean class="org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor">  
        <property name="entityManagerFactory" ref="entityManagerFactory" />  
    </bean>
</mvc:interceptors>


过滤器不起作用

您好,您已经更新了我的帖子并添加了一些代码,正如您所看到的,我不使用collection,我使用Set,但惰性异常仍然存在