Hibernate -- learning (12) -- one to one association based on foreign key mapping

Keywords: Hibernate Session xml Java

1. For the 1-1 association based on foreign key, the foreign key can be stored on either side, and the many to one element can be added at the end where the foreign key needs to be stored.

Add unique = "true" attribute to many to one element to represent 1-1 Association

2. The other end needs to use the one-to-one element, which uses the property ref attribute to specify the field other than the primary key of the associated entity as the associated field

 

3. example.

3.1 directory structure

3.2 Department class

package com.lishenhuan.hibernate.one2one.foreign;

public class Department {
	private Integer depId;
	private String depName;
	private Manager mag;
	public Integer getDepId() {
	    return depId;
	}
	public void setDepId(Integer depId) {
	    this.depId = depId;
	}
	public String getDepName() {
	    return depName;
	}
	public void setDepName(String depName) {
	    this.depName = depName;
	}
	public Manager getMag() {
	    return mag;
	}
	public void setMag(Manager mag) {
	    this.mag = mag;
	}
}

3.3 Manager class

package com.lishenhuan.hibernate.one2one.foreign;

public class Manager {
	private Integer magId;
	private String magDepName;
	private Department dep;
	public Integer getMagId() {
	    return magId;
	}
	public void setMagId(Integer magId) {
	    this.magId = magId;
	}
	public String getMagDepName() {
	    return magDepName;
	}
	public void setMagDepName(String magDepName) {
	    this.magDepName = magDepName;
	}
	public Department getDep() {
	    return dep;
	}
	public void setDep(Department dep) {
	    this.dep = dep;
	}
}

3.4 Department.hbm.xml file

<?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.lishenhuan.hibernate.one2one.foreign.Department" table="DEPARTMENTS">
        <id name="depId" type="java.lang.Integer">
            <column name="DEP_ID" />
            <generator class="native" />
        </id>
        <property name="depName" type="java.lang.String">
            <column name="DEP_NAME" />
        </property>

        <!-- Use many-to-one To map 1-1 Correlation -->
        <many-to-one name="mag" class="com.lishenhuan.hibernate.one2one.foreign.Manager"
           column="MAG_ID"  unique="true"></many-to-one>
    </class>
</hibernate-mapping>

3.5 Manager.hbm.xml file

<?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.lishenhuan.hibernate.one2one.foreign.Manager" table="MANAGERS">
        <id name="magId" type="java.lang.Integer">
            <column name="MAG_ID" />
            <generator class="native" />
        </id>
        <property name="magDepName" type="java.lang.String">
            <column name="MAGDEP_NAME" />
        </property>
        <!-- Mapping 1-1 Relationship of: There is already a foreign key in the corresponding data table, Current persistent class usage one-to-one Mapping -->
        <!--The end without a foreign key needs to be used one-to-one Element, which uses property-ref Property specifies to use a field other than the primary key of the associated entity as the associated field -->
        <one-to-one name="dep" class="com.lishenhuan.hibernate.one2one.foreign.Department"
        property-ref="mag" ></one-to-one>
    </class>
</hibernate-mapping>

3.6 hibernate.cfg.xml file

<?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.username">okaya10</property>
		<property name="connection.password">okaya10</property>
		<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
		<property name="connection.url">jdbc:oracle:thin:okaya10@//10.0.7.208:1521/ORCL</property>

		<property name="dialect">org.hibernate.dialect.Oracle9iDialect</property>
		<!-- Specifies whether the program is output at the console when it runs SQL Sentence -->
		<property name="show_sql">true</property>
		<!-- Specify whether to output SQL Statement to format -->
		<property name="format_sql">true</property>
		<!-- Specifies whether data tables are automatically generated in the database when the program runs -->
		<property name="hbm2ddl.auto">update</property>

		<!-- To configure C3P0 data source -->
		<property name="hibernate.c3p0.max_size">10</property>
		<property name="hibernate.c3p0.min_size">5</property>
		<property name="c3p0.timeout">2000</property>
		<property name="c3p0.acquire_increment">200</property>
		<property name="hibernate.c3p0.acquire_increment">10</property>
		<property name="hibernate.c3p0.max_statements">10</property>

       <!-- Statement The number of records taken from the database each time the data is read. -->
        <property name="hibernate.jdbc.fetch_size">100</property>

        <!-- Set the batch size when deleting, updating and inserting the database in batches -->
        <property name="hibernate.jdbc.batch_size">30</property>

		<!-- Specify associated.hbm.xml file -->
		<mapping resource="com/lishenhuan/hibernate/one2one/foreign/Manager.hbm.xml" />
        <mapping resource="com/lishenhuan/hibernate/one2one/foreign/Department.hbm.xml" />
	</session-factory>
</hibernate-configuration>

3.7 test documents

package com.lishenhuan.hibernate.one2one.foreign;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class TestNews {

	private SessionFactory sessionFactory;
	private Session session;
	private Transaction transaction;

	@Before
	public void init() {
		Configuration configuration = new Configuration().configure();
		ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
				.applySettings(configuration.getProperties())
				.buildServiceRegistry();

		sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		session = sessionFactory.openSession();
		transaction = session.beginTransaction();

	}

	@After
	public void destory() {
		transaction.commit();
		session.close();
		sessionFactory.close();
	}

	@Test
	public void testOne2One() {

		Department department = new Department();
		department.setDepName("DEPT-aa");

		Manager manager = new Manager();
		manager.setMagDepName("MGR-aa");

		//Set association relationship
		department.setMag(manager);
		manager.setDep(department);

		//Save operation
		//It is recommended to save the object without foreign key column first. This will reduce the UPDATE statement
		session.save(manager);
		session.save(department);

	}

	@Test
	public void testGet(){
		//1. Lazy loading is used for association properties by default
		//2. So there will be a problem of lazy loading
		Department dept = (Department) session.get(Department.class, 46);
		System.out.println(dept.getDepName());
		Manager manager =  dept.getMag();
		System.out.println(manager.getMagDepName());

	}

}

 

Posted by zemerick on Wed, 04 Dec 2019 16:10:41 -0800