Hibernate's crud&hql& pagination

Source: Internet
Author: User

 Packagecom.eudask.ht1;Importjava.util.Date; Public classStu {PrivateInteger ID; PrivateString XM; PrivateString sex; PrivateDate SR;  PublicInteger getId () {returnID; }     Public voidsetId (Integer id) { This. ID =ID; }     PublicString Getxm () {returnXM; }     Public voidSetxm (String xm) { This. XM =XM; }     PublicString Getsex () {returnsex; }     Public voidsetsex (String sex) { This. Sex =sex; }     PublicDate GETSR () {returnSR; }     Public voidSETSR (Date sr) { This. sr =SR; } @Override PublicString toString () {return"Stu [id=" + ID + ", xm=" + XM + ", sex=" + Sex + ", sr=" +SR+ "]"; }    }
Stu.java
<?xml version= "1.0"? ><! DOCTYPE hibernate-    mappingPublic "-//hibernate/hibernate mapping DTD 3.0//en"    "/http WWW.HIBERNATE.ORG/DTD/HIBERNATE-MAPPING-3.0.DTD ">mapping    package =" Com.eudask.ht1 ">        <class name=" Com.eudask.ht1.Stu "table=" Stu ">        <id name=" id ">            Class= "Native" ></generator>        </id>        <property name= "XM"  column= " XM "/>        <property name=" Sex "type=" java.lang.String "column=" Sex "/>        <property name=" sr "type=" Java.util.Date "column=" sr "/>                </class>        
Stu.hbm.xml
 Packagecom.eudask.ht1.test;Importjava.sql.Date;Importjava.util.List;ImportOrg.hibernate.Criteria;ImportOrg.hibernate.Query;ImportOrg.hibernate.SQLQuery;Importorg.hibernate.Session;Importorg.hibernate.Transaction;Importorg.hibernate.criterion.Restrictions;Importorg.junit.Test;ImportCom.eudask.ht1.Stu;ImportCom.eudask.ht1.util.HibernateUtil; Public classtestst {@Test Public voidAddstu () {Stu Stu=NewStu (); STU.SETXM ("Guo Degang 2"); Stu.setsex ("Male 2"); STU.SETSR (Date.valueof ("2016-10-21")); //Get SessionSession session =hibernateutil.getsession (); //Open TransactionTransaction ts =session.begintransaction (); Try{session.save (stu);        Ts.commit (); } Catch(Exception e) {e.printstacktrace ();        Ts.rollback (); } finally{session.close (); }} @Test Public voidTestcritetoa () {//Get SessionSession session =hibernateutil.getsession (); Criteria CR=session.createcriteria (Stu.class); Cr.add (Restrictions.eq ("id", 1)); List<Stu> stus=cr.list ();  for(Stu stu:stus) {System.out.print (STU);            } session.close (); } @Test Public voidTestsql () {//Get SessionSession session =hibernateutil.getsession (); String SQL= "SELECT * from Stu"; SQLQuery SQ=session.createsqlquery (SQL); List<Object[]> stus=sq.list ();  for(object[] stu:stus) { for(Object stuo:stu) {System.out.println (Stuo);                        }} session.close (); }        //querying data by ID@Test Public voidFindByID () {Session session=hibernateutil.getsession (); Stu Stu= (Stu) session.get (Stu.class, 1);            System.out.println (Stu.getid ());            System.out.println (Stu.getsex ());            System.out.println (STU.GETXM ());            System.out.println (STU.GETSR ());        Session.close (); }                //Modifying Data@Test Public voidUpdate () {Session session=hibernateutil.getsession (); Stu Stu= (Stu) session.get (Stu.class, 1); //Open TransactionTransaction ts =session.begintransaction (); Try{STU.SETXM ("Yu Yunpeng");                Session.update (Stu);            Ts.commit (); } Catch(Exception e) {e.printstacktrace ();            Ts.rollback (); } finally{session.close (); }        }                //Query All@Test Public voidSelectAll () {//Get Hibernatesession ObjectSession session =hibernateutil.getsession (); //Writing HQL StatementsString hql = "from Stu where Id=:input";//String hql = "from Stu as S where id=?"; //Create a query object by invoking the CreateQuery of the session as a parameter of the HQL statementQuery query =session.createquery (HQL); //If there are parameters set the query condition through the Query.setxx () methodQuery.setinteger ("Input", 1);//Query.setinteger (0, 1); //iterate through query results by using Query's list and other methodsList<stu> Stus =query.list ();  for(Stu s:stus) {System.out.println (s);        } session.close (); }                //Delete@Test Public voidDelete () {Session session=hibernateutil.getsession (); Stu Stu= (Stu) session.get (Stu.class, 2); Transaction TS=session.begintransaction (); Try{session.delete (stu);            Ts.commit (); } Catch(Exception e) {e.printstacktrace ();            Ts.rollback (); } finally{session.close (); }        }                        //page of Hibernate         Public voidFenye (intPageintPageitems) {Session Session=hibernateutil.getsession (); String hql= "From Stu"; Query Query=session.createquery (HQL); Query.setfirstresult (Page-1) *pageitems);            Query.setmaxresults (Pageitems); List<Stu> list=query.list ();  for(Stu stu:list) {System.out.println (STU); }                    }                 Public Static voidMain (string[] args) {testst T=Newtestst (); T.fenye (1, 10); System.out.println ("======================="); T.fenye (2, 10); }}
Testst.java
 PackageCom.eudask.ht1.util;Importorg.hibernate.Session;Importorg.hibernate.SessionFactory;Importorg.hibernate.cfg.Configuration; Public classHibernateutil {Private Staticsessionfactory sessionfactory; Static{        //To load Hibernate master configuration files//Configuration Confg=new configuration (). Configure ();Configuration confg=NewConfiguration ();        Confg.configure (); Sessionfactory=confg.buildsessionfactory (); }        //Create session     Public StaticSession getsession () {returnsessionfactory.opensession (); }}
Hibernateutil.java
<! DOCTYPE hibernate-Configuration Public"-//hibernate/hibernate Configuration DTD 3.0//en" "Http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd" >///hibernate_20120328</property><property name= "Connection.driver_class" >com.mysql.jdbc.Driver</property> <property name= " Connection.username ">root</property> <property name=" Hibernate.connection.password ">hyy</ property> <property name= "Hibernate.show_sql" >true</property> <property name= "Hibernate.format_sql" >false</property> <!--Create : Delete, then create update: If the table does not exist on the creation, not the same as the update, just do nothing. Create-drop: When the table is created when initializing, Sessionfactory executes close () when the table is dropped.         Validate: Verifies that the table structure is consistent and throws an exception if it is not consistent. --<property name= "Hbm2ddl.auto" >update</property> <!--Set the default transaction isolation level: the integer corresponding to the isolation level represents the READ uncommited1READ commited2Repeatable READ4serializeable8--<property name= "connection.isolation" >2</property> <mapping resource= "Com/eudask /ht1/stu.hbm.xml "/> <mapping resource=" Com/eudask/ht1/tea.hbm.xml "/> <mapping resource=" com/eudask/ht1 /qiang.hbm.xml "/></session-factory>Hibernate.cfg.xml

Hibernate's crud&hql& pagination

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.