Saturday, 9 April 2011

org.hibernate.HibernateException: Current transaction is not in progress

Follow the below to overcome Current transaction is not in progress exception:



 this.getSessionFactory().openSession().createCriteria(Project.class);

Dont use the following if you are experiencing the above exception:

this.getSessionFactory().getCurrentSession().createCriteria(Project.class);

Else you can also use the following also:


Session session = ModelManager.getInstance().getCurrentSession();
  Transaction tx = null;
  List<Actor> studentList= null;

  try {
    tx = session.beginTransaction();

    Criteria criteria = session.createCriteria(Student.class);
    criteria.add( Restrictions.like("name", "A%") );
    actorList = criteria.list();

    tx.commit();
  } catch (HibernateException he) {
    tx.rollback()

  }





JSON data

Convert data into JSON format in Spring:

First import the following :
com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;

    private class XStreamJsonView implements View {

        public void render(Map<String, ?> model, HttpServletRequest req,
                HttpServletResponse res) throws Exception {
            XStream xs = new XStream(new JsonHierarchicalStreamDriver());
            xs.setMode(XStream.NO_REFERENCES);
          
            xs.toXML(model, res.getWriter());
        }


        public String getContentType() {
            return "application/json";
        }
 You can use XStreamJsonView in the following way for any responses in controller:
    @RequestMapping("/example.json")
    public ModelAndView listTestSuites() throws someException {
        List<String> answer = new ArrayList<String>();
        for (loopforSomething var : something.getNames()) {
            answer.add(var.getFirstName());
        }
        Map<String, List<String>> model = new HashMap<String, List<String>>();
        model.put("someString", passitAsResponseVariable);
        return new ModelAndView(new XStreamJsonView(),model);
    }