-->
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.  [ 19 posts ]  Go to page 1, 2  Next
Author Message
 Post subject: Looking for error in my mapping.
PostPosted: Fri Jan 30, 2009 5:18 pm 
Newbie

Joined: Fri Jan 30, 2009 5:08 pm
Posts: 17
Location: Florida
Need help with Hibernate? Read this first:
http://www.hibernate.org/ForumMailingli ... AskForHelp

Hibernate version: 3

Name and version of the database you are using: Mysql 5

Looking for proper mapping, I am not sure what I am doing wrong, but I am pretty sure it has something to do with my mappings.

If I insert the data Hibernate will query fine.

For example: insert into users (first_name) values('John');
insert into email (user_id, email_address) values(1, 'me@here.com');

HQL:
from UserVo;
Every thing is fine and it all shows up correctly.

If I create a user and use save or update as in:

UserVo u = null;
EmailAddress e = null;
e=new EmailAddress();
u=new UserVo();
e.setEmailAddress("me@here.com");
u.setEmail(e);
u.setUserName("me");
u.setPass("mypassword");

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.saveOrUpdate(u);
session.getTransaction().commit();

session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
u = (UserVo) session.createQuery("from UserVo where userName = ? and pass =?").setString(0, "me").setString(1, "mypassword").uniqueResult();
session.getTransaction().commit();

When I look in the database I see the entry in the tables, but in the email table the user_id column is null.

What am I doing wrong?


Java Classes:
public class UserVo{
private int userId;
private String firstName;
private EmailAddress email;

public String getFirstName(){
return firstName;
}
public void setFirstName(String firstName){
this.name = firstName;
}
public EmailAddress getName(){
return email;
}
public void setEmail(EmailAddress email){
this.email = email;
}
public int getUserId(){
return userId;
}
public void setUserId(int userId){
this.userId = userId;
}
}

public class EmailAddress{
private int emailId;
private UserVo user;
private String emailAddress;

public int getEmailId() {
return emailId;
}
public void setEmailId(int emailId) {
this.emailId = emailId;
}
public UserVo getUser() {
return user;
}
public void setUser(UserVo user) {
this.user = user;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
}
Hibernate mappings:

UserVo.hbm.xml
<?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="UserVo" table="users">
<id column="user_id" name="userId">
<generator class="native"/>
</id>
<property name="firstName" column="first_name"/>
<one-to-one cascade="all" name="email" foreign-key="user_id" class="EmailAddress"/>
</class>
</hibernate-mapping>

EmailAddress.hbm.xml
<?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="EmailAddress" table="email">
<id name="emailId" column="email_id">
<generator class="native"/>
</id>
<many-to-one name="user" property-ref="userId" column="user_id" class="UserVo" />
<property name="emailAddress" column="email_address" type="java.lang.String"/>
</class>
</hibernate-mapping>

SQL for tables:
create table users(
user_id int not null auto_increment,
first_name varchar(30),
primary key(user_id)
);

create table email(
email_id int not null auto_increment,
user_id int,
email_address varchar(70),
foreign key (user_id) references users(user_id),
primary key(email_id)
);


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jan 30, 2009 6:33 pm 
Regular
Regular

Joined: Tue Dec 30, 2008 8:14 pm
Posts: 50
Need to call
e.setUser(u);

---
please rate


Top
 Profile  
 
 Post subject:
PostPosted: Mon Feb 02, 2009 11:25 am 
Newbie

Joined: Fri Jan 30, 2009 5:08 pm
Posts: 17
Location: Florida
In order to have a bidirectional mapping ...would I need to have the email Id in the user table as well?

I was under the understanding that the mapping would put the userid in the user table automatically if the mapping is done correctly.


Top
 Profile  
 
 Post subject:
PostPosted: Mon Feb 02, 2009 11:35 am 
Expert
Expert

Joined: Thu Jan 08, 2009 6:16 am
Posts: 661
Location: Germany
No, there is no extra-column necessary in the user-table. But your mapping seems not to be right anyway. Your association is not bidirectional: user has one email address, but emailAddress has a manyToOne to user? Thats not the same association. You should either map users emails as oneToMany(with inverse=true) or mark both sides as oneToOne.

_________________
-----------------
Need advanced help? http://www.viada.eu


Top
 Profile  
 
