hibernate tutorial note 3

Keywords: Session Hibernate Database SQL

Why to learn HQL (hibernate query language) - > this is an official recommendation with powerful functions
? delete
Session.delete (object) - > batch delete
Add?
session.save session.persist
Modify - > batch modify
Sessin.update (object)

Query object obj
obj.setXXX();
Query?
load get
Query all gender male employees?

Detailed explanation of hql
In order to explain clearly, I simulate a student course selection system and create three tables
From the three tables created, we can see that:
hibernate designers recommend that when designing tables, we should have a primary key for each table, and the primary key should not contain business logic,

product table
id productNo name price
1. bi001 refrigerator 1000
2 nj111 computer 2000

Now we use the hibernate tool to automatically generate the domain object and the mapping file. If our table has the relationship of primary and foreign keys, we should map the primary table first, and then the secondary table

  • uniqueResult method
    If we retrieve an object and know that there is at most one object, this method is recommended:
    The specific usage is as follows:
    Student s=(Student) session.createQuery("from Student where sid='20050003'").uniqueResult();
    System.out.println(s.getSname());
    *Use of distinct
    Filter duplicate records
//For example, show the gender and age of all students
			List list=session.createQuery("select distinct sage,ssex from Student").list();
			for(int i=0;i<list.size();i++){
				Object []  objs=(Object[]) list.get(i);
				System.out.println(objs[0].toString()+" "+objs[1].toString());
			}
*between and..
List list=session.createQuery("select distinct sage,ssex,sname from Student where sage between 20 and 22").list();
			for(int i=0;i<list.size();i++){
				Object []  objs=(Object[]) list.get(i);
				System.out.println(objs[0].toString()+" "+objs[1].toString()+objs[2].toString());
			}
*in /not in
//Query information of students in computer department and foreign language department
			
			List<Student> list=session.createQuery("from Student where sdept in ('Department of Computer Science','Department of foreign languages')").list();
			//Take out 1. for enhancement
			for(Student s:list){
				System.out.println(s.getSname()+" "+s.getSaddress()+" "+s.getSdept());
			}
  • group by use
//Shows the average age of students in each department
List<Object[]> list=session.createQuery("select avg(sage),sdept from  Student group by sdept").list();
			//Take out 1. for enhancement
			for(Object[] obj:list){
				System.out.println(obj[0].toString()+" "+obj[1].toString());
			}


//The use of having
			//1. Filter the results after group query: for example, please display the Department name with more than 3 people
			//a. Find out how many students there are in each department
			
			List<Object[]> list=session.createQuery("select count(*) as c1,sdept from  Student group by sdept having count(*)>3").list();
			//Take out 1. for enhancement
			for(Object[] obj:list){
				System.out.println(obj[0].toString()+" "+obj[1].toString());
			}
//2 departments with less than 200 girls
			//a. Check the number of girls in each department
			List<Object[]> list=session.
			createQuery("select count(*) as c1,sdept from  Student where ssex='F' group by sdept").list();
			//Take out 1. for enhancement
			for(Object[] obj:list){
				System.out.println(obj[0].toString()+" "+obj[1].toString());
			}
//1. How many people are there in the computer department? - > if we return a column of data
			//At this time, our method is to directly retrieve list - > object instead of list - > Object []
			List<Object[]> list=session.
			createQuery("select sage from  Student where sdept='Department of Computer Science'").list();
			//Take out 1. for enhancement
			for(Object obj:list){
				System.out.println(obj.toString());
			}
//Check the highest and lowest marks of course 11
			List<Object[]> list=session.
			createQuery("select 11,max(grade),min(grade) from Studcourse where course.cid=11").list();
			//Take out 1. for enhancement
			for(Object[] obj:list){
				System.out.println(obj[0].toString()+" max="+obj[1].toString()+" min="+obj[2].toString());
			}
//Count the number of students who fail in each subject
			
			List<Object[]> list=session.
			createQuery("select count(*),student.sdept from Studcourse where grade<60 group by student.sdept").list();
			//Take out 1. for enhancement
			for(Object[] obj:list){
				System.out.println(obj[0].toString()+" "+obj[1].toString());
			}
  • Parameter binding case (JDBC - > Preparedstatement setXXX)
    The advantages of using parameter binding are as follows:
  1. Improve readability, 2 high effect, 3 prevent sql injection vulnerability
    Interview question: if parameter binding is not used, how to prevent sql injection during login?
    name password
    Ideas: 1. Through the user name, find out the corresponding password of the user name in the database, and then compare it with the secret entered by the user. If it is equal, then the user sum method, otherwise, it is illegal

There are two forms of parameter binding
Query q=session.createQuery(from Student where sdept=:dept and sage>:age)

If our parameter is given in the form of colon, our parameter binding should be as follows:

