liguofeng29’s blog

個人勉強用ブログだっす。

Hibernate - 関連マッピング - @OneToMany

@OneToManyのサンプル
一人(1)が複数(N)のアドレスを持つ。

<?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>
        <!-- 接続情報 -->
        <property name="connection.url">jdbc:mysql://localhost/hibernate</property>
        <property name="connection.username">root</property>
        <property name="connection.password">xxxx</property>
        <!-- 各種設定 -->
        <property name="hibernate.c3p0.max_size">20</property>
        <property name="hibernate.c3p0.min_size">1</property>
        <property name="hibernate.c3p0.timeout">5000</property>
        <!-- プール内最大Statement -->
        <property name="hibernate.c3p0.max_statements">100</property>
        <property name="hibernate.c3p0.idle_test_period">3000</property>
        <property name="hibernate.c3p0.acquire_increment">2</property>

        <property name="hibernate.c3p0.validate">true</property>
        <!-- DB方言解消 -->
        <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
        <!-- 必要に応じて表生成 -->
        <property name="hbm2ddl.auto">update</property>
        <!-- 生成SQL表示 -->
        <property name="show_sql">true</property>
        <property name="hibernate.format_sql">true</property>

        <!-- マッピングテーブル -->
        <mapping class="relation.one_to_many.Person"/>
        <mapping class="relation.one_to_many.Address"/>

    </session-factory>
</hibernate-configuration>
package relation.one_to_many;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;

@Entity
@Table(name = "person_inf")
public class Person {

    @Id
    @Column(name = "person_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String name;
    private int age;

    @OneToMany(targetEntity = Address.class)
    @JoinColumn(name = "person_id", referencedColumnName = "person_id")
    @Cascade(CascadeType.ALL)
    private Set<Address> addresses = new HashSet<>();

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getId() {
        return this.id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getAge() {
        return this.age;
    }

    public void setAddresses(Set<Address> addresses) {
        this.addresses = addresses;
    }

    public Set<Address> getAddresses() {
        return this.addresses;
    }
}
package relation.one_to_many;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "address_inf")
public class Address {
    @Id
    @Column(name = "address_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int addressId;
    private String addressDetail;

    public Address() {
    }

    public Address(String addressDetail) {
        this.addressDetail = addressDetail;
    }

    public void setAddressId(int addressId) {
        this.addressId = addressId;
    }

    public int getAddressId() {
        return this.addressId;
    }

    public void setAddressDetail(String addressDetail) {
        this.addressDetail = addressDetail;
    }

    public String getAddressDetail() {
        return this.addressDetail;
    }

}
package relation.one_to_many;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {
    public static final SessionFactory sessionFactory;

    static {
        try {
            Configuration cfg = new Configuration().configure();
            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                    .applySettings(cfg.getProperties()).build();
            sessionFactory = cfg.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    public static final ThreadLocal<Session> session = new ThreadLocal<Session>();

    public static Session currentSession() throws HibernateException {
        Session s = session.get();
        if (s == null) {
            s = sessionFactory.openSession();
            session.set(s);
        }
        return s;
    }

    public static void closeSession() throws HibernateException {
        Session s = session.get();
        if (s != null)
            s.close();
        session.set(null);
    }
}
package relation.one_to_many;

import org.hibernate.Session;
import org.hibernate.Transaction;

public class PersonManager {
    public static void main(String[] args) {
        Session session = HibernateUtil.currentSession();
        Transaction tx = session.beginTransaction();
        // Person生成
        Person p = new Person();
        p.setName("佐藤");
        p.setAge(21);

        // Address生成
        Address address1 = new Address("住所1-1");
        Address address2 = new Address("住所2-2");

        // 関連
        p.getAddresses().add(address1);
        p.getAddresses().add(address2);

        // 保存
        session.persist(p);

        tx.commit();
        HibernateUtil.closeSession();
    }
}

結果

ログ:
Hibernate: 
    insert 
    into
        person_inf
        (age, name) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        address_inf
        (addressDetail) 
    values
        (?)
Hibernate: 
    insert 
    into
        address_inf
        (addressDetail) 
    values
        (?)
Hibernate: 
    update
        address_inf 
    set
        person_id=? 
    where
        address_id=?
Hibernate: 
    update
        address_inf 
    set
        person_id=? 
    where
        address_id=?


mysql> select * from person_inf;
+-----------+-----+--------+
| person_id | age | name   |
+-----------+-----+--------+
|         2 |  21 | 佐藤   |
+-----------+-----+--------+
1 row in set (0.00 sec)

mysql> select * from address_inf;
+------------+---------------+-----------+
| address_id | addressDetail | person_id |
+------------+---------------+-----------+
|          1 | 住所2-2       |         2 |
|          2 | 住所1-1       |         2 |
+------------+---------------+-----------+
2 rows in set (0.00 sec)