 Post subject:
PostPosted: Mon Feb 02, 2009 12:38 pm 
Newbie

Joined: Fri Jan 30, 2009 5:08 pm
Posts: 17
Location: Florida
Attempting to e.setUser(u);
Resulted in this
Exception in thread "main" org.hibernate.HibernateException: Unable to resolve property: userId, which makes sense as I have not set a userId and it supposed to be set by the auto_increment in the MySql table.


UserVo.hbm.xml
<?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="UserVo" table="users">
<id column="user_id" name="userId">
<generator class="native"/>
</id>
<property name="firstName" column="first_name"/>
<one-to-one cascade="all" name="email" foreign-key="user_id" class="EmailAddress"/>
</class>
</hibernate-mapping>

EmailAddress.hbm.xml
<?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="EmailAddress" table="email">
<id name="emailId" column="email_id">
<generator class="native"/>
</id>
<one-to-one name="user" foreign-key="user_id" property-ref="userId" class="UserVo"/>
<property name="emailAddress" column="email_address" type="java.lang.String"/>
</class>
</hibernate-mapping>

Java Test Code:
UserVo u = null;
EmailAddress e = null;
e=new EmailAddress();
u=new UserVo();
e.setEmailAddress("me@here.com");
u.setEmail(e);
u.setUserName("me");
u.setPass("mypassword");

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.saveOrUpdate(u);
session.getTransaction().commit();

session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
u = (UserVo) session.createQuery("from UserVo where userName = ? and pass =?").setString(0, "me").setString(1, "mypassword").uniqueResult();
session.getTransaction().commit();

Exception in thread "main" java.lang.NullPointerException
at org.hibernate.persister.entity.AbstractEntityPersister.loadByUniqueKey(AbstractEntityPersister.java:1672)


Still getting NULL in the email table for user_id.

I also attempted to make map email in the user as a bag with a one-to-many and set up the Java class to accept a List, and setup email mapping as many-to-one.


Top
 Profile  
 
 Post subject:
PostPosted: Mon Feb 02, 2009 1:31 pm 
Newbie

Joined: Fri Jan 30, 2009 5:08 pm
Posts: 17
Location: Florida
Another interesting note, when I use <property name="hbm2ddl.auto">create</property>

Hibernate creates a schema just like I had, when I use the mappings in the original post, but it still will not populate the user_id column of the email table.


Top
 Profile  
 
 Post subject:
PostPosted: Mon Feb 02, 2009 2:45 pm 
Senior
Senior

Joined: Thu Jan 08, 2009 3:48 pm
Posts: 168
Try moving the "u = new User() etc" part inside the transaction


Top
 Profile  
 
 Post subject:
PostPosted: Mon Feb 02, 2009 3:02 pm 
Newbie

Joined: Fri Jan 30, 2009 5:08 pm
Posts: 17
Location: Florida
Same result, no value in user_id column of email table.

Just for a bigger picture I am trying to use this to make an application with Flex3/Java/Hibernate/MySql.


I am running all of this from Java at the moment, to make sure that there isn't something in flex.


Top
 Profile  
 
 Post subject:
PostPosted: Tue Feb 03, 2009 4:03 am 
Expert
Expert

Joined: Thu Jan 08, 2009 6:16 am
Posts: 661
Location: Germany
remove "property-ref="userId"" out of your mapping, as userId is your primary-key and property-ref is used when the targeted property is not a PK.

_________________
-----------------
Need advanced help? http://www.viada.eu


Top
 Profile  
 
