∪∩deniable Design

个人JAVA版GAE(google app engine),struts2+jpa+jQuery开发,互相交流 http://iunbug.appspot.com/
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

Hibernate学习笔记(二)-- 实体映射

Posted on 2008-09-01 16:12 ∪∩BUG 阅读(574) 评论(4)  编辑  收藏 所属分类: Hibernate学习笔记

关于如何配置请参看:Hibernate学习笔记(一)--用MyEclipse 6.5+MySQL 5.0的环境跑起来
准备:建表

用MySQL在名为STMS数据库中建表persons

 src/org.lxh.hibernate.Contact.java

 1package org.lxh.hibernate;
 2
 3/**
 4 * @author ∪∩BUG E-mail: tidelgl@163.com
 5 * @version Aug 30, 2008 8:02:48 PM 
 6 */

 7public class Contact {
 8
 9    private String address;
10    private String zipcode;
11    private String tel;
12
13    public String getAddress() {
14        return address;
15    }

16
17    public void setAddress(String address) {
18        this.address = address;
19    }

20
21    public String getZipcode() {
22        return zipcode;
23    }

24
25    public void setZipcode(String zipcode) {
26        this.zipcode = zipcode;
27    }

28
29    public String getTel() {
30        return tel;
31    }

32
33    public void setTel(String tel) {
34        this.tel = tel;
35    }

36
37}

38


 src/org.lxh.hibernate.Name.java

 1package org.lxh.hibernate;
 2
 3/**
 4 * @author ∪∩BUG E-mail: tidelgl@163.com
 5 * @version Aug 30, 2008 7:59:53 PM 
 6 */

 7public class Name {
 8
 9    private String firstname;
10    private String lastname;
11
12    public String getFirstname() {
13        return firstname;
14    }

15
16    public void setFirstname(String firstname) {
17        this.firstname = firstname;
18    }

19
20    public String getLastname() {
21        return lastname;
22    }

23
24    public void setLastname(String lastname) {
25        this.lastname = lastname;
26    }

27
28}

29

 src/org.lxh.hibernate.Persons.java

 1package org.lxh.hibernate;
 2/** 
 3 * @author ∪∩BUG E-mail: tidelgl@163.com
 4 * @version Aug 30, 2008 8:04:57 PM 
 5 * @本类包含Nane类和Contact类
 6 */

 7public class Persons {
 8    private int id;
 9    private Name name;
10    private Contact contact;
11
12    public int getId() {
13        return id;
14    }

15
16    public void setId(int id) {
17        this.id = id;
18    }

19
20    public Name getName() {
21        return name;
22    }

23
24    public void setName(Name name) {
25        this.name = name;
26    }

27
28    public Contact getContact() {
29        return contact;
30    }

31
32    public void setContact(Contact contact) {
33        this.contact = contact;
34    }

35
36}

37


 src/org.lxh.hibernate.PersonsOperate.java

 1package org.lxh.hibernate;
 2
 3import java.util.List;
 4
 5import org.hibernate.Query;
 6import org.hibernate.Session;
 7import org.hibernate.SessionFactory;
 8import org.hibernate.cfg.Configuration;
 9
10/**
11 * @author ∪∩BUG E-mail: tidelgl@163.com
12 * @version Aug 30, 2008 8:55:43 PM @ 具体操作Hibernate的类
13 */

14public class PersonsOperate {
15    // 在Hibernate中所有的操作都是通过Session来完成
16    private Session session;
17
18    // Session 是一个接口,必须实例化
19    // 在构造方法中实例实化Session对象
20    public PersonsOperate() {
21        // 找到Hibernae配置文件
22        Configuration config = new Configuration().configure();
23
24        // 从全局文件中取出SessionFactory
25        SessionFactory factory = config.buildSessionFactory();
26
27        // 从sessionFactory中取出一个session
28        this.session = factory.openSession();
29    }

30
31    // 所有的操作都是通过Session进行
32    // (1)增加操作
33    public void insert(Persons p) {
34        // 将数据存放到数据库中
35        this.session.save(p);
36
37        // 事务提交
38        this.session.beginTransaction().commit();
39    }

40
41    // 通过HQL查询全部数据
42    public List queryAll() {
43        String hql = "FROM Persons as p";
44        Query q = this.session.createQuery(hql);
45        List l = q.list();
46        return l;
47    }

48}

