zoukankan      html  css  js  c++  java
  • hibernate学习(设计一对多 关系 映射)

    1,配置文件:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-configuration PUBLIC
            "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
            "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    <hibernate-configuration>
        <session-factory>
        <!-- 指定连接数据库所用的驱动 -->
            <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
            <!-- 指定连接数据库的url,其中hibernate是本应用连接的数据库名 -->
            <property name="connection.url">jdbc:mysql://localhost:3306/hibernate02?useUnicode=true&amp;characterEncoding=utf-8 </property>
            <!-- 指定连接数据库的用户名 -->
            <property name="connection.username">root</property>
            <!-- 指定连接数据库的密码 -->
            <property name="connection.password">123456</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.crazy.app.domain.Person"/>
            <mapping class="org.crazy.app.domain.Address"/>
            </session-factory>
    </hibernate-configuration>

    2,写 hibernateutil 

    package lee;
    
    import org.hibernate.HibernateException;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
    import org.hibernate.cfg.Configuration;
    import org.hibernate.service.ServiceRegistry;
    
    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);
            }
    }

    3,java beans

    //父亲
    package org.crazy.app.domain;
    
    import java.util.HashSet;
    import java.util.Set;
    
    import javax.persistence.*;
    
    import org.hibernate.annotations.Cascade;
    import org.hibernate.annotations.CascadeType;
    
    @Entity
    @Table(name="person_inf")
    public class Person {
        @Id
        @Column(name="person_id")
        @GeneratedValue(strategy=GenerationType.IDENTITY)
        private Integer id;
        public Person() {
        }
        private String name;
        private  int age;
        @OneToMany(targetEntity=Address.class,mappedBy="person")
        private Set<Address> addresses=new HashSet<Address>();
        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 int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        public Set<Address> getAddresses() {
            return addresses;
        }
        public void setAddresses(Set<Address> addresses) {
            this.addresses = addresses;
        }
    }
    //----------------------------------------------------------------------
    //儿子
    package org.crazy.app.domain;
    
    import javax.persistence.*;
    
    @Entity
    @Table(name="address_inf")
    public class Address {
        @Id
        @Column(name="address_id")
        @GeneratedValue(strategy=GenerationType.IDENTITY)
        private Integer addressId;
        private String addressDetail;
        @ManyToOne(targetEntity=Person.class)
        @JoinColumn(name="person_id",referencedColumnName="person_id",nullable=false)
        private Person person;
    
        public Address(String addressDetail) {
            this.addressDetail = addressDetail;
        }
        public Integer getAddressId() {
            return addressId;
        }
        public void setAddressId(Integer addressId) {
            this.addressId = addressId;
        }
        public String getAddressDetail() {
            return addressDetail;
        }
        public void setAddressDetail(String addressDetail) {
            this.addressDetail = addressDetail;
        }
        public Person getPerson() {
            return person;
        }
        public void setPerson(Person person) {
            this.person = person;
        }
        
        
    }

    4,测试:

    package lee;
    
    import org.crazy.app.domain.Address;
    import org.crazy.app.domain.Person;
    import org.hibernate.Session;
    import org.hibernate.Transaction;
    
    
    
    public class PersonManager {
        public static void main(String[] args) {
            testCascase();
        }
        public static void testCascase(){
            Session session=HibernateUtil.currentSession();
            Transaction tx=session.beginTransaction();
            Person p=new Person();
            p.setAge(33);p.setName("abc");
            session.save(p);
            Address a=new Address("广州天河");
            a.setPerson(p);
            session.persist(a);
            Address a2=new Address("上海虹口");
            a2.setPerson(p);
            session.persist(a2);
            tx.commit();
            HibernateUtil.closeSession();
        }
    
    }

    5,运行,生成表结构 如下

  • 相关阅读:
    Linux 基本权限管理
    javaweb期末项目-stage1-part2-UML设计
    javaweb期末项目-项目结构
    javaweb期末项目-stage1-part1-需求分析(Requirements analysis)
    Data type
    Backup &recovery备份和还原
    CDI services--Scope(生命周期)&&EL.(Sp El)
    CDI services--Event(事件)
    CentOS 8.2上安装部署MongoDB 4.4
    CentOS8.2 安装部署squid代理服务器
  • 原文地址:https://www.cnblogs.com/panqingqiang/p/5074685.html
Copyright © 2011-2022 走看看