gpt4 book ai didi

Spring Hibernate Lazy Fetch 集合事务不起作用

转载 作者:IT老高 更新时间:2023-10-28 13:48:12 28 4
gpt4 key购买 nike

我完全糊涂了,我一直在用 hibernate 创建我的第一个 Spring 应用程序,当从我的数据库中延迟加载对象时,我似乎无法发现我的错误。

我的模型如下

团队类

@Entity
public class Team {

@Id
@Column
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
@Column
private String name;
@Column
private String description;

@OneToMany(fetch=FetchType.LAZY , cascade = CascadeType.ALL, mappedBy="team")
@JsonIgnore
public List<Person> members;

//Constructors and setters getters ommited
}

Person 类

@Entity
@Table(name="`person`")
public class Person {

@Id
@Column
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
@Column
private String name;

@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="team")
@JsonIgnore
private Team team;

//omitted constructor and methods
}

然后我的数据访问对象都遵循与此相同的模式

@Repository
public class TeamDaoImpl implements TeamDao {

@Autowired
private SessionFactory session;

@Override
public void add(Team team) {
session.getCurrentSession().save(team);
}

@Override
public void edit(Team team) {
session.getCurrentSession().update(team);
}

@Override
public void delete(int teamId) {
session.getCurrentSession().delete(getTeam(teamId));
}

@Override
public Team getTeam(int teamId) {
return (Team) session.getCurrentSession().get(Team.class, teamId);
}

@Override
public List getAllTeam() {
return session.getCurrentSession().createQuery("from Team").list();
}

}

在所有这些方法中,我确保使用当前 session 来执行这些操作。据我了解,这确保它将这些调用放入在服务类中创建的现有事务中,如下所示:

@Service
public class PersonServiceImpl implements PersonService {

Logger log = Logger.getLogger(PersonServiceImpl.class);

@Autowired
PersonDao personDao;

@Autowired
TeamDao teamDao;

//Ommitted other methods

@Transactional
public List getPeopleForTeam(int teamId) {
log.info("Getting people for team with id " + teamId);
Team team = teamDao.getTeam(teamId);
return team.getMembers();
}

}

我的理解是 @Transactional 注释应该将该方法放入单个事务中。

这一切都编译得很好,但是当我运行它时,我得到了以下错误

org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: failed to lazily initialize a collection of role: model.Team.members, no session or session was closed; nested exception is 
com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: model.Team.members, no session or session was closed
org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.writeInternal(MappingJackson2HttpMessageConverter.java:207)

org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:179)

org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:148)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:90)
org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:189)
org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:69)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:122)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)

我做错了什么?我对@Transactional 注释的理解不正确吗?如果是这样,我应该如何在对象内部延迟加载集合,同时在某些事务方法中获取它们?

编辑:

这是我的spring配置的相关部分

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseuri}" p:username="${jdbc.username}" />



<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>

<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="dataSource" ref="dataSource" />
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />

这是配置的另一部分

    <mvc:annotation-driven>
<mvc:message-converters>
<!-- Use the HibernateAware mapper instead of the default -->
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.bt.opsscreens.mappers.HibernateAwareObjectMapper" />
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>

这是 Controller 的部分

@RequestMapping(value="/{teamId}/people", method=RequestMethod.GET)
public @ResponseBody List<Person> getPeopleForTeam(@PathVariable int teamId) {
return personService.getPeopleForTeam(teamId);
}

最佳答案

您可能从 Controller 调用服务方法(例如)。会发生什么:

-controller method
-call service method
-start transaction
-hibernate do lazy loading
-end transaction
-end service method
you try to access somethind from the lazy initialied list, but no hibernate transaction here
-end controller method

延迟加载意味着 hibernate 有一个代理对象,它只存储实体的 id 并仅在需要时执行 select 语句(例如访问实体的某些属性)。您可以查看 Open session in view 但它被认为是不好的做法 Why is Hibernate Open Session in View considered a bad practice? .尝试急切地获取集合。

编辑:1)Hibernate 要求一切都在事务中执行例如

Transaction tx = null;
try{
tx = session.beginTransaction();
...
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}

2)延迟加载:Hibernate 创建代理对象(它不会向数据库触发语句)。当你尝试访问代理,向数据库发送一条语句并检索结果(这需要在 hibernate 事务中。)

3) Spring 通过以下方式简化了事务管理使用 AOP 拦截给定的方法。首先它开始一个事务,然后调用该方法并提交或回滚它。

getPeopleForTeam() 返回代理。然后在交易之外的某个地方你访问了一些属性,hibernate 尝试触发一个 select 语句。

关于Spring Hibernate Lazy Fetch 集合事务不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20599504/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com