49


 src/org.lxh.hibernate.Persons.hbm.xml

 1xml version="1.0" encoding="utf-8"?>
 2DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 3"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 4
 7<hibernate-mapping>
 8    <class name="org.lxh.hibernate.Persons" table="persons"
 9        catalog="stms">
10        <id name="id" type="java.lang.Integer">
11            <column name="id" />
12            <generator class="assigned" />
13        id>
14        
19        <component name="name" class="org.lxh.hibernate.Name">
20            <property name="firstname" type="java.lang.String">
21                <column name="firstname" length="20" not-null="true" />
22            property>
23            <property name="lastname" type="java.lang.String">
24                <column name="lastname" length="20" not-null="true" />
25            property>
26        component>
27        <component name="contact" class="org.lxh.hibernate.Contact">
28
29            <property name="address" type="java.lang.String">
30                <column name="address" length="20" not-null="true" />
31            property>
32            <property name="zipcode" type="java.lang.String">
33                <column name="zipcode" length="6" not-null="true" />
34            property>
35            <property name="tel" type="java.lang.String">
36                <column name="tel" length="20" />
37            property>
38        component>
39    class>
40hibernate-mapping>
41

 src/org.lxh.hibernate.TestDemo.java

 1package org.lxh.hibernate;
 2
 3import java.util.Iterator;
 4import java.util.List;
 5
 6import sun.security.action.GetBooleanAction;
 7
 8/** 
 9 * @author ∪∩BUG E-mail: tidelgl@163.com
10 * @version Aug 30, 2008 8:55:03 PM 
11 * @测试类
12 */

13public class TestDemo {
14
15    /**
16     * @param args
17     */

18    public static void main(String[] args) {
19        
20            PersonsOperate po = new PersonsOperate();
21            /*
22            //测试插入数据
23            Persons p = new Persons();
24            Name n = new Name();
25            Contact c = new Contact();
26            
27            n.setFirstname("My");
28            n.setLastname("SQL");
29            
30            c.setAddress("mysql.com");
31            c.setTel("12345678");
32            c.setZipcode("54321");
33            
34            p.setId(1);
35            p.setName(n);
36            p.setContact(c);
37            
38            po.insert(p);
39            */

40            
41            //测试查询全部数据
42            List l = po.queryAll();
43            Iterator iter = l.iterator();
44            while (iter.hasNext()) {
45                Persons p = (Persons)iter.next();
46                System.out.println("ID:\t" + p.getId());
47                System.out.println("FIRSTNAME:\t" + p.getName().getFirstname());
48                System.out.println("LASTNAME:\t" + p.getName().getLastname());
49                System.out.println("ADDRESS:\t" + p.getContact().getAddress());
50                System.out.println("TEL:\t" + p.getContact().getTel());
51                System.out.println("ZIPCODE:\t" + p.getContact().getZipcode());
52                System.out.println("----------------------------------------------");
53            }

54    }

55
56}

57

src/hibernate.cfg.xml

 1xml version='1.0' encoding='UTF-8'?>
 2DOCTYPE hibernate-configuration PUBLIC
 3          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 4          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 5
 6
 7<hibernate-configuration>
 8
 9    <session-factory>
10        <property name="connection.username">rootproperty>
11        <property name="connection.url">
12            jdbc:mysql://localhost:3306/STMS
13        property>
14        <property name="dialect">
15            org.hibernate.dialect.MySQLDialect
16        property>
17        <property name="myeclipse.connection.profile">
18            MySql_localhost
19        property>
20        <property name="connection.password">rootproperty>
21        <property name="connection.driver_class">
22            com.mysql.jdbc.Driver
23        property>
24        <property name="show_sql">trueproperty>
25
26        
27        <mapping resource="org/lxh/hibernate/Persons.hbm.xml" />
28
29    session-factory>
30
31hibernate-configuration>

 

