-->
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.  [ 8 posts ] 
Author Message
 Post subject: One to Many && Many to One mapping.
PostPosted: Fri Apr 28, 2006 6:19 am 
Newbie

Joined: Fri Apr 28, 2006 6:14 am
Posts: 8
Hi,

I am trying "<many-to-one name>" && "<one-to-many>".[Ref : http://saloon.javaranch.com/cgi-bin/ubb ... &f=78&java]

Team --> Player..

Data is getting inserted in Teams table, but "team_id" column in the players table is NULL.
I think team_id's will be automatically inserted by Hibernat{using <id>} and both have to be same to maintain the relation..

Hence, when i try to fetch the data;

i.e. First I fetch Teams and from Teams i am trying to get-Players(). Players Set is not having any values because there is no mapping between Team <--> Player..

Can anyone tell me what am i missing.

*] Is there anything wrong in xmls.
*] DB mapping need to be changed. Currently i have team_id from Teams && player_id from Players are PK's.

Team.hbm.xml

<hibernate-mapping>
<class name="com.test.Team" table="dbo.teams">
<id name="id" column="team_id" >
<generator class="hilo"/>
</id>
<property name="name" column="team_name" />
<property name="city" column="city" />
<set name="players" cascade="all" inverse="true" lazy="true">
<key column="team_id"/>
<one-to-many class="com.test.Player"/>
</set>
</class>
</hibernate-mapping>


Player.hbm.xml

<hibernate-mapping>
<class name="com.test.Player" table="dbo.players">
<id name="id" column="player_id">
<generator class="hilo"/>
</id>
<property name="firstName" column="first_name" />
<property name="lastName" column="last_name" />
<property name="draftDate" column="draft_date" />
<property name="annualSalary" column="salary" />
<property name="jerseyNumber" column="jersey_number" />
<many-to-one name="team" class="com.test.Team" column="team_id"/>
</class>
</hibernate-mapping>

Code:

Team team = new Team();
team.setCity("City");
team.setName("Name");
// team.setId(001);
// session.save(team);

Player player = new Player();
player.setFirstName("FN");
player.setLastName("LN");
player.setAnnualSalary(100);
// player.setDraftDate(new java.util.Date());
player.setCity("City");
player.setJerseyNumber(36471);

Set players = new HashSet();
players.add(player);

team.setPlayers(players);
session.saveOrUpdate(team);
tx.commit();
System.out.println("Saved Team details..");


Any help would be highly appreciated..

Thanks in Advance..
/Shridhar..


Top
 Profile  
 
 Post subject: Reference
PostPosted: Fri Apr 28, 2006 10:11 am 
Regular
Regular

Joined: Wed Feb 22, 2006 11:28 am
Posts: 65
Location: Santiago, Chile
Hello Friend:

After reading your post, i think a lot about your problem. It seens all OK without any problem.

I went to read the Hibernate Reference Document, and i found a Data interesting.

please see: http://www.hibernate.org/hib_docs/v3/re ... ns-mapping

at point [i]6.3.2. Bidirectional associations[/i]


The abstract about this point is like:

you put:
<set name="players" cascade="all" inverse="true" lazy="true">

so, u can not save thows players. Because that means :Changes made only to the inverse end of the association are not persisted, as like the reference document say.

You can take away the attribute inverse from your Tean class mapping, and put it into Player´s many-to-one tag like this:

many-to-one name="team" class="com.test.Team" column="team_id" inverse="true"/>

And this will work just fine.

I suggest u to read the reference document.

Request for comments


Top
 Profile  
 
 Post subject: Add bidirectional link
PostPosted: Fri Apr 28, 2006 1:14 pm 
Newbie

Joined: Wed Jan 18, 2006 4:17 pm
Posts: 8
Hi

In One-many and Many-one relations hibernate requires the bidirectional links/associations specified in the hbm files. You do have it but you in the players hbm make add not-null="true" in the association so it would look something like this:

<hibernate-mapping>
<class name="com.test.Player" table="dbo.players">
<id name="id" column="player_id">
<generator class="hilo"/>
</id>
<property name="firstName" column="first_name" />
<property name="lastName" column="last_name" />
<property name="draftDate" column="draft_date" />
<property name="annualSalary" column="salary" />
<property name="jerseyNumber" column="jersey_number" />
<many-to-one name="team" class="com.test.Team" column="team_id" not-null="true" />
</class>
</hibernate-mapping>


