Hibernate - 関連マッピング - @ManyToOne
@ManyToOneのサンプル
複数の人(N)が同じ(1)のアドレスを持つ。
<?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">xxxxx</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.many_to_one.Person"/> <mapping class="relation.many_to_one.Address"/> </session-factory> </hibernate-configuration>
package relation.many_to_one; 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.ManyToOne; 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; @ManyToOne(targetEntity = Address.class) @JoinColumn(name = "address_id", nullable = false) @Cascade(CascadeType.ALL) private Address address; 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 setAddress(Address address) { this.address = address; } public Address getAddress() { return this.address; } }
package relation.many_to_one; 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.many_to_one; 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.many_to_one; 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(20); // Address生成 Address address1 = new Address("住所1-1"); // 関連 p.setAddress(address1); // p保存 session.persist(p); Address address2 = new Address("住所2-2"); p.setAddress(address2); tx.commit(); HibernateUtil.closeSession(); } }
結果
ログ: Hibernate: insert into address_inf (addressDetail) values (?) Hibernate: insert into person_inf (address_id, age, name) values (?, ?, ?) Hibernate: insert into address_inf (addressDetail) values (?) Hibernate: update person_inf set address_id=?, age=?, name=? where person_id=? mysql> select * from person_inf; +-----------+-----+--------+------------+ | person_id | age | name | address_id | +-----------+-----+--------+------------+ | 1 | 20 | 佐藤 | 2 | +-----------+-----+--------+------------+ 1 row in set (0.00 sec) mysql> select * from address_inf; +------------+---------------+ | address_id | addressDetail | +------------+---------------+ | 1 | 住所1-1 | | 2 | 住所2-2 | +------------+---------------+ 2 rows in set (0.00 sec)