List<Student> list=session.createQuery("from Student where sdept=:a1 and sage>:sage")
			.setString("a1", "Department of Computer Science").setString("sage", "2").list();

There is another form:

Query q=session.createQuery(from Student where sdept=? and sage>?)

If our parameters are given in the form of?, the parameter binding should:

List<Student> list=session.createQuery("from Student where sdept=? and sage>?")
			.setString(0, "Department of Computer Science").setString(1, "2").list();

The binding of parameters can be written separately as follows:

Query query=session.createQuery("from Student where sdept=? and sage>?");
			
			query.setString(0, "Department of Computer Science");
			query.setString(1, "2");
			List <Student> list=query.list();
			for(int i=0;i<list.size();i++){
				Student s= list.get(i);
				System.out.println(s.getSname()+" "+s.getSage());
			}

Upgrade HibernateUtil

  • Get hql statement in mapping file
    hibernate provides a more flexible query method:
    Configure the hql statement to the object relation mapping file,
<query name="myquerytest">
	<![CDATA[select sname,ssex from Student where sage>22]]>
	</query>

In the program, we get and execute as follows:

List list=session.getNamedQuery("myquerytest").list();
		System.out.println(list.size());
		Iterator it=list.iterator();
		while(it.hasNext()){
			Object obj[]=(Object[])it.next();
			System.out.println("n="+obj[0]);
	}

There are three relationships of hibernate objects:

  1. One – to – one: ID card < - > person
  2. one – to – many department < - > employees
  3. Many to one employee < - > Department
  4. Many to many students < - > teachers

  • Criteria uses:
//Query criteria for students older than 10
		
		Session s=HibernateUtil.getCurrentSession();
		Transaction tx=s.beginTransaction();
		Criteria cri=s.createCriteria(Student.class);
		//Add search criteria
		cri.add(Restrictions.gt("sage", new Long(10)));
		List<Student> list=cri.list();
		for(Student s1: list){
			System.out.println(s1.getSname());
		}
		
		tx.commit();       

Among the three ways of hibernate development:
Write the domain object + mapping file -------- create the corresponding database,
Here we show that if you want to automatically create the corresponding database, you need to do configuration (hibernate.cfg.xml)
create
There are four configuration values: create, update, create drop, validate
Create: when our application loads hibernate.cfg.xml [new configuration(). Config();] it will create a database according to the mapping file, which will be recreated every time, and the data in the original table is not available!!!
Update: if there is no such table in the database, create it. If there is any table, see if there is any change. If there is any change, update it
Create drop: drop the schema of the database when closing sessionFactory is displayed
validate: it is equivalent to verifying whether the structure of the table in the database is consistent with that of the hbm file before inserting data

  • In development testing, we can test any configuration. However, if the project is released, it is better to configure it once by ourselves to generate the corresponding database, and then cancel the configuration,

  • domain object details:

  1. A parameterless constructor is required (for hibernate to reflect the object)
  2. There should be a primary key attribute without business logic
  3. Give each property a get set method
  4. The properties in the domian object can only be managed by hibernate after they are configured to the object mapping file
  5. Property is generally private scope
  • Description of object relation mapping file
    In the object relation file, some properties can not be matched. hibernate will adopt the default mechanism, such as
    If the table value does not match, use the lower case of the class as the table name
    If type is not configured, hibernate will select an appropriate type according to the attribute type of the class

There are three states of hibernate object, transformation diagram:

Interview question: if you judge the state of an object?
The main basis is: 1. Check whether the object is in session; 2. Check whether there are corresponding records in the database
Transient: no session management and no corresponding record in the database
Persistent: session management and records in the database
Off pipe / free state: no session management, but there are records in the database

  • Lazy loading:
    Brief introduction: when we query an object, by default, only the common properties of the object are returned. When the user uses the properties of the object, he will send another query to the database. This phenomenon is called lazy phenomenon
    The solution can be as follows:
  1. Show initialize hibernate.initialized (proxy object)
  2. Modify object relation file lazy override lazy=false
  3. Through the filter (web project) openSessionInView
  • Relation mapping of hibernate objects
  1. many-to-one
  2. one-to-many
    Look at a requirement: get all the students in a department by a department number (1)?
    Here, please refer to the code:
  3. one-to-one
    There are two ways of one-on-one
    (1) One to one based on primary key

schematic diagram:

(2) One to one based on foreign key

Schematic diagram:

  1. many-to-many

Students < - > the course is many to many
Customers < - > Products
Qq< - >qq group

Practice on the computer,
Please think of your own life
one-to-many
many-to-one
many-to-many
one-to-one
Four groups of object relations, and use hibernate implementation to write
The corresponding domain object and object relation mapping file are created automatically through hbm2ddl

131 original articles published, 24 praised, 20000 visitors+
Private letter follow

Posted by trilbyfish on Mon, 17 Feb 2020 00:38:56 -0800