JavaEE ------ Hibernate Study Notes

Source: Internet
Author: User

JavaEE ------ Hibernate Study Notes
Hibernate framework needs to be configured
Hibernate. cfg. xml file (which is set to connect to the database and MAP value object)

The value object is also required:
For example, Custom. hbm. xml is configured with values in hibernate (including the size of data fields in the database and IDs). The fields in xml must be the same value object in the value object and the modified xml file must be stored together.
Basically, some configuration files are copied.
Single table:

Query

SessionFactory sessionfactory = config. buildSessionFactory ();/* generate a Session instance through the session factory class */Session session = sessionfactory. openSession ();/* generates a Query object through a session */Query query = session. createQuery ("from bean. customer ");/* returns a collection List */List
 
  
Cuslist = query. list ();
 
Add
Session session = HibernateSessionFactory. getSession ();/* define Transaction start */Transaction tran = session. beginTransaction (); Dept dept = new Dept (new Long (1001), "math", "shanghai"); session. save (dept);/* submit the transaction and save it to the database */tran. commit ();
Delete
Session session = HibernateSessionFactory. getSession ();/* first query the records to be deleted by ID */Dept dept = (Dept) session. get (Dept. class, new Long (10); Transaction tran = session. beginTransaction (); session. delete (dept); tran. commit ();}

Modify
Session session = HibernateSessionFactory. getSession (); Transaction tran = session. beginTransaction ();/* first find the record to be modified by ID */Dept dept = (Dept) session. get (Dept. class, new Long (10); dept. setDname ("math"); session. saveOrUpdate (dept); tran. commit ();
Auto-increment of primary keys in data:
Generator usage in value object configuration.
 
             
              
           
  
 
There are several methods:
Assigned: manually set and the primary key is generated by an external program without Hibernate. Identity: automatically generated. You do not need to manage it. columns are automatically increased. When a record is added, the value of the primary key can be assigned no value. Use the primary key generation mechanism provided by the database. Increment: The primary key increments by numerical order. Some data is not supported. It is generated by hibernate and has a problem with multithreading. sequence: uses the sequence mechanism provided by the database to generate the primary key, given sequence 1 -- 3---5---7 --.... Native: Hibernate uses identity, hilo, and sequence as the primary key generation method based on the underlying database. Uuid. hex: The ID column assigned by Hibernate. You do not need to specify this value.
Hibernate query statement:
Session session = HibernateSessionFactory. getSession (); Query query = session. createQuery ("from Customer"); // equivalent to limit 10. 10 subscripts start from 10 and the next 10 subscripts. This is the case in paging technology. Query. setFirstResult (10); // set the start position of the query record, and the index starts from 0. Query. setMaxResults (10); // sets the maximum number of records returned by the query. List list = query. list ();

Conditional query:
I. Partial query:
Session session = HibernateSessionFactory. getSession (); Query query = session. createQuery ("from Customer cus where cus. name = 'zhou'"); // the Query name is the name of zhou.

Ii. Single Attribute Query

Session = HibernateSessionFactory. getSession ();

List cnames = session. createQuery ("select cname from Customer"). list ();
// Variable name in java.
For (int I = 0; I <cnames. size (); I ++ ){

String name = (String) cnames. get (I );

System. out. println (name );
}

3. query multiple attributes using an array of Objects
Session = HibernateSessionFactory. getSession ();
// Query multiple attributes. The set element is an array of objects.

// The type of the array element, which is related to the attribute type of the object class

List students = session. createQuery ("select sno, sname from Students"). list ();
For (int I = 0; I <students. size (); I ++ ){
Object [] obj = (Object []) students. get (I );

System. out. println (obj [0] + "," + obj [1]);

}


4. It can be encapsulated into a list for querying multiple attributes. Some columns can be loaded using the List set.

Session session = HibernateSessionFactory. getSession ();
Query query = session. createQuery (
"Select new list (cus. name, cus. phone) from Customer cus" // encapsulate a set
);

List list = query. list ();
For (int I = 0; I <list. size (); I ++ ){
List temp = (List) list. get (I );
System. out. println (temp. get (0 ));
// 0 is the index
}

5. Use the Map set to install some columns
Session session = HibernateSessionFactory. getSession ();

Query query = session. createQuery (
"Select new map (cus. name, cus. phone) from Customer cus"
);

List list = query. list ();
For (int I = 0; I <list. size (); I ++ ){
Map temp = (Map) list. get (I );
System. out. println (temp. get ("1 "));
// "1" is the key
}

6. Internal Connection Query
Query query = session. createQuery ("select c. name, s. name from Student s join s. classes c"). list ();
For (Iterator iter = students. iterator (); iter. hasNext ();){
Object [] obj = (Object []) iter. next ();
System. out. println (obj [0] + "," + obj [1]);

}

7. External links:
This is written to Query query = session. createQuery (content );
Select c. name, s. name from Classes c left join c. students s
Select c. name, s. name from Classes c right join c. students s

8. query with Parameters
? As a parameter
For example, "from Customer cus where cus. name =? ";
Session session = HibernateSessionFactory. getSession ();
Query query = session. createQuery ("from Customer cus where cus. name =? ");
Query. setParameter (0, "zhou ");
// Set the parameter, starting from 0.
List list = query. list ();

Parameter name: name
For example, "from Customer cus where cus. name =: name ";
Session session = HibernateSessionFactory. getSession ();
Query query = session. createQuery ("from Customer cus where cus. name =: name ");
Query. setParameter ("name", "zhou ");
// If you set the parameter, you do not need to write a number. You can set the name directly.
List list = query. list ();
Conditional query, use? Transmission Parameters
Query query = session. createQuery ("SELECT s. id, s. name FROM Student s WHERE s. name LIKE? ");

Query. setParameter (0, "% week %"); // the index of the parameter passing starts from 0.
For example, for conditional query, use the ": parameter" name to pass the Parameter

Query query = session. createQuery ("SELECT s. id, s. name FROM Student s WHERE s. name LIKE: myname ");
Query. setParameter ("myname", "Zhang San ");
// PASS Parameters
Because the setParameter method returns the Query interface,
Therefore, you can use the omitted method to query
List students = session. createQuery ("SELECT s. id, s. name FROM Student s WHERE s. name LIKE: myname and s. id =: myid ")
SetParameter ("myname", "% week %"). setParameter ("myid", 15). list ();

Test native SQL embedding
:
SQLQuery sqlQuery = session. createSQLQuery ("select * from t_student ");

List students = sqlQuery. list ();
For (Iterator iter = students. iterator (); iter. hasNext ();){
Object [] obj = (Object []) iter. next ();
System. out. println (obj [0] + "," + obj [1]);
}

Multi-Table operations:
For example, students and faculty
Many-to-one

Configure student. xml

This is the multi-to-one relationship.

For departments:
Dept. hbm. xml

The above is tested:
In the department, we added a set named students.
Session s = HibernateSessionFactory. getSession ();
Query q = s. createQuery ("from Dept ");
List l = q. list ();
For (int I = 0; I Dept dept = (Dept) l. get (I );
System. out. println (dept. getDeptid ());
Set stu = dept. getStudents (); // you can use the Department instance to query the students in this school.
Iterator it = stu. iterator ();
While (it. hasNext ()){
Student st = (Student) it. next ();
System. out. print (st. getSno () + "");
}
}

Cascade:
Many to many tables
Student Class ing File
...... <Role-to-define class = "Teacher"
Column = "teacher_id" = "">

Mappings
......

Column = "student_id"/>

Note: splitting multiple-to-multiple associations into two one-to-multiple associations provides better scalability and operability.

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.