Once you do that you it makes it required for you to associate a team to the player. So in your code you would need to set the team for player which would be something like this: player.setTeam(teamObject)

this sets the association from Player to team and by adding player set to team you make team to player association and then you should see the hibernate magic..:)


crazee_dude......
Do not forget to rate this reply...


Top
 Profile  
 
 Post subject: One date interesting
PostPosted: Fri Apr 28, 2006 2:05 pm 
Regular
Regular

Joined: Wed Feb 22, 2006 11:28 am
Posts: 65
Location: Santiago, Chile
Hello Friend:

I suggest u read the follow Hibernate´s reference:

http://www.hibernate.org/hib_docs/v3/re ... ientupdate

19.5.2. Lists, maps, idbags and sets are the most efficient collections to update

19.5.3. Bags and lists are the most efficient inverse collections


They are talking about the efficent use of Bag, List , Set , and so on. It will help u a lot.

Requests for comments.


Top
 Profile  
 
 Post subject:
PostPosted: Tue May 02, 2006 5:09 am 
Newbie

Joined: Fri Apr 28, 2006 6:14 am
Posts: 8
Hello neketsushonen,

Thanks for your reply.
As suggested, I have made the changes in both the xml files.

Team.hbm.xml:

<hibernate-mapping>
<class name="com.test.Team" table="dbo.teams">
<id name="id" column="team_id" >
<generator class="hilo"/>
</id>
<property name="name" column="team_name" />
<property name="city" column="city" />
<set name="players" cascade="all" lazy="true">
<key column="team_id"/>
<one-to-many class="com.test.Player"/>
</set>
</class>
</hibernate-mapping>

PLayer.hbm.xml:

<hibernate-mapping>
<class name="com.test.Player" table="dbo.players">
<id name="id" column="player_id">
<generator class="hilo"/>
</id>
<property name="firstName" column="first_name" />
<property name="lastName" column="last_name" />
<property name="draftDate" column="draft_date" />
<property name="annualSalary" column="salary" />
<property name="jerseyNumber" column="jersey_number" />
<many-to-one name="team" class="com.test.Team" column="team_id" inverse="true" />
</class>
</hibernate-mapping>

After these changes, when i execute i am getting following exception..

org.hibernate.MappingException: Error reading resource: Player.hbm.xml
at org.hibernate.cfg.Configuration.addResource(Configuration.java:447)
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1381)
at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1353)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1335)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1302)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1230)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1216)
at com.test.TeamPlayer.main(TeamPlayer.java:31)
Caused by: org.hibernate.MappingException: invalid mapping
at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:394)
at org.hibernate.cfg.Configuration.addResource(Configuration.java:444)
... 7 more
Caused by: org.xml.sax.SAXParseException: Attribute "inverse" must be declared for element type "many-to-one".
at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
at org.apache.xerces.util.ErrorHandlerWrapper.error(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.dtd.XMLDTDValidator.addDTDDefaultAttrsAndValidate(Unknown Source)
at org.apache.xerces.impl.dtd.XMLDTDValidator.handleStartElement(Unknown Source)
at org.apache.xerces.impl.dtd.XMLDTDValidator.emptyElement(Unknown Source)
at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at org.dom4j.io.SAXReader.read(SAXReader.java:334)
at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:393)
... 8 more
Error org.hibernate.MappingException: Error reading resource: Player.hbm.xml

Can you please tell me, what might be wrong??
Is there anything wrong in DB??

Thanks,
/Shridhar..


Top
 Profile  
 
 Post subject:
PostPosted: Tue May 02, 2006 5:15 am 
Newbie

Joined: Fri Apr 28, 2006 6:14 am
Posts: 8
Hi crazee_dude,


Thanks for your reply.
As suggested, I have made the changes in both the Player.hbm.xml file.

After these changes, when i execute i am getting following exception..

Error org.hibernate.PropertyValueException: not-null property references a null or transient value: com.test.Player.team
org.hibernate.PropertyValueException: not-null property references a null or transient value: com.test.Player.team
at org.hibernate.engine.Nullability.checkNullability(Nullability.java:72)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:234)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:158)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:107)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:184)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:173)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:96)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:69)
at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:416)
at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:411)
at com.test.TeamPlayer.main(TeamPlayer.java:75)


Can you please tell me, what might be wrong??
Is there anything wrong in DB??

Thanks,
/Shridhar..


Top
 Profile  
 
 Post subject: Check nullability
PostPosted: Tue May 02, 2006 11:16 am 
Newbie

Joined: Wed Jan 18, 2006 4:17 pm
Posts: 8
It seems you are trying to save player before the team while it is null. Team id seems to be null while you are trying to save the player. So check if the team id is not null and then assign team object to the player and then save either the player or if cascade is set to all you can save team. So it would be something like
if(team != null && team.team_id != null)
{
player.setTeam(team)
}else{
//get the team object from the database
//then assign it to the player
}

// saveOrUpdate


Top
 Profile  
 
 Post subject: could not initialize a collection:
PostPosted: Tue May 02, 2006 11:19 pm 
Newbie

Joined: Fri Apr 28, 2006 6:14 am
Posts: 8
Hi All,

I am getting the following message, when i try to retreive the child object from the parent..



Session sess = sessionFactory.openSession();
Team obj = (Team) sess.load(Team.class, new Long(2457600));
Set s = obj.getPlayers();
System.out.println("PLayer -- "+obj.getPlayers());


Error Message :

org.hibernate.exception.GenericJDBCException: could not initialize a collection: [com.test.Team.players#2457600]
org.hibernate.exception.GenericJDBCException: could not initialize a collection: [com.test.Team.players#2457600]
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:82)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:70)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.loader.Loader.loadCollection(Loader.java:1351)
at org.hibernate.loader.collection.OneToManyLoader.initialize(OneToManyLoader.java:106)
at org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:484)
at org.hibernate.event.def.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:60)
at org.hibernate.impl.SessionImpl.initializeCollection(SessionImpl.java:1346)
at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:170)
at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:47)
at org.hibernate.collection.PersistentSet.toString(PersistentSet.java:221)
at java.lang.String.valueOf(String.java:2131)
at java.lang.StringBuffer.append(StringBuffer.java:370)
at com.test.TeamPlayer.main(TeamPlayer.java:70)
Caused by: java.sql.SQLException: [Microsoft][ODBC SQL Server Driver]Invalid Descriptor Index
at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6958)
at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7115)
at sun.jdbc.odbc.JdbcOdbc.SQLGetDataDouble(JdbcOdbc.java:3658)
at sun.jdbc.odbc.JdbcOdbcResultSet.getDataDouble(JdbcOdbcResultSet.java:5579)
at sun.jdbc.odbc.JdbcOdbcResultSet.getLong(JdbcOdbcResultSet.java:635)
at sun.jdbc.odbc.JdbcOdbcResultSet.getLong(JdbcOdbcResultSet.java:653)
at org.hibernate.type.LongType.get(LongType.java:26)
at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:77)
at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:68)
at org.hibernate.persister.collection.AbstractCollectionPersister.readKey(AbstractCollectionPersister.java:612)
at org.hibernate.loader.Loader.readCollectionElement(Loader.java:545)
at org.hibernate.loader.Loader.readCollectionElements(Loader.java:344)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:299)
at org.hibernate.loader.Loader.doQuery(Loader.java:384)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:203)
at org.hibernate.loader.Loader.loadCollection(Loader.java:1344)
... 10 more


Team [Parent] <--> Player [Child]

Team.hbm.xml
<hibernate-mapping>
<class name="com.test.Team" table="dbo.teams">
<id name="id" column="team_id" >
<generator class="hilo"/>
</id>
<property name="name" column="team_name" />
<property name="city" column="city" />
<set name="players" cascade="all" inverse="true" lazy="true">
<key column="team_id"/>
<one-to-many class="com.test.Player"/>
</set>
</class>
</hibernate-mapping>


PLayer.hbm.xml:
<hibernate-mapping>
<class name="com.test.Player" table="dbo.players">
<id name="id" column="player_id">
<generator class="hilo"/>
</id>
<property name="firstName" column="first_name" />
<property name="lastName" column="last_name" />
<property name="draftDate" column="draft_date" />
<property name="annualSalary" column="salary" />
<property name="jerseyNumber" column="jersey_number" />
<many-to-one name="team" class="com.test.Team" column="team_id" />
</class>
</hibernate-mapping>


Any help would be highly appreciated..

Thanks,
/Shridhar..


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 8 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.