Hibernate one-to-many映射实例

首先创建一个Maven工程,最简单的即可



创建Java实例Entity


package org.hibernate.tutorial.domain;

public class Address {
  private int id; 
  private String name;
  
  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
}

package org.hibernate.tutorial.domain;

import java.util.List;

public class User { 
  private int id; 
  private String name;
  private List<Address> locations;
  
  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public List<Address> getLocations() {
    return locations;
  }
  public void setLocations(List<Address> locations) {
    this.locations = locations;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  
}


然后配置hibernate映射
<pre name="code" class="html"><?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 package="org.hibernate.tutorial.domain">
  <class name="User" table="t_user">
    <id name="id">
      <generator class="native"/>
    </id>
    <property name="name"/>
    <list name="locations">
      <key column="user_id"/>
      <index column="lsequence"/>
      <one-to-many class="org.hibernate.tutorial.domain.Address"/>
    </list>
  </class>  
  <class name="Address" table="t_address">
    <id name="id">
      <generator class="native"/>
    </id>
    <property name="name"/>
  </class>
</hibernate-mapping>

hibernate本身配置hibernate.cfg.xml

 
<pre name="code" class="html"><?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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="show_sql">true</property>
    <property name="format_sql">true</property>
    <mapping resource="org/hibernate/tutorial/domain/test.hbm.xml" />
   
</session-factory>
</hibernate-configuration>

数据库定义
 

DROP TABLE IF EXISTS `t_user`;

CREATE TABLE `t_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,

  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `t_address`;

CREATE TABLE `t_address` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11),
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  FOREIGN KEY(`user_id`) REFERENCES t_user(`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;


测试用例

package org.hibernate.tutorial.domain;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
 
public class HibernateUtil {
 
    private static SessionFactory sessionFactory;
     
    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            Configuration configuration = new Configuration();
            configuration.configure("hibernate.cfg.xml");
            System.out.println("Hibernate Configuration loaded");
             
            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
            System.out.println("Hibernate serviceRegistry created");
             
            SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
             
            return sessionFactory;
        }
        catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            ex.printStackTrace();
            throw new ExceptionInInitializerError(ex);
        }
    }
     
    public static SessionFactory getSessionFactory() {
        if(sessionFactory == null) sessionFactory = buildSessionFactory();
        return sessionFactory;
    }
}

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.tutorial.domain.Address;
import org.hibernate.tutorial.domain.HibernateUtil;
import org.hibernate.tutorial.domain.User;

public class App {
  public static void main(String[] args) {
    System.out.println("Hibernate one to many (XML Mapping)");
    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
    User user = new User();
    user.setName("shuai");
    Address add1 = new Address();
    add1.setName("addr1");
    Address add2 = new Address();
    add2.setName("addr2");
    List<Address> lst =  new ArrayList<Address>(2);
    lst.add(add1);
    lst.add(add2);
    user.setLocations(lst);
    session.saveOrUpdate(user);
    session.saveOrUpdate(add1);
    session.saveOrUpdate(add2);
    
    session.getTransaction().commit();
    System.out.println("Done");
  }
}


测试结果如下



从这里看,lsequence会自动被赋值,大小为0,1.。。。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值