Many to Many Mapping : Many to Many Mapping « Hibernate « Java Tutorial

Java Tutorial
1. Language
2. Data Type
3. Operators
4. Statement Control
5. Class Definition
6. Development
7. Reflection
8. Regular Expressions
9. Collections
10. Thread
11. File
12. Generics
13. I18N
14. Swing
15. Swing Event
16. 2D Graphics
17. SWT
18. SWT 2D Graphics
19. Network
20. Database
21. Hibernate
22. JPA
23. JSP
24. JSTL
25. Servlet
26. Web Services SOA
27. EJB3
28. Spring
29. PDF
30. Email
31. J2ME
32. J2EE Application
33. XML
34. Design Pattern
35. Log
36. Security
37. Apache Common
38. Ant
39. JUnit
Java
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Tutorial » Hibernate » Many to Many Mapping 
21. 6. 1. Many to Many Mapping

File: Main.java

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

public class Main {
  public static void main(String[] argsthrows Exception {
    HibernateUtil hibernateUtil = new HibernateUtil();
    hibernateUtil.executeSQLCommand("create table event(event_id int,event_date date, title varchar)");
    hibernateUtil.executeSQLCommand("create table person(person_id int,firstname varchar, lastname varchar,age int)");
    hibernateUtil.executeSQLCommand("create table PERSON_EVENT(event_id int, person_id int)");
    Session session = hibernateUtil.getSession();
    
    Event event1 = new Event();
    event1.setTitle("event1");
    Event event2 = new Event();
    event2.setTitle("event2");
    
    Person person1 = new Person();
    person1.setFirstname("person1");
    Person person2 = new Person();
    person2.setFirstname("person2");
    
    person1.getEvents().add(event1);
    person1.getEvents().add(event2);
    
    person2.getEvents().add(event1);
    person2.getEvents().add(event2);
    
    session.save(event1);
    session.save(event2);
    
    session.save(person1);
    session.flush();
    
    person1.getEvents().clear();
    
    session.save(person1);
    session.flush();
    
    session.close();
    hibernateUtil.checkData("select * from event");
    hibernateUtil.checkData("select * from person");
    hibernateUtil.checkData("select * from PERSON_EVENT");
  }
}

File: Person.java

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

public class Person {

    private Long id;
    private int age;
    private String firstname;
    private String lastname;

    public Person() {}

    private Set events = new HashSet();

    public Set getEvents() {
        return events;
    }

    public void setEvents(Set events) {
        this.events = events;
    }

    public int getAge() {
      return age;
    }

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

    public String getFirstname() {
      return firstname;
    }

    public void setFirstname(String firstname) {
      this.firstname = firstname;
    }

    public Long getId() {
      return id;
    }

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

    public String getLastname() {
      return lastname;
    }

    public void setLastname(String lastname) {
      this.lastname = lastname;
    }

}

File: Person.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="Person" table="person">
        <id name="id" column="person_id">
            <generator class="increment"/>
        </id>
        <property name="age"/>
        <property name="firstname"/>
        <property name="lastname"/>
      <set name="events" table="PERSON_EVENT">
          <key column="PERSON_ID"/>
          <many-to-many column="EVENT_ID" class="Event"/>
      </set>
        
    </class>



</hibernate-mapping>

File: Event.java

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

public class Event {
    private Long id;

    private String title;
    private Date date;

    private Set persons = new HashSet();
    
    public Event() {}

    public Long getId() {
        return id;
    }

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

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Set getPersons() {
      return persons;
    }

    public void setPersons(Set persons) {
      this.persons = persons;
    }
    
}

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="event">
        <id name="id" column="event_ID">
            <generator class="increment"/>
        </id>
        <property name="date" type="timestamp" column="event_date"/>
        <property name="title"/>
        
      <set name="persons" table="PERSON_EVENT">
          <key column="PERSON_ID"/>
          <many-to-many column="EVENT_ID" class="Event"/>
      </set>        
    </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;
  Configuration config;
  
  public HibernateUtil() throws Exception{
    config = new Configuration().configure();

    
    SessionFactory sessionFactory = config.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 Configuration getConfiguration(){
    return config;
  }
  public Session getSession(){
    return session;
  }
  public void executeSQLCommand(String sqlthrows Exception {
    st.executeUpdate(sql);
  }

  public void checkData(String sqlthrows 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="Person.hbm.xml"/>
    </session-factory>
</hibernate-configuration>
  Download:  HibernatereturnSingleColumnQuery.zip( 4,863 k)
21. 6. Many to Many Mapping
21. 6. 1. Many to Many Mapping
21. 6. 2. Many To Many Mapping Cascade Delete
21. 6. 3. Many To Many Mapping: set collection
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.