Saturday 15 March 2014

Hibernate: How to return the last id of an object? -


When I made a new cocktail, I want to return cocktails. I have already tried several methods, but that's why I'm new to hibernate and programming - I'm not even sure that my syntax is correct ...

My latest code snippet - & gt;

My Cocktail Dao: // Return the previous made cocktail session session; Public cocktail Lost cocktail () (return (cocktail) session.createSQLQuery ( "Choose LAST_INSERT_ID ()"). UniqueResult ();}

I CocktailController:

 < Code> // Create cocktail @RequestMapping (value = "/ EditCocktail.html", method = RequestMethod.GET) Public ModelAndView Edit (@ReiseParam (required = false) integer ID) {log Debug ("EditCocktail.html") ; ModelAndView MV = new ModelAndView (); If (id == null) {mv.addObject (new cocktail ());} else {mv.addObject (Cokteldaokfndbiaiaidi (id));} MvksetViewName ( "edit Cocktail "); Return MV;} // Order Editing Cocktail @RequestMapp ing get cocktails made previous to continue with (value = "/ CreateCocktail.html", method = RequestMethod.GET) public ModelAndView lastCocktail (@RequestParam (= false) requires integer id) {ModelAndView mv = new models and views ( ); Mv.addObject ( "title", "cocktail"); Mv.addObject ( "message", "Stalen Sii Dan cocktail Frtig"); Mv.addObject ( "cocktail", Cokteldaoktlast cocktail ()); System. Out.println ("_____________________________________________________________" + ID); Mv.addObject ("edit", incorrect); Mv.setViewName ("list-cocktail"); Return MV; }   

Right now I am getting the following error message:

  June 22, 2013 13:03:08 org.apache.catalina.core.StandardWrapperValve SEVERE : In the context of the [Pikpride] path with servlet for servlet.service () [/ DP] threw exception [request process failed; Nested exception de.hdu.pms.ctrl.CocktailController.lastCocktail (CocktailController.java:103) on sun.reflect.NativeMethodAccessorImpl.invoke0 java.lang.NullPointerException] root causes with JavaklangkNullPointerException (Native Method) at sun the SunkreflectkDelegatingMethodAccessorImplkinvoke (unknown source .reflect.NativeMethodAccessorImpl.invoke java.lang.reflect.Method.invoke) on (unknown source) (unknown source)   

thanks in advance for your help!

With hibernate, you save the method, this Id, the saved object of the return. Once you save, to get your cocktail again, just get the ID, find it in the database. Check the code given below:

  public integer addCocktail (string your properties) {session session = factory.p.in session (); Transaction tx = null; Integer cocktail id = null; Try {Tx = session.beginTransaction (); Cocktail maccall = new cocktail (your properties); Cocktail id = (integer) session.save (mycockTail); Tx.commit (); } Hold (Hibernate Expression E) {if (tx! = Null) tx. Rollback (); E.printStackTrace (); } Finally {session.close (); } Return Cocktail ID; }   

Hope this is helpful!

No comments:

Post a Comment