Hibernate's Getting Started Crud

Source: Internet
Author: User

Package Com.test;import com.demo.user;import org.hibernate.hibernateexception;import org.hibernate.Session; Import Org.hibernate.sessionfactory;import Org.hibernate.transaction;import org.hibernate.cfg.Configuration; Import Org.junit.test;import java.util.arrays;import java.util.List;/** No hibernateutil gadget*/ Public classCrudtest {Private StaticSessionfactory sessionfactory;//The factory has only one build based on the configuration file .    Static{Configuration cfg=NewConfiguration (); //cfg.configure ();//default Auto-config hibernate.cfg.xml under src//Cfg.addresource ("Com/demo/user.hbm.xml");//Add a mapping file that has already been configured in the configuration)//Cfg.addclass (user.class);//go to the package in which the user class looks for a file with the name user and the suffix. Hbm.xmlCfg.configure ("Hibernate.cfg.xml");//reads the specified master profile (the location can also be specified without specifying, by default automatically finds the Cfg.xml under SRC)Sessionfactory = Cfg.buildsessionfactory ();//Generate session Factory} @Test Public voidTestsave () throws Exception {User u=NewUser (); U.setname ("BB"); U.setpassword ("1563"); U.settype ("Root"); Session ses= Sessionfactory.opensession ();//Open a new sessionTransaction ts = ses.begintransaction ();//Start Transaction----The object that created the transaction TS        Try{ses.save (u);//save data to table User1Ts.commit ();//Commit a transaction}Catch(Hibernateexception He) {he.printstacktrace (); System. out. println ("it's dead."); Ts.rollback ();//Rollback of a transaction}finally{ses.close ();            Sessionfactory.close (); System. out. println ("Insert Successful"); }} @Test Public voidTestget () throws Exception {Session session=sessionfactory.opensession (); Transaction TX=session.begintransaction (); User User= (User) session.Get(User.class,4);//get field 1 in the user tableSystem. out. println (user);//The tostring method has been rewritten [user:id=1,name=hoobey,password=456,type=admin]Tx.commit ();    Session.close (); } @Test Public voidTESTHQL () {Session session=sessionfactory.opensession (); Transaction TX=session.begintransaction (); String hql=NULL; //Execute Query//1. Simple Query        /*hql = "from User";*/        //2. Take the filter and sort from User as U--use alias as to omit        /*hql= "from User u where u.id = 1";*/        //3. Specify the SELECT clauseHQL ="Select U.id, u.name from User u";//querying multiple specified forexample returns the array output using array.tostring ()List List=session.createquery (HQL). List ();  for(Object obj:list) {if(Obj.getclass (). IsArray ()) {System. out. println (Arrays.tostring ((object[)) obj);//when the query returns an array}Else{System. out. println (obj);//Direct output When the query returns the type of the original property}            }          }        //---------------The second part of the study-----------------------------//1, aggregate function: Count (), Max (), Min (), AVG (), SUM ()//hql = "Select COUNT (*) from User";//The returned result is a long type.//hql = "Select min (id) from Employee";//The returned result is the type of the id attribute//Number result = (number) session.createquery (HQL). Uniqueresult ();//System.out.println (Result.getclass ());//System.out.println (Result); //2, group: GROUP By ... having//hql = "Select E.name,count (e.id) from the Employee e GROUP by E.name"; //hql = "Select E.name,count (e.id) from the Employee e GROUP by E.name have COUNT (e.id) >1"; //hql = "Select E.name,count (e.id) from the Employee e WHERE id<9 GROUP by E.name have COUNT (e.id) >1"; // ---        //hql = "Select E.name,count (e.id)" +//        //"from Employee E" +//        //"WHERE id<9" +//        //"GROUP by e.name" +//        //"having count (e.id) >1" +//        //"ORDER by Count (e.id) ASC"; // ---        //hql = "Select E.name,count (e.id) as C" +//        //"from Employee E" +//        //"WHERE id<9" +//        //"GROUP by e.name" +//        //"having count (e.id) >1" +//column aliases cannot be used in a HAVING clause//"ORDER by C ASC";//column aliases can be used in the By clause//3, Connection query/HQL is an object-oriented query//>> Internal connection (inner keyword can be omitted)//hql = "Select E.id,e.name,d.name from Employee e JOIN e.department D"; //hql = "Select E.id,e.name,d.name from Employee e INNER JOIN e.department d"; //>> LEFT OUTER join (outer keyword can be omitted)//hql = "Select E.id,e.name,d.name from Employee e left OUTER JOIN e.department D"; //>> right outer join (outer keyword can be omitted)//hql = "Select E.id,e.name,d.name from Employee e right JOIN e.department d"; //You can use the more convenient method//hql = "Select E.id,e.name,e.department.name from Employee e"; //4, using parameters when querying//>> method One: use '? ' Occupy position//hql = "from Employee e WHERE id between?" and? ";//List List = Session.createquery (HQL)//        //. Setparameter (0, 5)//set the parameter, and the index of the 1th parameter is 0. //. Setparameter (1,)//        //. List (); //>> Method Two: Use variable name//hql = "from Employee e WHERE id between:idmin and:idmax"; //List List = Session.createquery (HQL)//        //. Setparameter ("Idmax",//        //. Setparameter ("Idmin", 5)//        //. List (); //When the parameter is a collection, be sure to use Setparameterlist () to set the parameter value//hql = "from the Employee e WHERE ID in (: IDs)"; //List List = Session.createquery (HQL)//        //. Setparameterlist ("IDs", new object[] {1, 2, 3, 5, 8, +})//        //. List (); //5, using named Queries//query query = session.getnamedquery ("Querybyidrange"); //query.setparameter ("Idmin", 3); //query.setparameter ("Idmax", 10); //List List = Query.list (); //6,update with Delete, does not notify session cache//>> Update//int result = Session.createquery (////"UPDATE User e SET e.name=?" WHERE user_id = 2 ")////. Setparameter (0, "HGHG")////. executeupdate ();//returns the result of the int type, indicating how many rows were affected. //System.out.println ("result =" + result); //User user = (user) Session.get (user.class, 1);//System.out.println (User.getname ()); //>> Delete        /** int result = Session.createquery (//"DELETE from Employee e WHERE id>15")//. Executeupdate ();//return int type The result, which indicates how many rows were affected.         SYSTEM.OUT.PRINTLN ("result =" + result); */        //-----Execute the query and display the results// //List list = Session.createquery (HQL). List (); //For (Object obj:list) {//if (Obj.getclass (). IsArray ()) {//System.out.println (arrays.tostring ((object[)) obj); //} else {//System.out.println (obj); // }        // }Tx.commit ();    Session.close (); }}

Hibernate's Getting Started Crud

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.