Many to One mapping : Many to One mapping « Hibernate « Java Tutorial






File: Main.java

import java.util.HashSet;

import org.hibernate.Session;

public class Main {
  public static void main(String[] args) throws Exception {
    HibernateUtil hibernateUtil = new HibernateUtil();
    hibernateUtil
        .executeSQLCommand("create table speakers (uid int, firstName varchar,lastName varchar, event_id int);");
    hibernateUtil
        .executeSQLCommand("create table locations (uid int, name varchar, address varchar,  event_id int);");
    hibernateUtil
        .executeSQLCommand("create table attendees (uid int, firstName varchar, lastName varchar,  event_id int);");
    hibernateUtil
        .executeSQLCommand("create table events (uid int , name varchar, start_date date, duration integer,location_id int);");

    Session session = hibernateUtil.getSession();

    Event e = new Event();
    e.setName("testSave");
    Location l = new Location();
    l.setName("building 1");
    e.setLocation(l);
    e.setSpeakers(new HashSet());
    e.getSpeakers().add(new Speaker("John", "Doe"));

    e.setAttendees(new HashSet());
    e.getAttendees().add(new Attendee("John", "Smith"));

    //session.save(l);
    session.save(e);
  //  session.flush();
    
    session.close();
    hibernateUtil.checkData("select * from events");
    hibernateUtil.checkData("select * from speakers");
    hibernateUtil.checkData("select * from locations");
    hibernateUtil.checkData("select * from attendees");
  }
}

File: Event.java

import java.util.Date;
import java.util.Set;

public class Event {

  private Long id;
  private String name;
  private Date startDate;
  private int duration;
  private Set speakers;
    private Set attendees;
    private Location location;

  public void setId(Long id) {
    this.id = id;
  }
  
  public Long getId() {
    return id;
  }

    public String getName() {
        return name;
    }

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

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    public int getDuration() {
        return duration;
    }

    public void setDuration(int duration) {
        this.duration = duration;
    }

    public Location getLocation() {
        return location;
    }

    public void setLocation(Location location) {
        this.location = location;
    }

  public void setSpeakers(Set speakers) {
    this.speakers = speakers;
  }
  
  public Set getSpeakers() {
    return speakers;
  }

    public Set getAttendees() {
        return attendees;
    }

    public void setAttendees(Set attendees) {
        this.attendees = attendees;
    }

}

File: Event.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<hibernate-mapping>
    <class name="Event" table="events">
        <id name="id" column="uid" type="long" unsaved-value="null">
            <generator class="native"/>
        </id>
        <property name="name" type="string" length="100"/>
        <property name="startDate" column="start_date"
                  type="date"/>
        <property name="duration" type="integer"/>

        <many-to-one name="location" column="location_id"
                     class="Location" cascade="all"/>
                     
                     
        <set name="speakers" cascade="all">
            <key column="event_id"/>
            <one-to-many class="Speaker"/>
        </set>
        <set name="attendees" cascade="all">
            <key column="event_id"/>
            <one-to-many class="Attendee"/>
        </set>
    </class>
</hibernate-mapping>

File: Attendee.java

public class Attendee {

    private Long id;
    private String firstName;
    private String lastName;

    public Attendee() {
    }

    public Attendee(String firstName, String lastName) {
        setFirstName(firstName);
        setLastName(lastName);
    }

    public Long getId() {
        return id;
    }

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

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }


}

File: Attendee.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<hibernate-mapping>
    <class name="Attendee" table="attendees">
        <id name="id" column="uid" type="long">
            <generator class="native"/>
        </id>
        <property name="firstName" type="string" length="20"/>
        <property name="lastName" type="string" length="20"/>
    </class>
</hibernate-mapping>

File: Speaker.java

public class Speaker {

    private Long id;
    private String firstName;
    private String lastName;

    public Speaker() {
    }

    public Speaker(String firstName, String lastName) {
        setFirstName(firstName);
        setLastName(lastName);
    }

    public Long getId() {
        return id;
    }

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

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

}

File: Speaker.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<hibernate-mapping>
    <class name="Speaker" table="speakers">
        <id name="id" column="uid" type="long">
            <generator class="native"/>
        </id>
        <property name="firstName" type="string" length="20"/>
        <property name="lastName" type="string" length="20"/>
    </class>
</hibernate-mapping>

File: Location.java

public class Location {

    private Long id;
    private String name;
    private String address;

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

File: Location.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<hibernate-mapping>
    <class name="Location" table="locations">
        <id name="id" column="uid" type="long">
            <generator class="native"/>
        </id>
        <property name="name" type="string"/>
        <property name="address" type="string"/>
    </class>
</hibernate-mapping>

File: HibernateUtil.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
  Session session;
  Statement st;
  public HibernateUtil() throws Exception{
    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    session = sessionFactory.openSession();

    // Load the JDBC driver.
    Class.forName("org.hsqldb.jdbcDriver");
    System.out.println("Driver Loaded.");
    // Establish the connection to the database.
    String url = "jdbc:hsqldb:data/tutorial";

    Connection conn = DriverManager.getConnection(url, "sa", "");
    System.out.println("Got Connection.");
    st = conn.createStatement();
  }
  public Session getSession(){
    return session;
  }
  public void executeSQLCommand(String sql) throws Exception {
    st.executeUpdate(sql);
  }

  public void checkData(String sql) throws Exception {
    ResultSet rs = st.executeQuery(sql);
    ResultSetMetaData metadata = rs.getMetaData();

    for (int i = 0; i < metadata.getColumnCount(); i++) {
      System.out.print("\t"+ metadata.getColumnLabel(i + 1)); 
    }
    System.out.println("\n----------------------------------");

    while (rs.next()) {
      for (int i = 0; i < metadata.getColumnCount(); i++) {
        Object value = rs.getObject(i + 1);
        if (value == null) {
          System.out.print("\t       ");
        } else {
          System.out.print("\t"+value.toString().trim());
        }
      }
      System.out.println("");
    }
  }
}

File: hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
        <property name="connection.url">jdbc:hsqldb:data/tutorial</property>
        <property name="connection.username">sa</property>
        <property name="connection.password"></property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.HSQLDialect</property>
        <!-- Enable Hibernate's current session context -->
        <property name="current_session_context_class">org.hibernate.context.ManagedSessionContext</property>

        <property name="hibernate.cache.use_second_level_cache">false</property>
        <property name="hibernate.cache.use_query_cache">false</property>
        
        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>        
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
        
        <!-- Mapping files -->
        <mapping resource="Event.hbm.xml"/>
        <mapping resource="Location.hbm.xml"/>        
        <mapping resource="Attendee.hbm.xml"/>
        <mapping resource="Speaker.hbm.xml"/>        
    </session-factory>
</hibernate-configuration>
  Download:  HibernateSetMappingWithKey.zip( 4,866 k)








21.7.Many to One mapping
21.7.1.Many to One mapping
21.7.2.Many To One Mapping: cascade all and set collection