Use Hibernate3.6.10 for CRUD operations

Source: Internet
Author: User

Commit commit 1. Add a data record and add it to the transaction.

Package com. itheima. util;

Import org. hibernate. Session;

Import org. hibernate. SessionFactory;

Import org. hibernate. cfg. Configuration;

// Hibenate tool class

Public class HibernateUtil {

Private static SessionFactory sessionFactory;

Static {

Configuration cfg = new Configuration (). configure ();

SessionFactory = cfg. buildSessionFactory ();

}

Public static Session getSession (){

Return sessionFactory. openSession ();

}

Public static void main (String [] args ){

Session s = getSession ();

S. close ();

}

}

You can see the addition operation here, without writing hql statements, is to set the value through the object, which is the benefit of hibernate

@ Test

Publicvoid testaddPerson (){

Personp = new Person ();

P. setName ("Chen xingyu 1 ");

P. setBirthday (newDate ());

P. setGender ("male ");

Sessionsession = HibernateUtil. getSession ();

Transactiontx = session. beginTransaction (); Start transaction

Session. save (p); // prepare to execute the SQL statement

System. out. println (p. getName (); when executed, the console prints the insert statement, but the database does not have data

Tx. commit (); Submit the transaction

Session. close (); execute to this, only data in the database is available. Refresh the database and you can see

System. out. println (p );

}

2. query entities based on the Union primary key

Package com. itheima. domain;

Import java. io. Serializable;

// Hypothesis: Students without duplicate names

Public class Student implementsSerializable {

PrivateString firstName; // Primary key

PrivateString secondName; // Primary key

PrivateString gender;

PublicString getFirstName (){

ReturnfirstName;

}

Publicvoid setFirstName (String firstName ){

This. firstName = firstName;

}

PublicString getSecondName (){

ReturnsecondName;

}

Publicvoid setSecondName (String secondName ){

This. secondName = secondName;

}

PublicString getGender (){

Returngender;

}

Publicvoid setGender (String gender ){

This. gender = gender;

}

}

Configuration File student. hbm. xml

"-// Hibernate/Hibernate Mapping DTD 3.0 // EN"

Http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd>

The following hql statement is not written and the get method is used for query.

// Query Objects Based on the Union primary key

@ Test

Publicvoid testQueryStudent (){

Sessionsession = HibernateUtil. getSession ();

// Set the federated primary key

Students1 = new Student ();

S1.setFirstName ("zhting ");

S1.setSecondName ("w ");

Students = (Student) session. get (Student. class, s1); // joint primary key: Use the entity class itself as a condition

System. out. println (s );

Session. close ();

}

3. Three states of persistent objects in Hibernate and their mutual conversion

4. hibernate Cache

// Session cache: Level 1 Cache

Public class HibernateDemo3 {

// Verify the existence of the cache

@ Test

Public void testaddStudent (){

Session session = HibernateUtil. getSession ();

Transaction tx = session. beginTransaction ();

Person p1 = (Person) session. get (Person. class, 1); // same as OID

Person p2 = (Person) session. get (Person. class, 1); // same as OID. Because this object exists in the cache, it is directly retrieved and will not be queried in the database again.

System. out. println (p1 = p2); // true

Tx. commit ();

Session. close ();

}

// Manage the first-level cache

/*

* Session. flush (): refresh the cache (synchronize the database ). The cached data is still

* Session. clear (): clears the cache.

* Session. evict (): clears the specified object.

*/

@ Test

Public void testSessionManager1 (){

Session session = HibernateUtil. getSession ();

Transaction tx = session. beginTransaction ();

Person p1 = (Person) session. get (Person. class, 1); // get the Persistent Object and put it in the Session cache.

System. out. println (p1 );

// Session. flush (); // only updates the database. The data in the cache is still

// Session. clear (); // clear the cache

Session. evict (p1); // clear the specified object from the cache

Person p2 = (Person) session. get (Person. class, 1 );

System. out. println (p2 );

Tx. commit ();

Session. close ();

}

// Snapshot:

// Refresh when commit is enabled

@ Test

Public void testSessionManager2 (){

Session session = HibernateUtil. getSession ();

Transaction tx = session. beginTransaction ();

Person p1 = (Person) session. get (Person. class, 1); // get the Persistent Object and put it in the Session cache.

P1.setName ("Chen xingyu 2"); // refresh database data can only refresh persistent child entities

Tx. commit (); // synchronize the database at this time

Session. close ();

}

@ Test

// Manual flush will refresh

Public void testSessionManager3 (){

Session session = HibernateUtil. getSession ();

Transaction tx = session. beginTransaction ();

Person p1 = (Person) session. get (Person. class, 1); // get the Persistent Object and put it in the Session cache.

P1.setName ("Chen xingyu"); // refresh database data can only refresh persistent child entities

Session. flush (); // synchronize the database

Tx. commit (); // synchronize the database at this time

Session. close ();

}

@ Test

// During Query execution, the changed object classes are automatically synchronized to the database.

Public void testSessionManager4 (){

Session session = HibernateUtil. getSession ();

Transaction tx = session. beginTransaction ();

Person p1 = (Person) session. get (Person. class, 1); // get the Persistent Object and put it in the Session cache.

P1.setName ("Chen xingyu 1"); // refresh database data can only refresh persistent State entities

Query q = session. createQuery ("from Person"); // a mandatory SQL statement

System. out. println (q. list (). get (0 ));

Session. flush (); // synchronize the database

Tx. commit (); // synchronize the database at this time

Session. close ();

}

@ Test

// Verify the refresh Mode

Public void testSessionManager5 (){

Session session = HibernateUtil. getSession ();

Transaction tx = session. beginTransaction ();

// Session. setFlushMode (FlushMode. COMMIT); // when the transaction is committed and manually flush. Not flushed during Query

// Session. setFlushMode (FlushMode. MANUAL); // when the transaction is committed and manually flush. Not flushed during Query

Person p1 = (Person) session. get (Person. class, 1); // get the Persistent Object and put it in the Session cache.

P1.setName ("Chen xingyu"); // refresh database data can only refresh persistent child entities

Query q = session. createQuery ("from Person"); // a mandatory SQL statement

System. out. println (q. list (). get (0); // get from Cache

Tx. commit (); // synchronize the database at this time

Session. flush (); // synchronize the database

Session. close ();

}

// Refresh: overwrites the cached data with the data in the database.

@ Test

Public void testSessionManager6 (){

Session session = HibernateUtil. getSession ();

Transaction tx = session. beginTransaction ();

Person p1 = (Person) session. get (Person. class, 1); // get the Persistent Object and put it in the Session cache.

P1.setName ("Chen xingyu ");

Session. refresh (p1); // overwrite the cached data with the data in the database

Tx. commit (); // synchronize the database at this time

Session. close ();

}

}

The above fl means to update data to the database. If it is not flushed out, it means not to update (synchronize) the data to the database.

5. Common Methods for Session interfaces in hibernate (CUD addition, deletion, and modification)

// Common Session Methods

Public class HibernateDemo1 {

// If the primary key of the object class is the proxy primary key. The manually set id is invalid.

// Save: instantaneous ---> persistent

@ Test

Public void test1 (){

Person p = new Person ();

P. setName ("Wang Dong ");

P. setBirthday (new Date ());

P. setGender ("female ");

Session s = HibernateUtil. getSession ();

Transaction tx = s. beginTransaction ();

P. setId (100); // unused.

S. save (p); // plan to execute an insert statement

P. setId (10); // an error is returned. In this case, the p object is persistent and ID cannot be changed.

Tx. commit (); // actually executed. FlushMode. AUTO.

S. close ();

}

// Update: disconnected ---> persistent

// Execute the update operation if the object is changed only.

@ Test

Public void test2 (){

Session s = HibernateUtil. getSession ();

Transaction tx = s. beginTransaction ();

Person p = (Person) s. get (Person. class, 1); // persistent state

S. evict (p); // exit the tube

P. setName ("xingyu ");

S. update (p); // if the object is an unmanaged object, the update statement will be executed no matter whether the object is changed or not.

Tx. commit (); // actually executed. FlushMode. AUTO.

S. close ();

}

//

// SaveOrUpdate ()

// The object is in the Instantaneous State. If the OID is null, save. Determine the configuration file

// The object is out of control: OID has, and update is executed.

@ Test

Public void test3 (){

Session s = HibernateUtil. getSession ();

Transaction tx = s. beginTransaction ();

// Skip --> persistent: update

// Person p = (Person) s. get (Person. class, 1); // persistent state

// S. evict (p); // exit the tube

// P. setName ("xingyu ");

// S. saveOrUpdate (p); // if the object is an unmanaged object, the update statement is executed no matter whether the object is changed or not.

// Instantaneous ---> persistent: save

Person p = new Person ();

P. setName ("Yang Xianbin ");

P. setBirthday (new Date ());

P. setGender ("female ");

S. saveOrUpdate (p); // execute save

Tx. commit (); // actually executed. FlushMode. AUTO.

S. close ();

}

//

@ Test

Public void test4 (){

Session s = HibernateUtil. getSession ();

Transaction tx = s. beginTransaction ();

Person p = (Person) s. get (Person. class, 1 );

S. evict (p );

S. saveOrUpdate (p); // insert. If id is 1, the framework treats it as an instantaneous object.

Tx. commit (); // actually executed. FlushMode. AUTO.

S. close ();

}

// SaveOrUpdate (): If a persistent State object is operated, it will not change.

@ Test

Public void test5 (){

Session s = HibernateUtil. getSession ();

Transaction tx = s. beginTransaction ();

Person p = (Person) s. get (Person. class, 1 );

S. saveOrUpdate (p );

Tx. commit ();

S. close ();

}

// Difference between get and load:

// 1. get instant retrieval; load indicates delayed retrieval (Agent Class)

// 2. If get gets a record that does not exist in the id database, null is returned; load throws an exception.

@ Test

Public void test6 (){

Session s = HibernateUtil. getSession ();

Transaction tx = s. beginTransaction ();

// Person p = (Person) s. get (Person. class, 100); // print null

Person p = (Person) s. load (Person. class, 100); // throw an exception

System. out. println (p );

Tx. commit ();

S. close ();

}

// Delete: The duration changes to instantaneous.

@ Test

Public void test7 (){

Session s = HibernateUtil. getSession ();

Transaction tx = s. beginTransaction ();

Person p = (Person) s. load (Person. class, 1 );

S. delete (p); // The deletion statement is scheduled to be executed.

Tx. commit (); // actually executed

S. close ();

}

}

Related Article

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.