例子结构:


评论

# re: Hibernate学习笔记(二)-- 实体映射   回复  更多评论   

2008-09-01 17:30 by ∪∩BUG
感觉HQL非常好使,以后得专门学习学习.

# re: Hibernate学习笔记(二)-- 实体映射   回复  更多评论   

2008-09-05 10:42 by tl
component是个啥属性啊,不懂

# re: Hibernate学习笔记(二)-- 实体映射   回复  更多评论   

2008-09-05 16:41 by ∪∩BUG

组件(Component)是一个被包含的对象,在持久化的过程中,它被当作值类型,而并非一个实体的引用。在这篇文档中,组件这一术语指的是面向对象的合成概念(而并不是系统构架层次上的组件的概念)。举个例子, 你对人(Person)这个概念可以像下面这样来建模:

 1public class Person {
 2    private java.util.Date birthday;
 3    private Name name;
 4    private String key;
 5    public String getKey() {
 6        return key;
 7    }

 8    private void setKey(String key) {
 9        this.key=key;
10    }

11    public java.util.Date getBirthday() {
12        return birthday;
13    }

14    public void setBirthday(java.util.Date birthday) {
15        this.birthday = birthday;
16    }

17    public Name getName() {
18        return name;
19    }

20    public void setName(Name name) {
21        this.name = name;
22    }

23    
24    
25}

26
 1public class Name {
 2    char initial;
 3    String first;
 4    String last;
 5    public String getFirst() {
 6        return first;
 7    }

 8    void setFirst(String first) {
 9        this.first = first;
10    }

11    public String getLast() {
12        return last;
13    }

14    void setLast(String last) {
15        this.last = last;
16    }

17    public char getInitial() {
18        return initial;
19    }

20    void setInitial(char initial) {
21        this.initial = initial;
22    }

23}

24

在持久化的过程中,姓名(Name)可以作为人(Person)的一个组件。需要注意的是:你应该为姓名的持久化属性定义getter和setter方法,但是你不需要实现任何的接口或申明标识符字段。

以下是这个例子的Hibernate映射文件:

 1<class name="eg.Person" table="person">
 2    <id name="Key" column="pid" type="string">
 3        <generator class="uuid"/>
 4    </id>
 5    <property name="birthday" type="date"/>
 6    <component name="Name" class="eg.Name"> <!-- class attribute optional -->
 7        <property name="initial"/>
 8        <property name="first"/>
 9        <property name="last"/>
10    </component>
11</class>
12

人员(Person)表中将包括pid, birthday, initial, firstlast等字段。

就像所有的值类型一样, 组件不支持共享引用。 换句话说,两个人可能重名,但是两个Person对象应该包含两个独立的Name对象,只不过这两个Name对象具有“同样”的值。 组件的值可以为空,其定义如下。 每当Hibernate重新加载一个包含组件的对象,如果该组件的所有字段为空,Hibernate将假定整个组件为空。 在大多数情况下,这样假定应该是没有问题的。

组件的属性可以是任意一种Hibernate类型(包括集合, 多对多关联, 以及其它组件等等)。嵌套组件不应该被当作一种特殊的应用(Nested components should not be considered an exotic usage)。 Hibernate倾向于支持细致的(fine-grained)对象模型。

<component> 元素还允许有 <parent>子元素,用来表明component类中的一个属性是指向包含它的实体的引用。

 1<class name="eg.Person" table="person">
 2    <id name="Key" column="pid" type="string">
 3        <generator class="uuid"/>
 4    </id>
 5    <property name="birthday" type="date">
 6    <component name="Name" class="eg.Name" unique="true">
 7        <parent name="namedPerson"/> <!-- reference back to the Person -->
 8        <property name="initial"/>
 9        <property name="first"/>
10        <property name="last"/>
11    </component&gt;
12</class>
13

# re: Hibernate学习笔记(二)-- 实体映射   回复  更多评论   

2009-11-17 16:05 by jb
hao

只有注册用户登录后才能发表评论。


网站导航: