Hibernate Set Set Mapping simple example

Source: Internet
Author: User
Tags commit constructor rollback set set

The relationship between the user table (User_set) and the E-mail table (email_set): Each user can have multiple different e-mail addresses, and for users, e-mail is a collection, which can be expressed in the user's entity class by defining the properties of a collection type.

Create two corresponding tables:

Email_set:

CREATE TABLE Email_set (
ID int (one) not NULL,
address varchar (+) NOT null
) Engine=innodb default charset= Gbk

User_set:

CREATE TABLE User_set (
ID int (one) not NULL auto_increment,
name varchar (+) NOT null default ',
primary KEY ( ID)
) engine=innodb default CHARSET=GBK;

To establish a role entity class Userset.java:

Package collect.set;

Import Java.util.HashSet;
Import Java.util.Set;

public class Userset implements java.io.Serializable {

	//fields

	private Integer ID;
	private String name;
	Private Set emails = new HashSet ();

	Constructors

	/** Default constructor *
	/Public Userset () {
	}

	/** Full constructor *
	/Public Userset (String name) {
		this.name = name;
	}

	Property accessors public

	Integer getId () {
		return this.id;
	}

	public void SetId (Integer id) {
		this.id = ID;
	}

	Public String GetName () {
		return this.name;
	}

	public void SetName (String name) {
		this.name = name;
	}

	Public Set getemails () {
		return emails;
	}

	public void Setemails (Set emails) {
		this.emails = emails;
	}

	public void Addemail (String email) {
		this.emails.add (email);
	}

	public void Removeemail (String email) {
		this.emails.remove (email);
	}
}

Resolution: Because a user can have multiple e-mail messages, and each e-mail message cannot be duplicated. Therefore, a variable of set type is defined in the Userset class to hold the e-mail message.

Establish a set type mapping file UserSet.hbm.xml:

<?xml version= "1.0" encoding= "Utf-8"?> <!
DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en"
"http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">
<!-- 
	mapping file autogenerated by MyEclipse persistence Tools---

Parse: Use the set mapping element to correlate the Email_set table with the above configuration of the set MAP element:

Name: The names of the collection properties.

Table: This collection corresponds to the name of the table (this specifies the table for which the set element corresponds Email_set).

Nested labels <key> and <element> correspond to the fields in table "Email_set", where <key> is the foreign key of table Email_set (the value is the primary key value of table User_set).

For the list collection, add a <index> tag to configure the list index.

With this set type mapping, when you insert a record in table User_set, the User_set table has one more record such as (' 1 ', ' user1 '), when the elements added in the collection properties emails, such as EMAIL1, EMAIL2, will automatically correspond to the id= ' 1 ') insert into table Email_set. For the "Modify, delete data" operation is the same, the two tables synchronously complete the update, delete operation.

Add the mapping file to the Hibernate configuration file and set up the test class Test.java:

Package collect.set;
Import Java.util.Iterator;
Import org.hibernate.Session;
Import Org.hibernate.SessionFactory;
Import org.hibernate.Transaction;

Import org.hibernate.cfg.Configuration; public class Test {public static void main (string[] args) {//configuration management Hibernate config config = ne
		W Configuration (). Configure (); Build Sessionfactory//Sessionfactory to create session sessionfactory Sessionfactory = CONFIG.BUILDSESSIONFA According to configuration

		Ctory ();
		Create instance Userset user1 = new Userset ();
		User1.setname ("user1");
		User1.addemail ("Email1");
		User1.addemail ("Email2");
		        
		User1.addemail ("Email2");
		Userset user2 = new Userset ();
		User2.setname ("User2");

		User2.addemail ("Email3");

		Define the primary key variable Integer pid;
		Add Data Session session = Sessionfactory.opensession ();
		Transaction tx = NULL;
			try {tx = Session.begintransaction ();
			Create PRIMARY KEY variable PID = (Integer) session.save (user1);
			Session.save (User2);
		Tx.commit (); } catch (RuntimeexCeption e) {if (tx! = null) tx.rollback ();
		Throw e;
		} finally {session.close ();
		}//Modify Data Session = Sessionfactory.opensession ();
		tx = NULL;
			try {tx = Session.begintransaction ();
			User1 = (userset) session.get (Userset.class, PID);
			Modify the user name User1.setname ("user1 update");
			User1.removeemail ("Email1");
			User1.addemail ("Email4");
			Session.update (user1);
		Tx.commit ();
			} catch (RuntimeException e) {if (tx! = null) tx.rollback ();
		Throw e;
		} finally {session.close ();
		}//Query data session = Sessionfactory.opensession ();
		User1 = (userset) session.get (Userset.class, PID);
		System.out.println ("User name:" + user1.getname ());
		Iterator iter = User1.getemails (). Iterator ();
		while (Iter.hasnext ()) {System.out.println ("email Name:" + (String) iter.next ());
		
		
		} session.close ();
		Delete Data session = Sessionfactory.opensession ();
		tx = NULL;
			try {tx = Session.begintransaction (); User1 = (userset) Session.get (Userset.class, PID);
			Session.delete (user1);
		Tx.commit ();
			} catch (RuntimeException e) {if (tx! = null) tx.rollback ();
		Throw e;
		} finally {session.close ();

	}//Close sessionfactory sessionfactory.close ();
 }

}

Note: Add, modify, query, delete data, this step by step to test, that is, when adding data, the other code first commented out, after the addition of the database query results, and then release the "Modify Data" section of the comments, so step by step to complete the test work. Otherwise, unexpected results occur.

Results in the database only after adding data is complete:

Empty the database and complete the "Add, modify data" results in the database:

(visible when modifying data, delete email1, add Email4)

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.