• Hibernate关系映射(一) 基于外键的单向一对一


    模拟用户和地址的映射关系,一个用户只有一个地址,用户知道地址,但是地址不知道用户。用户对地址的单向一对一映射。

    一、建立实体类

    Account.cs类

    复制代码
    package com.lxit.entity;
    
    import java.io.Serializable;
    
    public class Account implements Serializable{
        public Account(){
            
        }
        private int id;
        private String name;
        private String password;
        //需要添加被控端的引用
        private Address address;
        
        
        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 String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        public Address getAddress() {
            return address;
        }
        public void setAddress(Address address) {
            this.address = address;
        }
        
    }
    复制代码

    Address.cs类  地址类

    复制代码
    package com.lxit.entity;
    
    import java.io.Serializable;
    
    public class Address implements Serializable{
        public Address(){
            
        }
        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;
        }
        
    }
    复制代码

    二、映射文件

    Account.hbm.xml

    复制代码
    <?xml version="1.0" encoding="UTF-8"?>
    <!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.lxit.entity.Account" table="Account">
      <id column="id" name="id">
       <generator class="native"/>
      </id>
      <property column="name" generated="never" lazy="false" name="name"/>
      <property column="password" generated="never" lazy="false" name="password"/>
      <!-- 通过many-to-one 标签添加唯一属性约束,建立一对一关联关系 -->
      <many-to-one column="address_id" name="address" unique="true"/>
      <!-- 必须通过映射关系生成的表才会生成唯一约束,否则不会生成 -->
     </class>
    </hibernate-mapping>
    复制代码

    Address.hbm.xml

    复制代码
    <?xml version="1.0" encoding="UTF-8"?>
    <!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.lxit.entity.Address" table="Address">
      <id column="id" name="id">
       <generator class="native"/>
      </id>
      <property column="name" generated="never" lazy="false" name="name"/>
     </class>
    </hibernate-mapping>
    复制代码

    三、HibernateUtil工具类

    复制代码
    package com.lxit.util;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    
    /**
     * Hibernate3.3工具类
     * @author Administrator
     *
     */
    public class HibernateUtil {
        private static SessionFactory factory;
        
        static{
            Configuration cfg = new Configuration().configure();
            factory = cfg.buildSessionFactory();        
        }
        
        public static SessionFactory getFactory(){
            return factory;
        }
        
        public static Session getSession(){
            return factory.openSession();
        }
        
        public static void CloseSession(Session session){
            if(session != null){
                session.close();
            }
        }    
    }
    复制代码

    四、hibernate.cfg.xml配置文件

    复制代码
    <!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    
    <hibernate-configuration>
    <session-factory name="foo">
        <!-- 配置数据库连接 -->
        <property name="hibernate.dialect">
            org.hibernate.dialect.MySQL5Dialect
        </property>
        <property name="hibernate.connection.driver_class">
            com.mysql.jdbc.Driver
        </property>
        <property name="hibernate.connection.url">
            jdbc:mysql://127.0.0.1:3306/test
        </property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
    
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
    
        <property name="hbm2ddl.auto">update</property>
        <mapping resource="com/lxit/entity/Account.hbm.xml" />
        <mapping resource="com/lxit/entity/Address.hbm.xml" />
    
    </session-factory>
    </hibernate-configuration>
    复制代码

    五、Jutil测试类

    复制代码
    package com.lxit.demo2.test;
    import org.hibernate.Session;
    import org.hibernate.Transaction;
    import org.junit.Test;
    
    import com.lxit.entity.Account;
    import com.lxit.entity.Address;
    import com.lxit.util.HibernateUtil;
    
    
    public class AccountTest {
        
        @Test
        public void Add(){
            Transaction tx = null;
            Session session = HibernateUtil.getSession();
            tx = session.beginTransaction();
            
            Address address= new Address();
            address.setName("深圳宝安");        
            session.save(address);
            
            Account account = new Account();
            account.setName("zhangsan");
            account.setPassword("123");
            account.setAddress(address);
            
            try {
                session.save(account);
                tx.commit();
            } catch (Exception e) {
                e.printStackTrace();
                tx.rollback();
            }finally{
                HibernateUtil.CloseSession(session);
            }     
        }
        
        @Test
        public void Add2(){
            Transaction tx = null;
            Session session = HibernateUtil.getSession();
            tx = session.beginTransaction();
            
            Address address= new Address();
            address.setName("深圳福田");        
            session.save(address);
            
            Account account1 = new Account();
            account1.setName("lisi");
            account1.setPassword("123");
            account1.setAddress(address);
            
            Account account2 = new Account();
            account2.setName("wangwu");
            account2.setPassword("123");
            account2.setAddress(address);
            
            try {
                //重复添加第二个用户,地址相同,则会报错
                session.save(account1);
                session.save(account2);
                tx.commit();
            } catch (Exception e) {
                e.printStackTrace();
                tx.rollback();
            }finally{
                HibernateUtil.CloseSession(session);
            }        
        }
    }
    复制代码

    总结:单向一对一必须通过实体类生成数据库表的方式,会自动生成相关的约束,直接创建表无效。

  • 相关阅读:
    缓存
    判断空对象的方法
    Vue响应式系统如何操作运用?本文详解
    2020最新中级web前端面试题库(含详细答案,15k级别)你会几道呢?
    如何用JavaScriptJ封装拖动验证滑块?本文教你
    Nodejs中ES Modules如何操作运用?本文详解
    Vue学习总结之Vue的生命周期是怎么运用操作的?本文详解
    Vue项目如何部署?实战教你
    canvas绘制简单的霓虹灯效果
    canvas绘制五角星详细过程
  • 原文地址:https://www.cnblogs.com/Jeely/p/11226124.html
Copyright © 2020-2023  润新知