你应该把它@Transactional放在DAO类和/或它们的方法中,还是更好地注释使用DAO对象调用的Service类?或者注释两个"层"是否有意义?
我有这个问题:
org.hibernate.LazyInitializationException:懒得初始化角色集合:mvc3.model.Topic.comments,没有会话或会话被关闭
这是模型:
@Entity
@Table(name = "T_TOPIC")
public class Topic {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
@ManyToOne
@JoinColumn(name="USER_ID")
private User author;
@Enumerated(EnumType.STRING)
private Tag topicTag;
private String name;
private String text;
@OneToMany(mappedBy = "topic", cascade = CascadeType.ALL)
private Collection<Comment> comments = new LinkedHashSet<Comment>();
...
public Collection<Comment> getComments() {
return comments;
}
}
Run Code Online (Sandbox Code Playgroud)
调用模型的控制器如下所示:
@Controller
@RequestMapping(value = "/topic")
public class TopicController {
@Autowired
private TopicService service;
private static final Logger logger = LoggerFactory.getLogger(TopicController.class);
@RequestMapping(value = "/details/{topicId}", method = RequestMethod.GET)
public ModelAndView …Run Code Online (Sandbox Code Playgroud) 考虑我有一个控制器方法get(),它调用一些使用数据库的服务方法.
使整个控制器方法成为事务性或只是每个服务方法是否正确?
在我看来,我们必须进行get()交易,因为它执行相关的操作.
我在Tomcat 7中运行的Web应用程序中使用Spring 3.2和JPA以及Hibernate 4.应用程序分为控制器,服务DAO类.服务类在类和方法级别具有带注释的事务配置.DAO是普通的JPA,实体管理器由@PersistenceContext注释注入.
@Service("galleryService")
@Transactional(propagation=Propagation.SUPPORTS, readOnly=true)
public class GalleryServiceImpl implements GalleryService {
@Override
public Picture getPicture(Long pictureId) {
return pictureDao.find(pictureId);
}
@Override
public List<PictureComment> getComments(Picture picture) {
List<PictureComment> comments = commentDao.findVisibleByPicture(picture);
Collections.sort(comments, new Comment.ByCreatedOnComparator(Comment.ByCreatedOnComparator.SORT_DESCENDING));
return comments;
}
...
}
@Controller
@RequestMapping("/gallery/displayPicture.html")
public class DisplayPictureController extends AbstractGalleryController {
@RequestMapping(method = RequestMethod.GET)
public String doGet(ModelMap model, @RequestParam(REQUEST_PARAM_PICTURE_ID) Long pictureId) {
Picture picture = galleryService.getPicture(pictureId);
if (picture != null) {
model.addAttribute("picture", picture);
// Add comments
model.addAttribute("comments", galleryService.getComments(picture));
} else {
LOGGER.warn(MessageFormat.format("Picture {0} …Run Code Online (Sandbox Code Playgroud) 我注意到以下内容不适用于标记为@Controller:
@Autowired
SessionFactory sessionFactory;
@ResponseBody
@Transactional
@RequestMapping(method = RequestMethod.GET , value = "/map")
public ArrayList<PhotoDTO> getPhotos(...someParams) {
Entity result sessionFactory.getCurrentSession()... //do some manipulation
return result;
}
Run Code Online (Sandbox Code Playgroud)
当我调用URL时,我得到一个错误,说该方法不是事务性的(尽管如您所见,它被标记为一个)
如果我将此方法复制到另一个名为MyService的类并从控制器调用它,它就可以完美地工作
这是一种Spring建议(一个让我多或少使用更多课程的阴谋)?
spring ×4
java ×3
spring-mvc ×3
transactions ×3
annotations ×1
dao ×1
hibernate ×1
jpa ×1
jsp ×1