【发布时间】:2017-08-18 12:26:25
【问题描述】:
我正在使用 spring MVC + hibernate + jackson。 春季版本:4.3.x 休眠版本:4.3.x 我想创建两个 API——一个也获取 BeanB 对象,一个不获取 BeanB 对象。我也在使用 fetchtype.lazy。
我有以下豆子:
@Entity
class BeanA
{
@Id
int id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "BeanB_id")
private BeanB beanB;
//getters and setters
}
@Entity
class BeanB
{
@Id
int i;
//getters and setters
}
在我的控制器中,我有两种方法:(删除服务层以使问题变小。在我的服务层类中,我有@Transactional)
@RequestMapping(value = "/beanA/{id}" , method=RequestMethod.GET)
public ResponseEntity<BeanA> findDetailedBeanAById(@PathVariable("id") int id )
{
// to return beanA object with beanB
BeanA beanA = beanADao.findDetailedBeanAById(id);
return new ResponseEntity<BeanA>(beanA, HttpStatus.OK);
}
@RequestMapping(value = "/beanA/{id}" , method=RequestMethod.GET)
public ResponseEntity<BeanA> findNonDetailedBeanAById(@PathVariable("id") int id )
{
// to return beanA object without beanB
BeanA beanA = beanADao.findNonDetailedBeanAById(id);
return new ResponseEntity<BeanA>(beanA, HttpStatus.OK);
}
在我的道
public BeanA findDetailedBeanAById(long id) {
BeanA beanA = (BeanA) getSession().get(BeanA.class, id);
Hibernate.initialize(beanA.getBeanB())
return beanA;
}
public BeanA findNonDetailedBeanAById(long id) {
BeanA beanA = (BeanA) getSession().get(BeanA.class, id);
return beanA;
}
当我点击 findNonDetailedBeanAById 控制器方法时,我收到错误:
org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: could not initialize proxy - no Session
当我点击 findNonDetailedBeanAById 控制器方法时,出现以下错误:
org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)`
需要做哪些改变?
【问题讨论】: