-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 3 posts ] 
Author Message
 Post subject: many-to-many does not work
PostPosted: Mon Aug 20, 2007 9:17 am 
Newbie

Joined: Mon Aug 20, 2007 6:08 am
Posts: 3
Hello Hibernate Users,

I am new to Hibernate and the many-to-many relationship does not work at my example. I hope you could help me. My example is the following:
There are events which have one or more persons as participants. My classes are "Event" and "Person", which have their own tables at database. The many-to-many relation is represented by the table "event_participants"

Hibernate 3.2.5
MySQL 5.0.38

hibernate.cfg.xml:
Code:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  "http://hibernate.sourceforge.net/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/navengine</property>
    <property name="hibernate.connection.username">username</property>
    <property name="hibernate.connection.password">password</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.show_sql">true</property>
    <property name="transaction.factory_class">
      org.hibernate.transaction.JDBCTransactionFactory
    </property>
    <property name="hibernate.cache.provider_class">
      org.hibernate.cache.HashtableCacheProvider
    </property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <mapping resource="Event.hbm.xml"/>
    <mapping resource="Person.hbm.xml"/>
  </session-factory>
</hibernate-configuration>


event.hbm.xml:
Code:
<?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>
   <class name="Event" table="event">
       <id name="id" type="integer">
            <generator class="native"/>
       </id>
       <property name="title" type="string"/>
       <property name="datetime" type="timestamp"/>
       <list name="participants" table="event_participants">
           <key column="event_id"/>
           <list-index column="ind"/>
           <many-to-many column="person_id" class="Person"/>
         </list>
     </class>
</hibernate-mapping>


Event.java:
Code:
import java.util.*;
public class Event {
   private long id;
   private String title;
   private Date datetime;
   private List<Person> participants = new ArrayList<Person>();

   public long getId() { return id; }
   public void setId(long id) { this.id = id;   }
   public String getTitle() {   return title; }
   public void setTitle(String title) { this.title = title; }
   public Date getDatetime() {   return datetime; }
   public void setDatetime(Date datetime) { this.datetime = datetime; }
   public List<Person> getParticipants() {   return participants; }
   public void setParticipants(List<Person> participants) { this.participants = participants;   }
}


person.hbm.xml:
Code:
<?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>
   <class name="Person" table="person">
       <id name="id" type="integer">
          <generator class="native"/>
       </id>
       <property name="name" type="string"/>
   </class>
</hibernate-mapping>


Person.java:
Code:
public class Person {
   private long id;
   private String name;
      
   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; }
}


Testing:
Code:
Person p1 = new Person();
Person p2 = new Person();
List<Person> personlist = new ArrayList<Person>();
      
p1.setName("Goerge Mason");
p2.setName("Jack Bauer");
personlist.add(p1);
personlist.add(p2);
   
Event e1 = new Event();
e1.setTitle("Business Meeting at Conference Room");
e1.setDatetime(new Date());
e1.setParticipants(personlist);
                  
SessionFactory sessionFactory;
Configuration config = new Configuration().configure();
SchemaExport export = new SchemaExport(config);
export.create(false,true);
sessionFactory = config.buildSessionFactory();
            
Session     sess = null;
Transaction trx  = null;
try {
       sess = sessionFactory.openSession();
       trx  = sess.beginTransaction();
       sess.save(p1);
       sess.save(p2);
       sess.save(e1);
       trx.commit();
}
catch( HibernateException ex )  {
        if( trx != null ) { trx.rollback(); }
   System.out.println(ex.toString());
}
finally { if( sess != null ) sess.close(); }


Console output:
Code:
0    [main] INFO  org.hibernate.cfg.Environment  - Hibernate 3.2.5
12   [main] INFO  org.hibernate.cfg.Environment  - hibernate.properties not found
16   [main] INFO  org.hibernate.cfg.Environment  - Bytecode provider name : cglib
24   [main] INFO  org.hibernate.cfg.Environment  - using JDK 1.4 java.sql.Timestamp handling
164  [main] INFO  org.hibernate.cfg.Configuration  - configuring from resource: /hibernate.cfg.xml
165  [main] INFO  org.hibernate.cfg.Configuration  - Configuration resource: /hibernate.cfg.xml
619  [main] INFO  org.hibernate.cfg.Configuration  - Reading mappings from resource : Event.hbm.xml
839  [main] INFO  org.hibernate.cfg.HbmBinder  - Mapping class: Event -> event
879  [main] INFO  org.hibernate.cfg.HbmBinder  - Mapping collection: Event.participants -> event_participants
884  [main] INFO  org.hibernate.cfg.Configuration  - Reading mappings from resource : Person.hbm.xml
952  [main] INFO  org.hibernate.cfg.HbmBinder  - Mapping class: Person -> person
954  [main] INFO  org.hibernate.cfg.Configuration  - Configured SessionFactory: null
1006 [main] INFO  org.hibernate.dialect.Dialect  - Using dialect: org.hibernate.dialect.MySQLDialect
1213 [main] INFO  org.hibernate.tool.hbm2ddl.SchemaExport  - Running hbm2ddl schema export
1214 [main] INFO  org.hibernate.tool.hbm2ddl.SchemaExport  - exporting generated schema to database
1220 [main] INFO  org.hibernate.connection.DriverManagerConnectionProvider  - Using Hibernate built-in connection pool (not for production use!)
1221 [main] INFO  org.hibernate.connection.DriverManagerConnectionProvider  - Hibernate connection pool size: 20
1221 [main] INFO  org.hibernate.connection.DriverManagerConnectionProvider  - autocommit mode: false
1241 [main] INFO  org.hibernate.connection.DriverManagerConnectionProvider  - using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost/navengine
1241 [main] INFO  org.hibernate.connection.DriverManagerConnectionProvider  - connection properties: {user=root, password=****}
1627 [main] INFO  org.hibernate.tool.hbm2ddl.SchemaExport  - schema export complete
1628 [main] INFO  org.hibernate.connection.DriverManagerConnectionProvider  - cleaning up connection pool: jdbc:mysql://localhost/navengine
1635 [main] INFO  org.hibernate.connection.DriverManagerConnectionProvider  - Using Hibernate built-in connection pool (not for production use!)
1636 [main] INFO  org.hibernate.connection.DriverManagerConnectionProvider  - Hibernate connection pool size: 20
1636 [main] INFO  org.hibernate.connection.DriverManagerConnectionProvider  - autocommit mode: false
1636 [main] INFO  org.hibernate.connection.DriverManagerConnectionProvider  - using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost/navengine
1636 [main] INFO  org.hibernate.connection.DriverManagerConnectionProvider  - connection properties: {user=root, password=****}
1676 [main] INFO  org.hibernate.cfg.SettingsFactory  - RDBMS: MySQL, version: 5.0.38-Ubuntu_0ubuntu1-log
1676 [main] INFO  org.hibernate.cfg.SettingsFactory  - JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.0.4 ( $Date: 2006-10-19 17:47:48 +0200 (Thu, 19 Oct 2006) $, $Revision: 5908 $ )
1682 [main] INFO  org.hibernate.dialect.Dialect  - Using dialect: org.hibernate.dialect.MySQLDialect
1696 [main] INFO  org.hibernate.transaction.TransactionFactoryFactory  - Transaction strategy: org.hibernate.transaction.JDBCTransactionFactory
1701 [main] INFO  org.hibernate.transaction.TransactionManagerLookupFactory  - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
1701 [main] INFO  org.hibernate.cfg.SettingsFactory  - Automatic flush during beforeCompletion(): disabled
1701 [main] INFO  org.hibernate.cfg.SettingsFactory  - Automatic session close at end of transaction: disabled
1701 [main] INFO  org.hibernate.cfg.SettingsFactory  - JDBC batch size: 15
1702 [main] INFO  org.hibernate.cfg.SettingsFactory  - JDBC batch updates for versioned data: disabled
1703 [main] INFO  org.hibernate.cfg.SettingsFactory  - Scrollable result sets: enabled
1703 [main] INFO  org.hibernate.cfg.SettingsFactory  - JDBC3 getGeneratedKeys(): enabled
1704 [main] INFO  org.hibernate.cfg.SettingsFactory  - Connection release mode: auto
1705 [main] INFO  org.hibernate.cfg.SettingsFactory  - Maximum outer join fetch depth: 2
1705 [main] INFO  org.hibernate.cfg.SettingsFactory  - Default batch fetch size: 1
1706 [main] INFO  org.hibernate.cfg.SettingsFactory  - Generate SQL with comments: disabled
1706 [main] INFO  org.hibernate.cfg.SettingsFactory  - Order SQL updates by primary key: disabled
1706 [main] INFO  org.hibernate.cfg.SettingsFactory  - Order SQL inserts for batching: disabled
1706 [main] INFO  org.hibernate.cfg.SettingsFactory  - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
1711 [main] INFO  org.hibernate.hql.ast.ASTQueryTranslatorFactory  - Using ASTQueryTranslatorFactory
1711 [main] INFO  org.hibernate.cfg.SettingsFactory  - Query language substitutions: {}
1711 [main] INFO  org.hibernate.cfg.SettingsFactory  - JPA-QL strict compliance: disabled
1711 [main] INFO  org.hibernate.cfg.SettingsFactory  - Second-level cache: enabled
1712 [main] INFO  org.hibernate.cfg.SettingsFactory  - Query cache: disabled
1712 [main] INFO  org.hibernate.cfg.SettingsFactory  - Cache provider: org.hibernate.cache.HashtableCacheProvider
1714 [main] INFO  org.hibernate.cfg.SettingsFactory  - Optimize cache for minimal puts: disabled
1714 [main] INFO  org.hibernate.cfg.SettingsFactory  - Structured second-level cache entries: disabled
1723 [main] INFO  org.hibernate.cfg.SettingsFactory  - Echoing all SQL to stdout
1724 [main] INFO  org.hibernate.cfg.SettingsFactory  - Statistics: disabled
1724 [main] INFO  org.hibernate.cfg.SettingsFactory  - Deleted entity synthetic identifier rollback: disabled
1724 [main] INFO  org.hibernate.cfg.SettingsFactory  - Default entity-mode: pojo
1724 [main] INFO  org.hibernate.cfg.SettingsFactory  - Named query checking : enabled
1815 [main] INFO  org.hibernate.impl.SessionFactoryImpl  - building session factory
2399 [main] INFO  org.hibernate.impl.SessionFactoryObjectFactory  - Not binding factory to JNDI, no JNDI name configured
2405 [main] INFO  org.hibernate.tool.hbm2ddl.SchemaUpdate  - Running hbm2ddl schema update
2405 [main] INFO  org.hibernate.tool.hbm2ddl.SchemaUpdate  - fetching database metadata
2407 [main] INFO  org.hibernate.tool.hbm2ddl.SchemaUpdate  - updating schema
2468 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata  - table found: navengine.event
2469 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata  - columns: [id, title, datetime]
2470 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata  - foreign keys: []
2470 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata  - indexes: [primary]
2504 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata  - table found: navengine.event_participants
2504 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata  - columns: [person_id, ind, event_id]
2504 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata  - foreign keys: []
2506 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata  - indexes: [fkbbcd7925c12321ba, fkbbcd79251497435a, primary]
2540 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata  - table found: navengine.person
2541 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata  - columns: [id, name]
2541 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata  - foreign keys: []
2541 [main] INFO  org.hibernate.tool.hbm2ddl.TableMetadata  - indexes: [primary]
2542 [main] INFO  org.hibernate.tool.hbm2ddl.SchemaUpdate  - schema update complete
Hibernate: insert into person (name) values (?)
Hibernate: insert into person (name) values (?)
Hibernate: insert into event (title, datetime) values (?, ?)
org.hibernate.HibernateException: identifier of an instance of Person was altered from 1 to 1


p1,p2 and e1 will be saved at database, but the relationship that p1 and p2 are participants of e1 will not be saved at table "event_participants". And I don't know what the Exception will tell me. Could anybody please help me? Thanks.


Top
 Profile  
 
 Post subject:
PostPosted: Mon Aug 20, 2007 5:01 pm 
Expert
Expert

Joined: Fri Jul 13, 2007 8:18 am
Posts: 370
Location: london
You're mapping your IDs as integer in the XML files but using long in the java files. Make the types consistent between java and xml and everything should be ok.


Top
 Profile  
 
 Post subject:
PostPosted: Wed Aug 22, 2007 5:26 pm 
Newbie

Joined: Mon Aug 20, 2007 6:08 am
Posts: 3
Thanks for your advice. The inconsistent mapping has been the reason for disfunction.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 3 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.