 Post subject:
PostPosted: Tue Feb 03, 2009 9:21 am 
Newbie

Joined: Fri Jan 30, 2009 5:08 pm
Posts: 17
Location: Florida
I went back to the beginning, and redid everything, and I have included all of the source for all the files. I have tried the suggestions, and I am at a loss, so any suggestions would be greatly appreciated.

All Java files:
------------BEGIN HibernateUtil.java ---------------
package com.example.apps.reports.dao;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class HibernateUtil {
private static SessionFactory sessionFactory;
static {
try {
sessionFactory = new Configuration().configure().buildSessionFactory();
}catch(Throwable t){
System.err.println("Initial SessionFactory creation failed " + t);
throw new ExceptionInInitializerError(t);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
------------END HibernateUtil.java ---------------
------------BEGIN DataService.java ---------------
package com.example.apps.reports.service;
import org.hibernate.Session;
import com.example.apps.reports.dao.HibernateUtil;
import com.example.apps.reports.vo.EmailAddress;
import com.example.apps.reports.vo.UserVo;
import com.example.apps.reports.vo.ValueObject;
public class DataService {
public static void saveItem(ValueObject vo){
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.saveOrUpdate(vo);
session.getTransaction().commit();
}
public static void main(String[] args) {
UserVo u = null;
EmailAddress e = null;
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
//This should pull back UserId 4 First Name Test4 and emailId 2 with Test4@here.com
u = (UserVo) session.createQuery("from UserVo where userId = ?").setInteger(0, 4).uniqueResult();
session.getTransaction().commit();
System.out.println(u.getFirstName());
//EMAIL is null
System.out.println(u.getEmail().getEmailAddress());
}
}
------------END DataService.java ---------------
------------BEGIN ValueObject.java ---------------
package com.example.apps.reports.vo;
public class ValueObject {

}
------------END ValueObject.java ---------------
------------BEGIN UserVo.java --------------
package com.example.apps.reports.vo;
public class UserVo extends ValueObject{
private int userId;
private String firstName;
private EmailAddress email;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public EmailAddress getEmail() {
return email;
}
public void setEmail(EmailAddress email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
------------END UserVo.java --------------
------------BEGIN EmailAddress.java --------------
package com.example.apps.reports.vo;
public class EmailAddress extends ValueObject{
private int emailId;
private UserVo user;
private String emailAddress;
public int getEmailId() {
return emailId;
}
public void setEmailId(int emailId) {
this.emailId = emailId;
}
public UserVo getUser() {
return user;
}
public void setUser(UserVo user) {
this.user = user;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
}
------------END EmailAddress.java --------------
HIBERNATE CONFIG AND MAPPING:
------------BEGIN hibernate.cfg.xml --------------
<?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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/testhibernate</property>
<property name="connection.username">root</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.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</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>
<!-- Drop and re-create the database schema on startup -->
<!-- <property name="hbm2ddl.auto">create</property> -->
<mapping resource="com/example/apps/reports/vo/mappings/UserVo.hbm.xml"/>
<mapping resource="com/example/apps/reports/vo/mappings/EmailAddress.hbm.xml"/>
</session-factory>
</hibernate-configuration>
------------END hibernate.cfg.xml --------------
------------BEGIN UserVo.hbm.xml --------------
<?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="com.example.apps.reports.vo.UserVo" table="users">
<id column="user_id" name="userId">
<generator class="native"/>
</id>
<property name="firstName" column="first_name"/>
<one-to-one cascade="all" name="email" class="com.example.apps.reports.vo.EmailAddress"/>
</class>
</hibernate-mapping>
------------END UserVo.hbm.xml --------------
------------BEGIN EmailAddress.hbm.xml --------------
<?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="com.example.apps.reports.vo.EmailAddress" table="email">
<id name="emailId" column="email_id">
<generator class="native"/>
</id>
<one-to-one name="user" foreign-key="user_id" class="com.example.apps.reports.vo.UserVo" />
<property name="emailAddress" column="email_address" type="java.lang.String"/>
</class>
</hibernate-mapping>
------------END EmailAddress.hbm.xml --------------
------------BEGIN create_mysql.sql --------------
drop database if exists testhibernate;
create database testHibernate;
use testHibernate;

drop table if exists users;
create table users(
user_id int not null auto_increment,
first_name varchar(30),
created_date datetime,
modified_date datetime,
created_by varchar(30),
modified_by varchar(30),
primary key(user_id)
);
drop trigger if exists aduit_users_insert;
DELIMITER //
create trigger aduit_users_insert before insert on users
for each row begin
set NEW.created_date = now();
if NEW.created_by is null then
SET NEW.created_by = 'SYSTEM';
end if;
end;//

drop trigger if exists audit_users_update//
create trigger audit_users_update before update on users
for each row
begin
set NEW.modified_date = now();
if NEW.modified_by is null then
SET NEW.modified_by = 'SYSTEM';
end if;
end; //
DELIMITER ;
insert into users (first_name) values('Test1');
insert into users (first_name) values('Test2');
insert into users (first_name) values('Test3');
insert into users (first_name) values('Test4');

drop table if exists email;
create table email(
email_id int not null auto_increment,
user_id int,
email_address varchar(70),
created_date datetime,
modified_date datetime,
created_by varchar(30),
modified_by varchar(30),
foreign key (user_id) references users(user_id),
primary key(email_id)
);

drop trigger if exists aduit_email_insert;
DELIMITER //
create trigger aduit_email_insert before insert on email
for each row begin
set NEW.created_date = now();
if NEW.created_by is null then
SET NEW.created_by = 'SYSTEM';
end if;
end;//

drop trigger if exists audit_email_update//
create trigger audit_email_update before update on email
for each row
begin
set NEW.modified_date = now();
if NEW.modified_by is null then
SET NEW.modified_by = 'SYSTEM';
end if;
end; //
DELIMITER ;
insert into email (user_id, email_address) values(1, 'Test1@here.com');
insert into email (email_address) values('Test4@here.com');
------------END create_mysql.sql --------------


Top
 Profile  
 
 Post subject: Which version of Hibernate?
PostPosted: Tue Feb 03, 2009 12:07 pm 
Beginner
Beginner

Joined: Wed Jul 09, 2008 5:34 am
Posts: 41
Location: Brno, Czech Republic
Which hibernate version are you using? I tested here with your almost exact code, on Hibernate 3.3.1 GA, and it worked as expected.

The sources I used are here: http://www.sendspace.com/file/3o3ja0


Top
 Profile  
 
 Post subject:
PostPosted: Tue Feb 03, 2009 12:20 pm 
Regular
Regular

Joined: Tue Dec 30, 2008 8:14 pm
Posts: 50
Try setting default-lazy="false" on the hibernate-mapping tag of both the mapping files.
My suspicion is that the Email object is proxied, and it is being accessed after the transaction has ended.

---
please rate


Top
 Profile  
 
 Post subject:
PostPosted: Tue Feb 03, 2009 4:11 pm 
Newbie

Joined: Fri Jan 30, 2009 5:08 pm
Posts: 17
Location: Florida
hibernate-distribution-3.3.1.GA-dist is the version I am using Mysql Version: '5.0.51a on Windows Vista Business Edition 64 bit.


Top
 Profile  
 
 Post subject: Can you check the uploaded code?
PostPosted: Tue Feb 03, 2009 4:21 pm 
Beginner
Beginner

Joined: Wed Jul 09, 2008 5:34 am
Posts: 41
Location: Brno, Czech Republic
warpedcodemonkey wrote:
hibernate-distribution-3.3.1.GA-dist is the version I am using Mysql Version: '5.0.51a on Windows Vista Business Edition 64 bit.


The OS should not be relevant, but I ran inside Eclipse on Fedora. MySQL version should not be relevant as well, but I have 5.0.67.

So, can you check the code I uploaded and run it on your environment? It works fine in my local, and should work fine in yours as well.


Top
 Profile  
 
 Post subject:
PostPosted: Tue Feb 03, 2009 4:27 pm 
Newbie

Joined: Fri Jan 30, 2009 5:08 pm
Posts: 17
Location: Florida
I set the hibernate.cfg.xml <property name="hbm2ddl.auto">create</property> when I create the database with the mappings one-to-one on both sides the email table is created with out a user_id column.

But when I change

<one-to-one name="user" foreign-key="user_id" class="com.example.apps.reports.vo.UserVo" />
to
<many-to-one name="user" column="user_id" class="com.example.apps.reports.vo.UserVo" />

in the EmailAddress.hmb.xml the table structure is created properly.

However user_id in the email table is still null.

Someone else suggested I go through this site : http://ndpsoftware.com/HibernateMappingCheatSheet.html I thought it would be helpful for others. I will try this on a linux machine when I get home, and see if that is making a difference.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 19 posts ]  Go to page 1, 2  Next

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.