This first stores the set set in the database. is to create a new table, the primary key for the new table corresponds to another foreign key, and each value of the collection corresponds to a record, which is distinguished by the same set of data as the primary key value.
Package Test.hibernate.set;import Java.util.set;public class User {private Integer id;private String name;private Set <String> addressset;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 set<string> Getaddressset () {return addressset;} public void Setaddressset (set<string> addressset) {this.addressset = AddressSet;}}
Package Test.hibernate.set;import Java.util.hashset;import Java.util.set;import org.hibernate.session;import Org.hibernate.sessionfactory;import Org.hibernate.cfg.configuration;import Org.junit.test;public class App {private static Sessionfactory sessionfactory = new Configuration ()//.configure ()//.addclass (user.class)// Add Hibernate entity Class (loads the corresponding mapping file). Buildsessionfactory (); @Testpublic void Testsave () throws Exception {Session session = Sessionfactory.opensession (); session.begintransaction ();//--------------------------------------------// Build Object User user = new user (); user.setname ("Li Ming"); set<string> set = new Hashset<string> (), Set.add ("Guangdong province"), Set.add ("Shenzhen"); Set.add ("Futian District"); User.setaddressset (set);//save Session.save (user);//-------------------------------------------- Session.gettransaction (). commit (); Session.close ();} @Testpublic void Testget () throws Exception {Session session = Sessionfactory.opensession (); Session.begintransaction () ;//Get data user user = (user) Session.get (user.class, 1);//Display Data System.out.println (User.getid ()); System.out.println (User.getname ()); System.out.println (User.getaddressset ()); Session.gettransaction (). commit (); Session.close ();}}
<?xml version= "1.0"? ><! DOCTYPE hibernate-mapping public "-//hibernate/hibernate mapping DTD 3.0//en" "http// Hibernate.sourceforge.net/hibernate-mapping-3.0.dtd ">
Note the mapping of Set
Results of two consecutive loads
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced. Http://blog.csdn.net/lindonglian
Hibernate Mapping Collection Properties