Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

java - @Transactional methods in @Controller class are not considred as transactional

I noticed that the following is not working in a class marked as a @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;
}

when I call the URL, I get an error saying that the method is not transactional (although, as you can see, it is marked as one)

If I copy this method to a another class called MyService and call it from the controller instead, it works perfectly

Is this some sort of a Spring advice (a conspiracy to make me use more classes more or less)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Don't do transactions in your controller. Put them in your service layer classes.

Separate your code into model-view-controller.

Yes it is a conspiracy. It enables to you to share code between controllers/views without repeating code. And also stops rollbacks of transactions unnecessarily (for exceptions unrelated to the actual transaction).

It might seem like more code to begin with, but in the long run it is much more manageable and simpler to develop.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...