首页 > 代码库 > hibernate

hibernate

 

 1 package hib;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 import org.hibernate.Session;
 7 import org.hibernate.SessionFactory;
 8 import org.hibernate.cfg.Configuration;
 9 
10 public class PersonManager {
11     private void createAndStroePerson() {
12         //打开线程安全的session
13         Configuration conf = new Configuration().configure();
14         //用Configuration创建SessionFactory
15         SessionFactory sf = conf.buildSessionFactory();
16         //用SessionFactory打开Session
17         Session sess = sf.openSession();
18         Person p = new Person();
19         p.setName("Tom");
20         p.setAge(20); 
21         List<String> schools = new ArrayList<String>();
22         schools.add("小学");
23         schools.add("中学");
24         p.setSchools(schools);
25         sess.save(p);
26         sess.close();
27         sf.close();
28     }
29 }

 

 

 1 package hib;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 public class Person {
 7     private int id;
 8     public int getId() {
 9         return id;
10     }
11     public void setId(int id) {
12         this.id = id;
13     }
14     public String getName() {
15         return name;
16     }
17     public void setName(String name) {
18         this.name = name;
19     }
20     public int getAge() {
21         return age;
22     }
23     public void setAge(int age) {
24         this.age = age;
25     }
26     public List<String> getSchools() {
27         return this.schools;
28     }
29     public void setSchools(List<String> schools) {
30         this.schools = schools;
31     }
32     private String name;
33     private int age;
34     private List<String> schools = new ArrayList<String>();
35     
36 }

 

 1 <?xml version="1.0"  encoding="UTF-8"?>    
 2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
 3 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
 4 
 5 <hibernate-mapping package="hib">
 6     <class name="Person" table="Person_inf">
 7         <id name="id" column="Person_id" type="int">
 8             <generator class="identity" />
 9         </id>
10         <property name="name" type="string" />
11         <property name="age" type="int" />
12         <list name="schools" table="schools">
13             <!-- 外键列-->
14             <key column="personid" not-null="true"/>
15             <!-- 索引列 -->
16             <list-index column="list_order"/>
17             <!-- 数据列 -->
18             <element type="string" column="school_name" />
19         </list>
20     </class>
21 </hibernate-mapping>

 

hibernate