我正在尝试获得与会者的大小(列表,这是班级演示文稿中的oneToMany)
规划包含具有相应演示文稿的OneToMany
每当我尝试获得与会者的大小时,它都无法延迟加载它们。我尝试编写一个查询,但它说我不能使用两次获取。有没有什么好方法可以获得我需要的数据?
互联网上有很多关于此事的讨论,但似乎没有一个能解决我的问题。
我正在使用最新版本的hibernate(4.1.7.Final)并使用Spring版本3.2.3
规划回购:
public interface PlanningRepository extends JpaRepository<Planning, Long>{
@Query("select pl from Planning pl join fetch pl.presentations p join fetch p.attendees a where pl.id = ?1")
Planning findOneById(Long id);
}
班级表达中的关系:
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "presentation_attendees",
joinColumns = {@JoinColumn(name = "presentation_id")},
inverseJoinColumns = {@JoinColumn(name = "student_id")})
private List<Student> attendees;
学生的关系:
@ManyToMany(mappedBy = "attendees")
private List<Presentation> presentationsAttending;
我在PlanningController中调用它:
Planning planning = planningRepository.findOneById(1L);
JSONArray pArray = new JSONArray();
JSONObject planningJSON = new JSONObject();
//List<Presentation> presentations = (List<Presentation>)presentationRepository.findByPlanning(planning.getId());
for(Presentation p : planning.getPresentations())
{
sessionFactory.openSession();
sessionFactory.getCurrentSession().getTransaction().begin();
//i need the size of attendees
presentationJSON.put("subscribers", p.getAttendees().size());
sessionFactory.getCurrentSession().getTransaction().commit();
sessionFactory.close();
}
调度-servlet.xml中:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="school"/>
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
答案 0 :(得分:1)
您需要将Repository调用封装在Service方法中。
例如: -
PresentationService
@Transactional
public List<Long> getAttendeesCountForPlanning(Long planningId) {
...
}
这必须返回每个Planning Id的Presentation Attendees Count列表。因此,这将包含在单个交易中。有关详细信息,请阅读此post
答案 1 :(得分:0)
我通过更改List&lt;&gt;来解决了这个问题。设置&lt;&gt;关于ManyToMany和OneToMany的关系
答案 2 :(得分:0)
奇怪,因为它似乎在方法中调用事务方法不起作用。例如,请参阅
@Service
public class MyServiceImpl implements MyService{
@Autowired
MyDAO myDAO;
@Override
@Transactional(readOnly=true)
public MyObject method1(String param) {
return MyObject myObject = myDAO.get(param);
}
@Override
//Won't work without the transactional annotation
public MyObject method2() {
return method1("bla");
}
}