hibernate一对一同步主键配置

hibernate一对一同步主键配置

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.sz</groupId>
  <artifactId>hibernate01</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>hibernate01</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

<!--mysql依赖-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.38</version>
    </dependency>

    <!--引入oracle的依赖-->
    <dependency>
      <groupId>com.oracle</groupId>
      <artifactId>ojdbc6</artifactId>
      <version>11.2.0.3</version>
      <!--
          basedir 工程的根路径的含义,
          ${}进行引用,
      -->
      <systemPath>${basedir}/lib/ojdbc6.jar</systemPath>
    </dependency>

    <!--引入hibernate依赖-->

    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>5.3.5.Final</version>
    </dependency>


  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.7.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.20.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <!--写法上面没有/ oracle协议固定全部使用:分割
    oracle:thin: oracle子协议
    -->
    <property name="connection.url">jdbc:oracle:thin:@localhost:1521:accp</property>
    <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
    <property name="connection.username">scott</property>
    <property name="connection.password">tiger</property>
    <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
    <!--<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>-->
    <!--<property name="connection.driver_class">com.mysql.jdbc.Driver</property>-->
    <!--<property name="connection.username">root</property>-->
    <!--<property name="connection.password">111111</property>-->
    <!--配置了方言,hibernate才知道如何去进行翻译。 -->
    <!--<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>-->
    <!--
      数据库方言配置
        hibernate就是一个翻译官,你只需要告诉为你说的是什么话就行了。
        oracle 生成oracle语法的SQL语句
        mysql 生成mysql语法的SQL语句
        不同版本下要求写的dialect不一样
    -->

    <property name="show_sql">true</property>
    <property name="format_sql">true</property>
      <!--常用值,如果表存在了不会再删除,又重新创建,只会用一次,不会再使用。 DBA设计,表存在了,
            反向设计领域模型。
            测试阶段方便
    -->
    <property name="hbm2ddl.auto">create</property>
      <!--当前这个会话是绑定在上下文当中的,这样互不干扰,自动关闭。-->
    <property name="current_session_context_class">thread</property>


    <!--引入hbm文件-->
    <mapping resource="com/sz/pojo/Student.hbm.xml"/>
    <mapping resource="com/sz/pojo/Teacher.hbm.xml"/>
  </session-factory>
</hibernate-configuration>


Student和Teacher POO

student

package com.sz.pojo;

import java.io.Serializable;

public class Student implements Serializable {

    private static final long serialVersionUID = -1633533936060759610L;
    private Integer id;
    private String name;
    private Teacher teacher;

    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 static long getSerialVersionUID() {
        return serialVersionUID;
    }

    public Teacher getTeacher() {
        return teacher;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }
}

teacher

package com.sz.pojo;

import java.io.Serializable;

public class Teacher implements Serializable {

    private static final long serialVersionUID = -1633533936060759610L;
    private Integer id;
    private String name;

    private Student student;

    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 Student getStudent() {
        return student;
    }

    public void setStudent(Student student) {
        this.student = student;
    }
}

工具类

package com.sz.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateUtil {

    private static SessionFactory sessionFactory;

    static {
        init();
    }

    private static void init() {
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure() // configures settings from hibernate.cfg.xml  默认就是使用这个名字。
                .build();
        try {
            sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
        }
        catch (Exception e) {
            // The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
            // so destroy it manually.  不需要存在,过河拆桥的对象。
            StandardServiceRegistryBuilder.destroy( registry );
        }
    }


    public static Session getSession(){
        return sessionFactory.getCurrentSession();
    }
}
package com.sz.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateUtil {

    private static SessionFactory sessionFactory;

    static {
        init();
    }

    private static void init() {
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure() // configures settings from hibernate.cfg.xml  默认就是使用这个名字。
                .build();
        try {
            sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
        }
        catch (Exception e) {
            // The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
            // so destroy it manually.  不需要存在,过河拆桥的对象。
            StandardServiceRegistryBuilder.destroy( registry );
        }
    }


    public static Session getSession(){
        return sessionFactory.getCurrentSession();
    }
}

HBM文件

Student.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.sz.pojo.Student" table="t_student" >
        <id name="id" column="id">
            <generator class="increment"/>
        </id>
        <property name="name"/>

        <!-- contstrained,使用student的主键当基准,teacher自动同步这边的ID-->
        <one-to-one name="teacher" class="com.sz.pojo.Teacher" constrained="true"
         cascade="all"></one-to-one>


    </class>
</hibernate-mapping>

Teacher.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.sz.pojo.Teacher" table="t_teacher" >
        <id name="id" column="id">
            <generator class="increment"/>
        </id>
        <property name="name"/>
        <one-to-one name="student" class="com.sz.pojo.Student"  ></one-to-one>


    </class>
</hibernate-mapping>

测试

package com.sz;

import com.sz.pojo.Student;
import com.sz.pojo.Teacher;
import com.sz.util.HibernateUtil;
import org.hibernate.Session;
import org.junit.Test;

public class TestOneToManyBiDirectional {

    @Test
    public void m1(){
       
        Session session = HibernateUtil.getSession();
        session.getTransaction().begin();
        Student s = new Student();
        s.setName("柏芝");
        Teacher t = new Teacher();
        t.setName("冠东");
        s.setTeacher(t);
        session.save(s);
        session.getTransaction().commit();

    }
 
}

结果

冠东同步柏芝的ID,插入成功。

posted @ 2018-08-27 17:05  沙漠皇帝  阅读(269)  评论(0编辑  收藏  举报