Summary of adding, deleting, modifying, and querying in hibernate

Source: Internet
Author: User
Tags date1

 

MySQL database table news, the field is as follows

Id | int | auto_increment | primary key

Title | varchar

Content | varchar

Date | varchar

 

1: hibernate insert operation

Session session = hibernatesessionfactory. getsession ();

News news = new news ();

News. setcontent ("My content ");

News. settitle ("My title ");

News. setdate ("My date"); // news is Vo

Transaction trans = session. begintransaction ();

Session. Save (News); // news is Po

Trans. Commit (); // any database update operations are performed after the database is committed.

Hibernatesessionfactory. closesession ();

 

2: update operation of Hibernate

Session session = hibernatesessionfactory. getsession ();

 

News news = new news ();

News. setid (103); // ID is indispensable. hibernate only uses ID to find the database.

News. setcontent ("update content ");

News. settitle ("Update title ");

Transaction trans = session. begintransaction ();

Session. Update (News );

Trans. Commit ();

Hibernatesessionfactory. closesession ();

 

Note: here we do not want to update the date, so we didn't write setdate, but hibernate will think that we want to set date to null, so if we want to update some fields in the table, it is best to use the following method.

 

Session session = hibernatesessionfactory. getsession ();

 

Transaction trans = session. begintransaction ();

News news = (News) Session. Get (news. Class, 103); // ***** (1)

News. setdate ("update date"); // ***** (2)

Session. Save (News); // ***** (3)

Trans. Commit ();

Hibernatesessionfactory. closesession ();

 

Here, we actually performed two operations on the database. (1) We searched the corresponding records from the database. Here, news is a po, and (2) We updated the Po date, the other data is not changed, and then (3) is saved. because (1) the detected data has title and content, the title and content are not null during storage.

 

3: hibernate delete operation

Session session = hibernatesessionfactory. getsession ();

 

Transaction trans = session. begintransaction ();

News news = new news ();

News. setid (8); // The effect of the following sentence is the same, but the SELECT statement is added.

// News news = (News) Session. Get (news. Class, 8 );

 

Session. Delete (News );

Trans. Commit ();

Hibernatesessionfactory. closesession ();

Note: Data can only be deleted by ID, but cannot be deleted by title or content. A missing identifier error is returned.

 

Use hql to delete (batch delete)

Session session = hibernatesessionfactory. getsession ();

String hql = "delete billdetail where Name> 'detailname1 '";

Query query = session. createquery (hql );

Int ref = query.exe cuteupdate ();

Session. begintransaction (). Commit ();

System. Out. println ("delete dates =>" + ref); // number of operations

 

Session. Close ();

 

 

4: Select Operation of Hibernate

 

Hibernate has a wide range of select operations, which are commonly used here:

 

1. Criteria Query

Session session = hibernatesessionfactory. getsession ();

 

Criteria c = session. createcriteria (news. Class); // news is a class, so n is capitalized.

C. Add (expression. LT ("date", "date5 "));

C. Add (expression. Between ("date", "date1", "date8 "));

C. addorder (order. DESC ("date "));

 

List <News> List = C. List ();

For (INT I = 0; I <list. Size (); I ++)

{

System. Out. println (list. Get (I). GETID () + ":" + list. Get (I). getdate ());

}

Hibernatesessionfactory. closesession ();

 

It is more in line with the object-oriented concept, because the library table and Java class have been mapped, note that all hibernate operations are for Java classes, rather than library tables, so it is case sensitive.

The preceding query is equivalent to the SQL statement: Select * from news where date <'date5' and date between 'date1' and 'date8' order by date DESC;

 

2. hql Query

Query query = session. createquery ("from News ");

List <News> List = query. List (); // traverse the same as above

 

Hql is the query method promoted by hibernate. It is similar to normal SQL statements, but it is very important to note that in hql, The from class name is followed by the Java class name, not the database table name, don't worry !!! The other is that if the full field "select *" is queried, it can be omitted without writing.

 

When you do not query all fields or query data from two tables, an array is returned:

Session session = hibernatesessionfactory. getsession ();

 

Query query = session. createquery ("select N. ID, N. Title, U. Username from news as N, user U ");

List list = query. List (); // each row is a one-dimensional array.

For (INT I = 0; I <list. Size (); I ++)

{

Object [] O = (object []) list. Get (I); // convert to an array

Int id = (integer) O [0]; // corresponds to the sequence type in select, which can be a class

String title = (string) O [1];

String username = (string) O [2];

System. Out. println ("ID:" + ID + "," + "title" + title + "," + username );

}

Hibernatesessionfactory. closesession ();

 

The size of the query result set (slightly different from hibernate2)

(Integer) Session. createquery ("select count (*) from user"). iterate (). Next ();

 

 

3. sqlquery Query

List <News> List = session. createsqlquery ("select * From News"). addentity (news. Class). List ();

 

Addentity cannot be forgotten. This query method puts the query results in an entity and traverses the operation. It is not recommended.

 

When querying some fields in sqlquery, use addscalar:

Sqlquery query = session. createsqlquery ("select ID, title from News ");

Query. addscalar ("ID", hibernate. integer); // register the field type.

Query. addscalar ("title", new org. hibernate. type. stringtype ());

List list = query. List ();

For (INT I = 0; I <list. Size (); I ++)

{

Object [] O = (object []) list. Get (I );

Int id = (integer) O [0];

String title = (string) O [1];

System. Out. println ("ID:" + ID + ", title:" + title );

}

 

JavaBean attributes can be used as named query parameters (hql)

Session session = hibernatesessionfactory. getsession ();

Transaction trans = session. begintransaction ()

 

Query query = session. createquery ("from room in class room where room. Name =: ")

Query. setparameter ("A", "room1"); // similar to preparestatement

// Room room1 = new room ();

// Room1.setname ("room1 ");

// Query = session. createquery ("from room in class room where room. name =: Name "); // If You Use Javabean to set parameters, the name of =: Name must correspond to the name in the room.

// Query. setproperties (room1 );

List <room> List = query. List ();

For (INT I = 0; I <list. Size (); I ++)

{

System. Out. println (list. Get (I). getname () + ":" + list. Get (I). getdescription ());

}

Trans. Commit ();

Hibernatesessionfactory. closesession ()

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.