• 框架:Hibernate单向多对1


    一、假定一个人只有多个地址,一个地址只对应一个人,那么地址和人对应关系为多对1。

    二、

           1、添加依赖包,参考上篇文章hibernate+mysql入门使用

           2、初始化数据库

    DROP  DATABASE  IF  EXISTS  moy_hibernate;
    CREATE  DATABASE  moy_hibernate   CHARACTER SET UTF8;
    View Code

           3、新建实体类Person和Address

    package com.moy.hibernate4.entity;
    
    import javax.persistence.*;
    import java.util.HashSet;
    import java.util.Set;
    
    /**
     * [Project]:moy-gradle-project  <br/>
     * [Email]:moy25@foxmail.com  <br/>
     * [Date]:2018/2/25  <br/>
     * [Description]:  <br/>
     *
     * @author YeXiangYang
     */
    @Table(name = "t_person")
    @Entity
    public class Person {
        @Id
        @Column(name = "person_id")
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Integer id;
        private String name;
        private int age;
    
        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;
        }
    
        @Override
        public String toString() {
            return "Person{" +
                    "id=" + id +
                    ", name='" + name + ''' +
                    ", age=" + age +
                    '}';
        }
    }
    View Code
    package com.moy.hibernate4.entity;
    
    import org.hibernate.annotations.Cascade;
    
    import javax.persistence.*;
    
    import org.hibernate.annotations.Cascade;
    import org.hibernate.annotations.CascadeType;
    
    /**
     * [Project]:moy-gradle-project  <br/>
     * [Email]:moy25@foxmail.com  <br/>
     * [Date]:2018/2/25  <br/>
     * [Description]:  <br/>
     *
     * @author YeXiangYang
     */
    @Entity
    @Table(name = "t_address")
    public class Address {
    
        @Id
        @Column(name = "id")
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private int addressId;
        private String addressDetail;
        @ManyToOne(targetEntity = Person.class)
        @JoinColumn(name = "person_id", nullable = false)
        private Person person;
    
        public int getAddressId() {
            return addressId;
        }
    
        public void setAddressId(int 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;
        }
    
        @Override
        public String toString() {
            return "Address{" +
                    "addressId=" + addressId +
                    ", addressDetail='" + addressDetail + ''' +
                    ", person=" + person +
                    '}';
        }
    }
    View Code

           4、新建配置文件hibernate.cfg.xml和log4j.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-configuration PUBLIC
            "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
            "http://www.hibernate.org/dtd/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/moy_hibernate</property>
            <!-- 指定连接数据库的用户名 -->
            <property name="connection.username">root</property>
            <!-- 指定连接数据库的密码 -->
            <property name="connection.password">123</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="com.moy.hibernate4.entity.Person"></mapping>
            <mapping class="com.moy.hibernate4.entity.Address"></mapping>
        </session-factory>
    </hibernate-configuration>
    View Code
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
    <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
        <appender name="console" class="org.apache.log4j.ConsoleAppender">
            <layout class="org.apache.log4j.PatternLayout">
                <param name="ConversionPattern" value="%d %-5p %-5c{3}:%L %x %n-> %m%n"/>
            </layout>
        </appender>
        <root>
            <priority value="DEBUG"/>
            <appender-ref ref="console"/>
        </root>
    </log4j:configuration>
    View Code

          5、为了方便测试,编写一个获取Session的工具类Hibernate4Utils

    package com.moy.hibernate4.util;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
    import org.hibernate.cfg.Configuration;
    import org.hibernate.service.ServiceRegistry;
    
    import java.util.Objects;
    
    public abstract class Hibernate4Utils {
    
        static {
            try {
                Configuration conf = new Configuration().configure();
                ServiceRegistry registry = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build();
                sessionFactory = conf.buildSessionFactory(registry);
            } catch (Throwable e) {
                throw e;
            }
        }
    
        public static final SessionFactory sessionFactory;
    
        public static final ThreadLocal<Session> sessionThread = new ThreadLocal<>();
    
        /**
         * 获取当前线程安全Session
         */
        public static Session getCurrentSession() {
            Session session = sessionThread.get();
            if (Objects.isNull(session)) {
                session = sessionFactory.openSession();
                sessionThread.set(session);
            }
            return session;
        }
    
        /**
         * 关闭Session
         */
        public static void closeCurrentSession() {
            Session session = sessionThread.get();
            if (Objects.nonNull(session)) {
                session.close();
            }
            sessionThread.set(null);
        }
    }
    View Code

          6、新建测试类ManyToOneTest测试

    package com.moy.hibernate4.entity;
    
    import com.moy.hibernate4.util.Hibernate4Utils;
    import org.hibernate.Session;
    import org.hibernate.Transaction;
    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    
    /**
     * [Project]:moy-gradle-project  <br/>
     * [Email]:moy25@foxmail.com  <br/>
     * [Date]:2018/2/25  <br/>
     * [Description]:  <br/>
     *
     * @author YeXiangYang
     */
    public class ManyToOneTest {
    
        Session session;
        Transaction transaction;
    
        @Before
        public void before() {
            session = Hibernate4Utils.getCurrentSession();
            transaction = session.beginTransaction();
        }
    
        @After
        public void after() {
            transaction.commit();
            Hibernate4Utils.closeCurrentSession();
        }
    
        @Test
        public void test() {
    
            Person p = new Person();
            p.setName("测试1对多");
            p.setAge(233);
            session.persist(p);
    
            Address firstAddress = new Address();
            firstAddress.setAddressDetail(firstAddress.toString());
            firstAddress.setPerson(p);
            session.persist(firstAddress);
    
            Address secondAddress = new Address();
            secondAddress.setAddressDetail(secondAddress.toString());
            secondAddress.setPerson(p);
            session.persist(secondAddress);
        }
    }
    View Code

    yexiangyang

    moyyexy@gmail.com


     

  • 相关阅读:
    JDK下载 安装 配置
    C#中的委托与事件 笔记
    转载 -- C# 中的委托和事件
    Laravel5 路由问题 /home页面无法访问
    eclipse的android智能提示设置
    svn在linux下的使用(ubuntu命令行模式操作svn)
    gdb结合coredump定位崩溃进程
    Android帧缓冲区(Frame Buffer)硬件抽象层(HAL)模块Gralloc的实现原理分析
    struct的初始化,拷贝及指针成员的使用技巧
    C++ 资源大全
  • 原文地址:https://www.cnblogs.com/moy25/p/8471100.html
Copyright © 2020-2023  润新知