Hibernate basic configuration file and Crdu operation and basic HQL query

Source: Internet
Author: User

All of the following are saved in the E:\JavaWebSrc\firstHibernate directory, the project name is Firsthibernate, open with idea, the project requires the jar package in f:\ common general \ Common Jar Package \hibernate\ Hibernate-release-4.3.10.final

directory, add the database connection package, the database name is: Hibernate

1, Hibernate.cfg.xml

The order of the configuration files is related and cannot be changed

<?xml version='1.0'encoding='Utf-8'? ><! DOCTYPE hibernate-Configuration Public"-//hibernate/hibernate Configuration dtd//en"        "HTTP://WWW.HIBERNATE.ORG/DTD/HIBERNATE-CONFIGURATION-3.0.DTD">"Hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property><property name="Hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="Hibernate.connection.username">root</property> <property name="Hibernate.connection.password">123456</property> <property name="Hibernate.show_sql">true</property> <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> <property name="Hibernate.hbm2ddl.auto">update</property> <property name="Hbm2ddl.auto">update</property> <property name="Format_sql">true</property>
The related classes need to be added here to configure <mapping resource="Domain/userentity.hbm.xml"/> <mappingclass="domain. Userentity"/> </session-factory>

2: Mapping file for Class XXX.cfg.xml

You can generate a database based on a class's mapping file, or you can generate a persisted class based on a table in the database

XXX.cfg.xml needs to be placed in a persistent, similar level of directory

<?xml version='1.0'encoding='Utf-8'? ><! DOCTYPE hibernate-Mapping Public"-//hibernate/hibernate Mapping DTD 3.0//en"    "HTTP://WWW.HIBERNATE.ORG/DTD/HIBERNATE-MAPPING-3.0.DTD">className="domain. Userentity"table="User"Schema="Hibernate"> <id name="ID"column="ID"Type="int"> <!--PRIMARY key generation strategy, make as much as possible hibernate management--<generatorclass="native"/> </id> <property name="username"column="username"Type="java.lang.String"/> <property name="Password"column="Password"Type="java.lang.String"/> </class>

3: Add Data

Save () and persist () both hold the data, but the Sava method caches the object, persist "stick" does not cache the object

 Public classtest1 {sessionfactory sessionfactory;    Session session; @Before Public  voidbefore () {Configuration Configuration=NewConfiguration ();        Configuration.configure (); Sessionfactory=configuration.buildsessionfactory (); Session=sessionfactory.opensession (); }    /** * Test saved data save and persist are saved*/@Test Public voidTestsave () {Transaction Transaction=session.begintransaction (); Userentity userentity=Newuserentity (); Userentity.setusername ("Yu Wenhui"); Userentity.setpassword ("123456");//Session.save (userentity);session.persist (userentity);    Transaction.commit (); } @After Public  voidAfter () {session.close ();    Sessionfactory.close (); }}

4: Load Data

Test load data get method and Load method
Get gets the SQL statement that is issued to the database immediately, and the persisted object is obtained
The load method calls for a proxy class object ( a subclass of Userentity) that only holds the ID of the persisted class (which confirms that the persisted class must have an ID as the primary key) until the non-primary key attribute of the object is used. To make angry statements to the database.
The GetClass () method does not use the object
**     *Test Load data get method and Load method*Get gets the SQL statement that is issued to the database immediately, and the persisted object is obtained*The load method calls for a proxy class object that only holds the ID of the persisted class (which confirms that the persisted class must have an ID as the primary key) until the non-primary key attribute of the object is used , and the database is issued an angry statement*the GetClass () method does not use the object*/@Test Public voidTestget () {Transaction Transaction=session.begintransaction (); Userentity userentity= (userentity) session.Get(Userentity.class,1); System. out. println (Userentity.getclass ());/*class domain. Userentity here is the real userentity object*/      /*userentity user = (userentity) session.load (Userentity.class, 1); System.out.println (User.getclass ()); *//*class domain. Userentity_$$_jvst85e_0 here is a proxy object that only holds the ID of the persisted class*/    }

5: Modify Data

/* *     * Test Update method     * Check this     object first, then change the object */     @Test    public  void testupdate () {        = session.begintransaction ();         = (userentity) session.load (userentity.  Class1);        User.setusername (" Yu Xiaoxi ");        Session.update (user);        Transaction.commit ();    }

6: Delete Data

/* *     * Test Delete method     * First query to this object, and then delete     the object */     @Test    public  void  testdelete () {        = session.begintransaction ();         = (userentity) session.load (userentity.  Class,3);        Session.delete (user);        Transaction.commit ();    }

7: Basic HQL Query

Get a single object

/**
* Get a single object
*/
@Test
public void testhql () {
String hql = "from userentity WHERE id =?" and username =? ";
Query query = session.createquery (HQL);
placeholder parameter starting from 0, not starting from 1
Query.setparameter (0,1). Setparameter (1, "Yu Xiaoxi");
Gets the 0 subscript object in the collection
Userentity user = (userentity) query.list (). get (0);
SYSTEM.OUT.PRINTLN (user);
}

Get multiple Objects (collection)

 /** * Query multiple objects, get a list in the collection*/@Test Public  voidtesthqllist () {//the From is not a table name, but a persisted class nameString HQL ="From userentity"; Query Query=session.createquery (HQL); List<UserEntity> users =query.list ();  for(userentity user:users) {System. out. println (User.tostring ()); }    }

Hibernate basic configuration file and Crdu operation and basic HQL query

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.