Hibernate example of a crud operation for a persistent class containing list attributes

Source: Internet
Author: User
Tags commit garbage collection

1.hibernate.cfg.xml

The code is as follows Copy Code

<! DOCTYPE hibernate-configuration Public
"-//hibernate/hibernate Configuration DTD 3.0//en"
"Http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd" >

<session-factory>
<!--configuration Database dialect-->
<property name= "Hibernate.dialect" >org.hibernate.dialect.MySQLDialect</property>
Driver--> for <!--configuration database
<property name= "Hibernate.connection.driver_class" >com.mysql.jdbc.Driver</property>
<!--metabase User name-->
<property name= "Hibernate.connection.username" >root</property>
<!--configuration Database password-->
<property name= "Hibernate.connection.password" >root</property>
<!--configuration database URL-->
<property name= "Hibernate.connection.url" >jdbc:mysql://localhost:3306/hibernate</property>
<!--Configure the maximum capacity of the data pool-->
<property name= "Hibernate.c3p0.max_size" >20</property>
<!--Configure the minimum capacity of the data pool-->
<property name= "Hibernate.c3p0.min_size" >1</property>
<!--The timeout limit for configuring data links-->
<property name= "Hibernate.c3p0.timeout" >5000</property>
<!--the console shows whether the background print execution SQL-->
<property name= "Hibernate.show_sql" >true</property>
<!--whether to display the printed SQL--> in a friendly format
<property name= "Hibernate.format_sql" >true</property>
<!--Print some of the supporting annotations-->
<property name= "Hibernate.use_sql_comments" >true</property>

<property name= "Hibernate.c3p0.max_statements" >100</property>
<property name= "Hibernate.c3p0.idle_test_period" >3000</property>
<property name= "Hibernate.c3p0.acquire_increment" >2</property>
<property name= "Hibernate.c3p0.validate" >true</property>
<!--How to configure data manipulation-->
<property name= "Hbm2ddl.auto" >update</property>
<!--Add the mapping file for the person above US-->
<mapping resource= "Org/rudiment/hibernate/person.hbm.xml"/>
</session-factory>


2. Persistent class person

The code is as follows Copy Code

Package Org. Rudiment.hibernate;

Import java.util.ArrayList;
Import java.util.List;

public class Person {
Private Integer ID;
private String name;
private int age;
Private list<string> schools = new arraylist<string> ();

Public Integer getId () {
return ID;
}
public void SetId (Integer id) {
This.id = ID;
}
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
public int getage () {
return age;
}
public void Setage (int age) {
This.age = age;
}
Public list<string> Getschools () {
return schools;
}
public void Setschools (list<string> schools) {
This.schools = schools;
}
}

3. Person.cfg.xml

The code is as follows Copy Code

<?xml version= "1.0"?>
<! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en"
"Http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<!--generated 2013-9-8 20:44:11 by Hibernate Tools 3.4.0.CR1-->
<class name= "org. Rudiment.hibernate.Person "table=" >
<id name= "id" type= "Java.lang.Integer" >
<column name= "ID"/>
<generator class= "native"/>
</id>
<property name= "name" type= "Java.lang.String" >
<column name= "Name"/>
</property>
<property name= "age" type= "int" >
<column name= "Age"/>
</property>
<list name= "Schools" inverse= "false" table= "SCHOOL" lazy= "true" >
<key>
<column name= "ID"/>
</key>
<list-index></list-index>
<element type= "Java.lang.String" >
<column name= "SCHOOLS"/>
</element>
</list>
</class>

4. Operation of the persistence of the class of functional class Personhandler

The code is as follows Copy Code

Package Org. Rudiment.hibernate;

Import java.util.ArrayList;
Import java.util.List;

Import Org.hibernate.Hibernate;
Import org.hibernate.Session;
Import Org.hibernate.SessionFactory;
Import org.hibernate.Transaction;
Import org.hibernate.cfg.Configuration;
Import Org.hibernate.service.ServiceRegistry;
Import Org.hibernate.service.ServiceRegistryBuilder;

public class Personhandler {

Insert Record
public static void InsertPerson (person p)
{
Configuration conf = new Configuration ();
Conf.configure ();
serviceregistry sr = new Serviceregistrybuilder (). Applysettings (Conf.getproperties ()). Buildserviceregistry ();
Sessionfactory SF = Conf.buildsessionfactory (SR);
Session Sess = Sf.opensession ();
Transaction tx = Sess.begintransaction ();
Sess.save (P);
Tx.commit ();
Sess.close ();
}

Update records
public static void Updateperson (person p)
{
Configuration conf = new Configuration ();
Conf.configure ();
serviceregistry sr = new Serviceregistrybuilder (). Applysettings (Conf.getproperties ()). Buildserviceregistry ();
Sessionfactory SF = Conf.buildsessionfactory (SR);
Session Sess = Sf.opensession ();
Transaction tx = Sess.begintransaction ();
Sess.update (P);
Tx.commit ();
Sess.close ();
}

Delete a record
public static void Deleteperson (person p)
{
Configuration conf = new Configuration ();
Conf.configure ();
serviceregistry sr = new Serviceregistrybuilder (). Applysettings (Conf.getproperties ()). Buildserviceregistry ();
Sessionfactory SF = Conf.buildsessionfactory (SR);
Session Sess = Sf.opensession ();
Transaction tx = Sess.begintransaction ();
Sess.delete (P);
Tx.commit ();
Sess.close ();
}

Query records
public static person Queryperson (int id)
{
Configuration conf = new Configuration ();
Conf.configure ();
serviceregistry sr = new Serviceregistrybuilder (). Applysettings (Conf.getproperties ()). Buildserviceregistry ();
Sessionfactory SF = Conf.buildsessionfactory (SR);
Session Sess = Sf.opensession ();
Person P = (person) sess.get (Person.class, id);
Sess.close ();
return p;
}


public static void Main (string[] args)
{
Person p = new person ();
/*
Insert Record
P.setname ("Itkezhan");
P.setage (1);
List<string> schools = new arraylist<string> ();
Schools.add ("primary School");
Schools.add ("Junior High School");
Schools.add ("High School");
P.setschools (schools);
InsertPerson (P);
*/

/*
Update records
The 5 in parentheses corresponds to the ID in the person table
p = Queryperson (5);
P.setage (10);
P.setname ("It Inn");
Updateperson (P);
*/

/*
Delete a record
The 5 in parentheses corresponds to the ID in the person table
p = Queryperson (5);
Deleteperson (P);
*/

}
}


Note:

1. Simply personhandler the first comment block of the main method of this class, a new record will be inserted into the person table named Hibernate.

  code is as follows copy code

mysql> use hibernate;
Database changed
mysql> select * from person;
+----+----------+------+
| ID | name     | age  |
+----+----------+------+
|  5 | Itkezhan |    1 |
+----+----------+------+
1 row in Set (0.00 sec)

Mysql> select * from school;
+----+---------+----- +
| ID | SCHOOLS | IDX |
+----+---------+-----+
|  5 | Primary     |   0 |
|  5 | Junior     |& nbsp;  1 |
|  5 | High school     |   2 |
+----+---------+-----+
3 rows in Set (0.00 sec)


2. Only Personhandler the second comment block of the main method of this class, will update the query's record to the person table with the database name hibernate.

  code is as follows copy code

mysql> select * from person;
+----+--------+------+
| ID | name   | age  |
+----+--------+------+
|  5 | It Inn |   10 |
+----+--------+------+
1 row in Set (0.00 sec)

Mysql> select * from school;
+----+---------+-----+< br> | ID | SCHOOLS | IDX |
+----+---------+-----+
|  5 | Primary     |   0 |
|  5 | Junior     |& nbsp;  1 |
|  5 | High school     |   2 |
+----+---------+-----+
3 rows in Set (0.00 sec)

3. Canceling only the third comment block of the main method of Personhandler this class will delete the records from the query

Here are some of the things to note about these methods:

In saying these methods, we must first agree on some words meaning, the persisted object in hibernate supports several object states as follows:
Transient: objects are created by the new operator, and objects that have not been associated with the Hibernate session are considered transient. Transient objects are not persisted to the database and are not given persistent identities. If a transient object reference is lost in the program, the transient object is destroyed by the garbage collection mechanism. You can change it to a persisted state by using the hibernate session.
Persistence: The object is on the Hibernate Session Association. Modifications to this object's properties affect the data content of the database.
To take off: the object that has been lasting. This object is called a Hibernate because it is detached from the session.
For more detailed concepts, see: Lightweight Java EE business application P386

=========================save () and Persist () method ============================
Hibernate provides a persist () approach that is almost exactly like the Save () feature, on the one hand, to take care of JPA usage habits. On the other hand, there is a difference between the save () and Persist () methods: When a persisted object is saved using the Save () method, the method returns the identity property of the persisted object (that is, the primary key value of the corresponding record), but when the persisted object is saved using the persist () The method does not have any return values. Because the Save () method needs to return the identity property value of the persisted object immediately, the program execution Save () method inserts the data for the persisted object into the database immediately, while persist () guarantees that it is not immediately converted to an INSERT statement when it is invoked outside of a transaction. This function is very useful, especially when we encapsulate a long session process, the persist () method is particularly important.

=========================load () and get () method ============================
The main difference between the load () method and The Get () method is whether to delay loading, using the load () method will have deferred loading, the load () method does not immediately access the database, and the load () method may return an uninitialized proxy object when the record you are trying to load does not exist; Method always accesses the database immediately, and the Get () method returns null directly when the record you are trying to load does not exist

========================= Remove the Pipe object again use the attention item =========================
For a persistent object that has been persisted but now is out of session management, we call it in a disconnected state. When we modify the state of a pipe-off object, the program should use a new session to save the changes. Hibernate provides methods such as update (), merge (), and Updateorsave () to save these modifications. When we save this change with another session, the off-pipe object returns to the session management again and returns to the persistent state again.

========================= Update () and merge () methods =========================
When you need to use Update to save a program's changes to a persisted object, if it is not clear if the object was persisted, the program can choose to use the Updateorsave () method, which automatically determines whether the object was persisted and, if it has persisted, uses the update () operation; Otherwise, the Save () action is used.
The merge () method can also save a program's modifications to the off-pipe object to the database, but the most significant difference between the merge () and update () methods is that the merge () method does not persist the given object. For example, when we execute Session.update (a) code, a object will become persisted, and after executing Session.merge (a) code, a object is still not persisted, a object is still not associated with the session

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.