Delete the table in the test database first:
Create a new web project and write the code:
Person. Java:
public class Person {private int id;private String name;private int age;private Set<String> schools=new HashSet<String>();public int getId() {return id;}public void setId(int 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 Set<String> getSchools() {return schools;}public void setSchools(Set<String> schools) {this.schools = schools;}}
Person. HBM. xml:
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
The property ing of the Set set is a little different from that of the list, because the set is unordered and cannot be repeated.<Set.../>You do not need to use the <list-index.../> sub-element to map the index column of the collection element. <Element.../> An element has a not-null attribute. The default value of this attribute is false, indicating that the column can be empty by default.
Test. Java:
Public class test {public static void main (string [] ARGs) {person p1 = new person (); p1.setname ("Tom"); p1.setage (20 ); set <string> schools1 = new hashset <string> (); schools1.add (""); schools1.add (""); p1.setschools (schools1 ); person P2 = new person (); p2.setname ("Jack"); p2.setage (23); set <string> schools2 = new hashset <string> (); schools2.add (""); schools2.add (""); schools2.add (""); p2.setschools (schools2); Session session = hibernatesessionfactory. getsession (); transaction TXT = session. begintransaction (); Session. save (P1); Session. save (P2); TXT. commit (); hibernatesessionfactory. closesession ();}}
Run test. Java to view the database:
Compare the list and set attributes: the elements in the list set are ordered, while those in the Set set are not ordered. When a set attribute is stored in another table, the list set attribute can use a foreign key associated with the persistence class; the column and the index column of the Set element are used as the joint primary key; but the Set set has no index column, the external key and element column of the associated persistence class are usedJoint primary key, Provided that the element Column cannot be empty.