zoukankan      html  css  js  c++  java
  • 吴裕雄--天生自然轻量级JAVA EE企业应用开发Struts2Sping4Hibernate整合开发学习笔记:Hibernate_unidirectional_1-1FK

    <?xml version="1.0" encoding="GBK"?>
    <project name="hibernate" basedir="." default="">
        <property name="src" value="src"/>
        <property name="dest" value="classes"/>
    
        <path id="classpath">
            <fileset dir="../../../lib">
                <include name="**/*.jar"/>
            </fileset>
            <pathelement path="${dest}"/>
        </path>
    
        <target name="compile" description="Compile all source code">
            <delete dir="${dest}"/>
            <mkdir dir="${dest}"/>
            <copy todir="${dest}">
                <fileset dir="${src}">
                    <exclude name="**/*.java"/>
                </fileset>        
            </copy>
            <javac destdir="${dest}" debug="true" includeantruntime="yes"
                deprecation="false" optimize="false" failonerror="true">
                <src path="${src}"/>
                <classpath refid="classpath"/>
                <compilerarg value="-Xlint:deprecation"/>
            </javac>
        </target>
    
        <target name="run" description="Run the main class" depends="compile">
            <java classname="lee.PersonManager" fork="yes" failonerror="true">
                <classpath refid="classpath"/>
            </java>
        </target>
    
    </project>
    <?xml version="1.0" encoding="GBK"?>
    <!-- 指定Hibernate配置文件的DTD信息 -->
    <!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
    <!-- hibernate-configuration是配置文件的根元素 -->
    <hibernate-configuration>
        <session-factory>
            <!-- 指定连接数据库所用的驱动 -->
            <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
            <!-- 指定连接数据库的url,其中hibernate是本应用连接的数据库名 -->
            <property name="connection.url">jdbc:mysql://localhost/hibernate</property>
            <!-- 指定连接数据库的用户名 -->
            <property name="connection.username">root</property>
            <!-- 指定连接数据库的密码 -->
            <property name="connection.password">32147</property>
            <!-- 指定连接池里最大连接数 -->
            <property name="hibernate.c3p0.max_size">20</property>
            <!-- 指定连接池里最小连接数 -->
            <property name="hibernate.c3p0.min_size">1</property>
            <!-- 指定连接池里连接的超时时长 -->
            <property name="hibernate.c3p0.timeout">5000</property>
            <!-- 指定连接池里最大缓存多少个Statement对象 -->
            <property name="hibernate.c3p0.max_statements">100</property>
            <property name="hibernate.c3p0.idle_test_period">3000</property>
            <property name="hibernate.c3p0.acquire_increment">2</property>
            <property name="hibernate.c3p0.validate">true</property>
            <!-- 指定数据库方言 -->
            <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
            <!-- 根据需要自动创建数据库 -->
            <property name="hbm2ddl.auto">update</property>
            <!-- 显示Hibernate持久化操作所生成的SQL -->
            <property name="show_sql">true</property>
            <!-- 将SQL脚本进行格式化后再输出 -->
            <property name="hibernate.format_sql">true</property>
            <!-- 罗列所有持久化类的类名 -->
            <mapping class="org.crazyit.app.domain.Person"/>
            <mapping class="org.crazyit.app.domain.Address"/>
        </session-factory>
    </hibernate-configuration>
    package org.crazyit.app.domain;
    
    import java.util.*;
    
    import javax.persistence.*;
    /**
     * Description:
     * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
     * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
     * <br/>This program is protected by copyright laws.
     * <br/>Program Name:
     * <br/>Date:
     * @author  Yeeku.H.Lee kongyeeku@163.com
     * @version  1.0
     */
    @Entity
    @Table(name="address_inf")
    public class Address
    {
        // 标识属性
        @Id @Column(name="address_id")
        @GeneratedValue(strategy=GenerationType.IDENTITY)
        private int addressId;
        // 定义地址详细信息的成员变量
        private String addressDetail;
    
        // 无参数的构造器
        public Address()
        {
        }
        // 初始化全部成员变量的构造器
        public Address(String addressDetail)
        {
            this.addressDetail = addressDetail;
        }
    
        // addressId的setter和getter方法
        public void setAddressId(int addressId)
        {
            this.addressId = addressId;
        }
        public int getAddressId()
        {
            return this.addressId;
        }
    
        // addressDetail的setter和getter方法
        public void setAddressDetail(String addressDetail)
        {
            this.addressDetail = addressDetail;
        }
        public String getAddressDetail()
        {
            return this.addressDetail;
        }
    }
    package org.crazyit.app.domain;
    
    import java.util.*;
    
    import javax.persistence.*;
    /**
     * Description:
     * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
     * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
     * <br/>This program is protected by copyright laws.
     * <br/>Program Name:
     * <br/>Date:
     * @author  Yeeku.H.Lee kongyeeku@163.com
     * @version  1.0
     */
    @Entity
    @Table(name="person_inf")
    public class Person
    {
        // 标识属性
        @Id @Column(name="person_id")
        @GeneratedValue(strategy=GenerationType.IDENTITY)
        private Integer id;
        private String name;
        private int age;
        // 定义该Person实体关联的Address实体
        @OneToOne(targetEntity=Address.class)
        // 映射名为address_id的外键列,参照关联实体对应表的addres_id主键列
        @JoinColumn(name="address_id"
            , referencedColumnName="address_id" , unique=true)
        private Address address;
    
        // id的setter和getter方法
        public void setId(Integer id)
        {
            this.id = id;
        }
        public Integer getId()
        {
            return this.id;
        }
    
        // name的setter和getter方法
        public void setName(String name)
        {
            this.name = name;
        }
        public String getName()
        {
            return this.name;
        }
    
        // age的setter和getter方法
        public void setAge(int age)
        {
            this.age = age;
        }
        public int getAge()
        {
            return this.age;
        }
    
        // address的setter和getter方法
        public void setAddress(Address address)
        {
            this.address = address;
        }
        public Address getAddress()
        {
            return this.address;
        }
    }
    package lee;
    
    import org.hibernate.*;
    import org.hibernate.cfg.*;
    import org.hibernate.service.*;
    import org.hibernate.boot.registry.*;
    /**
     * Description:
     * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
     * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
     * <br/>This program is protected by copyright laws.
     * <br/>Program Name:
     * <br/>Date:
     * @author  Yeeku.H.Lee kongyeeku@163.com
     * @version  1.0
     */
    public class HibernateUtil
    {
        public static final SessionFactory sessionFactory;
    
        static
        {
            try
            {
                // 使用默认的hibernate.cfg.xml配置文件创建Configuration实例
                Configuration cfg = new Configuration()
                    .configure();
                // 以Configuration实例来创建SessionFactory实例
                ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                    .applySettings(cfg.getProperties()).build();
                sessionFactory = cfg.buildSessionFactory(serviceRegistry);
            }
            catch (Throwable ex)
            {
                System.err.println("Initial SessionFactory creation failed." + ex);
                throw new ExceptionInInitializerError(ex);
            }
        }
    
        // ThreadLocal可以隔离多个线程的数据共享,因此不再需要对线程同步
        public static final ThreadLocal<Session> session
            = new ThreadLocal<Session>();
    
        public static Session currentSession()
            throws HibernateException
        {
            Session s = session.get();
            // 如果该线程还没有Session,则创建一个新的Session
            if (s == null)
            {
                s = sessionFactory.openSession();
                // 将获得的Session变量存储在ThreadLocal变量session里
                session.set(s);
            }
            return s;
        }
    
        public static void closeSession()
            throws HibernateException
        {
            Session s = session.get();
            if (s != null)
                s.close();
            session.set(null);
        }
    }
    package lee;
    
    import org.hibernate.Transaction;
    import org.hibernate.Session;
    
    import java.util.Date;
    import java.util.Set;
    import java.util.HashSet;
    
    import org.crazyit.app.domain.*;
    /**
     * Description:
     * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
     * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
     * <br/>This program is protected by copyright laws.
     * <br/>Program Name:
     * <br/>Date:
     * @author  Yeeku.H.Lee kongyeeku@163.com
     * @version  1.0
     */
    public class PersonManager
    {
        public static void main(String[] args)
        {
            PersonManager mgr = new PersonManager();
            mgr.testPerson();
            HibernateUtil.sessionFactory.close();
        }
    
        private void testPerson()
        {
            Session session = HibernateUtil.currentSession();
            Transaction tx = session.beginTransaction();
            // 创建一个Person对象
            Person p = new Person();
            // 设置Person的name为crazyit字符串
            p.setName("crazyit");
            p.setAge(21);
            // 创建一个瞬态的Address对象
            Address a = new Address("广州天河");
            // 通过Person对象建立它自己与Address实体的关联关系
            p.setAddress(a);
            // 先持久化Address对象(对应为插入主表记录)
            session.persist(a);
            // 再持久化Person对象(对应为插入从表记录)
            session.save(p);
            tx.commit();
            HibernateUtil.closeSession();
        }
    }
  • 相关阅读:
    Windows Azure Web Site (19) Azure Web App链接到VSTS
    Windows Azure Virtual Machine (35) Azure VM通过Linked DB,执行SQL Job
    Azure PowerShell (16) 并行开关机Azure ARM VM
    Windows Azure Virtual Network (12) 虚拟网络之间点对点连接VNet Peering
    Azure ARM (21) Azure订阅的两种管理模式
    Windows Azure Platform Introduction (14) 申请海外的Windows Azure账户
    Azure ARM (20) 将非托管磁盘虚拟机(Unmanage Disk),迁移成托管磁盘虚拟机(Manage Disk)
    Azure ARM (19) 将传统的ASM VM迁移到ARM VM (2)
    Azure ARM (18) 将传统的ASM VM迁移到ARM VM (1)
    Azure Automation (6) 执行Azure SQL Job
  • 原文地址:https://www.cnblogs.com/tszr/p/12369747.html
Copyright © 2011-2022 走看看