Example of CRUD operations for persistence classes with List attributes in Hibernate

Source: Internet
Author: User

This article will introduce the CRUD operation examples of persistence classes with List attributes in Hibernate. If you are interested, please refer to them.

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>

<Hibernate-configuration>
<Session-factory>
<! -- Configure database Dialect -->
<Property name = "hibernate. dialect"> org. hibernate. dialect. MySQLDialect </property>
<! -- Configure the database driver -->
<Property name = "hibernate. connection. driver_class"> com. mysql. jdbc. Driver </property>
<! -- Configure the database username -->
<Property name = "hibernate. connection. username"> root </property>
<! -- Configure the Database Password -->
<Property name = "hibernate. connection. password"> root </property>
<! -- Configure the 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>
<! -- Configure the timeout threshold for data links -->
<Property name = "hibernate. c3p0. timeout"> 5000 </property>
<! -- Display whether the executed SQL is printed in the background on the console -->
<Property name = "hibernate. show_ SQL"> true </property>
<! -- Whether to display printed SQL statements in a friendly format -->
<Property name = "hibernate. format_ SQL"> true </property>
<! -- Print some auxiliary comments -->
<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>
<! -- Configure the data operation method -->
<Property name = "hbm2ddl. auto"> update </property>
<! -- Add the above Person ing file -->
<Mapping resource = "org/Rudiment/hibernate/Person. hbm. xml"/>
</Session-factory>
</Hibernate-configuration>


2. Persistence 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 -->
<Hibernate-mapping>
<Class name = "org. Rudiment. hibernate. Person" table = "PERSON">
<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>
</Hibernate-mapping>

4. PersonHandler, a function class of the Operation persistence class

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 ("Elementary School ");
Schools. add ("Junior High School ");
Schools. add ("High School ");
P. setSchools (schools );
InsertPerson (p );
*/

/*
// Update records
// 5 in the brackets corresponds to the ID in the Person table.
P = queryPerson (5 );
P. setAge (10 );
P. setName ("IT Inn ");
UpdatePerson (p );
*/

/*
// Delete a record
// 5 in the brackets corresponds to the ID in the Person table.
P = queryPerson (5 );
DeletePerson (p );
*/

}
}


Note:

1. Only cancel the first comment block of the main method of the PersonHandler class and insert a new record to the Person table named hibernate in the database.

The 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 School | 0 |
| 5 | Junior High School | 1 |
| 5 | high school | 2 |
+ ---- + --------- + ----- +
3 rows in set (0.00 sec)


2. only remove the second comment block of the main method of the PersonHandler class, and update the queried records to the Person table named hibernate in the database.

The 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;
+ ---- + --------- + ----- +
| ID | SCHOOLS | idx |
+ ---- + --------- + ----- +
| 5 | Primary School | 0 |
| 5 | Junior High School | 1 |
| 5 | high school | 2 |
+ ---- + --------- + ----- +
3 rows in set (0.00 sec)

3. Only cancel the third comment block of the main method of the PersonHandler class, and the query records will be deleted.

The following are some notes for these methods:

When talking about these methods, we need to specify the meanings of some words. Persistence objects in Hibernate support the following object states:
Transient: objects created by the new operator and not associated with the Hibernate Session are considered to be in transient state. The transient object will not be persisted into the database, nor will it be assigned a persistent identifier. If the transient object reference is lost in the program, the transient object will be destroyed by the garbage collection mechanism. You can use Hibernate Session to change it to a persistent state.
Persistence: the object is associated with the Hibernate Session. Modification to this object attribute will affect the data content of the database.
Unmanageable: objects that once existed. Because it is out of association with the Hibernate Session, this object is called "out of tube.
For more information, see section 6

====================================== Save () and persist () method ==================================
Hibernate provides a persist () method that is almost similar to the save () function. On the one hand, it aims to take care of the usage habits of JPA. On the other hand, there is another difference between the save () and persist () Methods: when you use the save () method to save a persistent object, this method returns the identifier attribute of the persistence object (that is, the primary key value of the corresponding record). However, when the persist () method is used to save the persistence object, this method does not return any value. Because the save () method needs to immediately return the identifier attribute value of the Persistent object, the program executes the save () method to immediately Insert the data corresponding to the persistent object into the database; and persist () this function is useful to ensure that it is not immediately converted into an insert statement when it is called outside a transaction. Especially when we encapsulate a long session flow, 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. The load () method will have the delayed loading function, and the load () method will not access the database immediately, when the record to be loaded does not exist, the load () method may return an uninitialized proxy object, while the get () method always accesses the database immediately. When the record to be loaded does not exist, the get () method returns null directly.

= ========================
For a persistent object that has been persisted but is now out of Session management, we call it in the unmanaged state. After modifying the status of the unmanaged object, the program should use the new Session to save the changes. Hibernate provides update (), merge (), and updateOrSave () Methods to save these changes. When we use another Session to save this modification, the unmanaged object will return to the Session management again, and will return to the persistent state again.

====================================== Update () and merge () method ======================================
When you need to use update to save the modifications made by the program to the persistent object, if you do not know whether the object has been persisted, you can use the updateOrSave () method, this method automatically determines whether the object has been persistent. If it has been persistent, update () is used; otherwise, save () is used.
The merge () method can also save the modifications made by the program to the database, but the biggest difference between the merge () method and the update () method is: merge () the method does not persistently specify objects. For example, when we execute session. after the update (a) code is executed, object a becomes persistent and the session is executed. after merge (a) code, object a is still not in the persistent state and object a is not associated with the Session.

 

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.