zoukankan      html  css  js  c++  java
  • Hibernate学习笔记3.1(Hibernate关系映射)

    主要指对象之间的关系

    1.一对一关联

    一对一单项外键关联

     比如说一夫一妻

    Wifi.java

    package com.bjsxt.hibernate;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    
    @Entity
    public class Wife {
        private int id;
        private String name;
        
        @Id
        @GeneratedValue
        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;
        }
        
    }

    Huaband.java

    package com.bjsxt.hibernate;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.JoinColumn;
    import javax.persistence.OneToOne;
    
    @Entity
    public class Husband {
        private int id;
        private String name;
        private Wife wife;
        @Id
        @GeneratedValue
        public int getId() {
            return id;
        }
        
        public String getName() {
            return name;
        }
        @OneToOne
        @JoinColumn(name="wifeId")
        public Wife getWife() {
            return wife;
        }
        public void setId(int id) {
            this.id = id;
        }
        public void setName(String name) {
            this.name = name;
        }
        public void setWife(Wife wife) {
            this.wife = wife;
        }
        
    }

    hibernate.cfg.xml

    <?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>
            <property name="connection.url">jdbc:mysql://localhost/hibernate</property>
            <property name="connection.username">root</property>
            <property name="connection.password">bjsxt</property>
            <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
           <!--
            <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
            <property name="connection.url">jdbc:oracle:thin:@localhost:1521:SXT</property>
            <property name="connection.username">scott</property>
            <property name="connection.password">tiger</property>
              <property name="dialect">org.hibernate.dialect.OracleDialect</property>
           -->
    
            <!-- JDBC connection pool (use the built-in) -->
            <property name="connection.pool_size">1</property>
    
            
    
            <!-- Enable Hibernate's automatic session context management -->
            <property name="current_session_context_class">thread</property>
    
            <!-- Disable the second-level cache  -->
            <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    
            <!-- Echo all executed SQL to stdout -->
            <property name="show_sql">true</property>
            <property name="format_sql">true</property>
    
            <!-- Drop and re-create the database schema on startup
            <property name="hbm2ddl.auto">update</property>
             -->
            <!--   -->
            <mapping resource="com/bjsxt/hibernate/Student.hbm.xml"/>
            <mapping resource="com/bjsxt/hibernate/StuIdCard.hbm.xml"/>
            <mapping class="com.bjsxt.hibernate.Husband"/>
            <mapping class="com.bjsxt.hibernate.Wife"/>
    
        </session-factory>
    
    </hibernate-configuration>

    test.java关键代码

    @Test
        public void testSchemaExport() {
            new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);
        }

     实际建表关系

        @OneToOne
        @JoinColumn(name="wifeId")
        public Wife getWife() {
            return wife;
        }
        public void setId(int id) {
            this.id = id;
        }

    上面可以指定生成的列名

    2.单向关联

    Student.java

    package com.bjsxt.hibernate;
    
    public class Student {
        
        private int id;
        private String name;
        
        private int age;
        private String sex;
        private boolean good;
        public boolean isGood() {
            return good;
        }
        public void setGood(boolean good) {
            this.good = good;
        }
        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 String getSex() {
            return sex;
        }
        public void setSex(String sex) {
            this.sex = sex;
        }
        
        
        
    }

    StuIdCard.java

    package com.bjsxt.hibernate;
    
    public class StuIdCard {
        private int id;
        private String num;
        private Student student;
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getNum() {
            return num;
        }
        public void setNum(String num) {
            this.num = num;
        }
        public Student getStudent() {
            return student;
        }
        public void setStudent(Student student) {
            this.student = student;
        }
        
    }

    StuIdCard.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">
    
    <hibernate-mapping>
        <class name="com.bjsxt.hibernate.StuIdCard">
            <id name="id">
                <generator class="native"></generator>
            </id>
            
            <property name="num"/>
            <many-to-one name="student" column="studentId" unique="true"></many-to-one>
        </class>
        
    </hibernate-mapping>

    从字面上看是多对一 其实后面指定了unique 所以实际上是一对一

    关系图

    2.一对一双向外键关联

    直接写@onetoone的话会导致产生两个外键

    Husband.java

    package com.bjsxt.hibernate;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.JoinColumn;
    import javax.persistence.OneToOne;
    
    @Entity
    public class Husband {
        private int id;
        private String name;
        private Wife wife;
        @Id
        @GeneratedValue
        public int getId() {
            return id;
        }
        
        public String getName() {
            return name;
        }
        @OneToOne
        @JoinColumn(name="wifeId")
        public Wife getWife() {
            return wife;
        }
        public void setId(int id) {
            this.id = id;
        }
        public void setName(String name) {
            this.name = name;
        }
        public void setWife(Wife wife) {
            this.wife = wife;
        }
        
    }

     Wife.java

    package com.bjsxt.hibernate;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.OneToOne;
    
    @Entity
    public class Wife {
        private int id;
        private String name;
        private Husband husband;
        @OneToOne(mappedBy="wife")      //在对方那里设置
        public Husband getHusband() {
            return husband;
        }
        public void setHusband(Husband husband) {
            this.husband = husband;
        }
        @Id
        @GeneratedValue
        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;
        }
        
    }

    只要有双向关联,必须设@OneToOne(mappedBy="wife")

    告诉hibernate对方那里是主导

    2.XML设置

    Student.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">
    
    <hibernate-mapping>
        <class name="com.bjsxt.hibernate.Student" dynamic-update="true">
            <id name="id">
                <generator class="native"></generator>
            </id>
            
            <property name="name"></property>
            <property name="age" />
            <property name="sex" />
            <property name="good" type="yes_no"></property>
            <one-to-one name="stuIdCard" property-ref="student"></one-to-one>
        </class>
        
    </hibernate-mapping>

    一对一单向双向的区别:在数据库没什么区别 但是在Java程序中有区别 单向和双向的区别能否靠对方找到自己

    4.一对一单向主键关联

    Husband.java

    package com.bjsxt.hibernate;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.JoinColumn;
    import javax.persistence.OneToOne;
    import javax.persistence.PrimaryKeyJoinColumn;
    
    @Entity
    public class Husband {
        private int id;
        private String name;
        private Wife wife;
        @Id
        @GeneratedValue
        public int getId() {
            return id;
        }
        
        public String getName() {
            return name;
        }
        @OneToOne
        @PrimaryKeyJoinColumn
        public Wife getWife() {
            return wife;
        }
        public void setId(int id) {
            this.id = id;
        }
        public void setName(String name) {
            this.name = name;
        }
        public void setWife(Wife wife) {
            this.wife = wife;
        }
        
    }

    wifi.java

    package com.bjsxt.hibernate;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    
    @Entity
    public class Wife {
        private int id;
        private String name;
        
        @Id
        @GeneratedValue
        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;
        }
        
    }

    测试

        @Test
        public void testSchemaExport() {
            new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);
        }

    但实际上并没有产生关联 这是一个bug

    在xml里面配置正常

    StuIdCard.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">
    
    <hibernate-mapping>
        <class name="com.bjsxt.hibernate.StuIdCard">
            <id name="id">
                <generator class="foreign">
                    <param name="property">student</param>
                </generator>
            </id>
            
            <property name="num"/>
            <one-to-one name="student" constrained="true"></one-to-one>
        </class>
        
    </hibernate-mapping>

    constrained = “true” 就可以加一个外键约束

    在实际开发中,一对一很少,一对一主键也很少

    一对一双向主键关联  不太重要 一般不使用 略

    联合主键

    Husband.java

    package com.bjsxt.hibernate;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.JoinColumn;
    import javax.persistence.JoinColumns;
    import javax.persistence.OneToOne;
    
    @Entity
    public class Husband {
        private int id;
        private String name;
        private Wife wife;
        @Id
        @GeneratedValue
        public int getId() {
            return id;
        }
        
        public String getName() {
            return name;
        }
        @OneToOne
        @JoinColumns(
            {
                @JoinColumn(name="wifeId", referencedColumnName="id"),
                @JoinColumn(name="wifeName", referencedColumnName="name")
            }
        )
        public Wife getWife() {
            return wife;
        }
        public void setId(int id) {
            this.id = id;
        }
        public void setName(String name) {
            this.name = name;
        }
        public void setWife(Wife wife) {
            this.wife = wife;
        }
        
    }

    Wife.java

    package com.bjsxt.hibernate;
    
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.IdClass;
    
    @Entity
    @IdClass(WifePK.class)
    public class Wife {
        private int id;
        private String name;
        private int age;
        
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        @Id
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        @Id
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        
    }

    WifePK.java

    package com.bjsxt.hibernate;
    
    import java.io.Serializable;
    
    
    
    public class WifePK implements Serializable {
        private int id;
        private String name;
        
        
        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;
        }
        
    }

    hibernate.cfg.xml

    <?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>
            <property name="connection.url">jdbc:mysql://localhost/hibernate</property>
            <property name="connection.username">root</property>
            <property name="connection.password">bjsxt</property>
            <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
           <!--
            <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
            <property name="connection.url">jdbc:oracle:thin:@localhost:1521:SXT</property>
            <property name="connection.username">scott</property>
            <property name="connection.password">tiger</property>
              <property name="dialect">org.hibernate.dialect.OracleDialect</property>
           -->
    
            <!-- JDBC connection pool (use the built-in) -->
            <property name="connection.pool_size">1</property>
    
            
    
            <!-- Enable Hibernate's automatic session context management -->
            <property name="current_session_context_class">thread</property>
    
            <!-- Disable the second-level cache  -->
            <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    
            <!-- Echo all executed SQL to stdout -->
            <property name="show_sql">true</property>
            <property name="format_sql">true</property>
    
            <!-- Drop and re-create the database schema on startup
            <property name="hbm2ddl.auto">update</property>
             -->
            <!--   -->
            
            <mapping class="com.bjsxt.hibernate.Husband"/>
            <mapping class="com.bjsxt.hibernate.Wife"/>
    
        </session-factory>
    
    </hibernate-configuration>

    Test

    package com.bjsxt.hibernate;
    
    import java.util.Date;
    
    import org.hibernate.Query;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.AnnotationConfiguration;
    import org.hibernate.tool.hbm2ddl.SchemaExport;
    import org.junit.AfterClass;
    import org.junit.BeforeClass;
    import org.junit.Test;
    
    public class HibernateORMappingTest {
        private static SessionFactory sessionFactory;
        
        //@BeforeClass
        public static void beforeClass() {
                sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        }
        //@AfterClass
        public static void afterClass() {
            sessionFactory.close();
        }
        
        
        
        @Test
        public void testSchemaExport() {
            new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);
        }
        
        public static void main(String[] args) {
            beforeClass();
        }
    }
  • 相关阅读:
    log4js 2.X版本配置详解
    ping -c 3 localhost
    children_process.exec 执行 ping命令报错
    淘宝双十一为什么会出现通道拥挤?
    'ascii' codec can't decode byte 0xd6 in position 0
    window 安装grunt
    display:none与visible:hidden的区别 slideDown与
    ztree-demo 2
    ztree-demo
    技术总结PHP+微信
  • 原文地址:https://www.cnblogs.com/frankzone/p/9447688.html
Copyright © 2011-2022 走看看