1、no-session
配置了懒加载,进行数据库操作时,EntityManager已经关闭
解决:在web.xml配置过滤器
<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>
当配置了过滤器,会出现第个问题
2、不能初始化代理
//方式1
@JsonIgnoreProperties(value={"hibernateLazyInitializer","handler","fieldHandler"})
//方式2
CustomMapper
public class CustomMapper extends ObjectMapper {
public CustomMapper() {
this.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// 设置 SerializationFeature.FAIL_ON_EMPTY_BEANS 为 false
this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
}
}
//applicationContext-mvc.xml配置
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json; charset=UTF-8</value>
<value>application/x-www-form-urlencoded; charset=UTF-8</value>
</list>
</property>
<!-- No serializer:配置 objectMapper 为我们自定义扩展后的 CustomMapper,解决了返回对象有关系对象的报错问题 -->
<property name="objectMapper">
<bean class="cn.itsource.aisell.common.CustomMapper"></bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
紧接着会出现第三个问题
3、修改部门失败 n to n
持久化对象的id不能做修改
解决:将关联对象设置为空
@ModelAttribute("editEmployee")
public Employee beforeUpdate(Long id,String _cmd){
if(id!=null&&"update".equals(_cmd)){
Employee employee = service.findOne(id);
employee.setDepartment(null);
return employee;
}
return null;
}