-->
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.  [ 6 posts ] 
Author Message
 Post subject: Hibernate Annotations
PostPosted: Tue Mar 23, 2010 9:59 am 
Newbie

Joined: Tue Mar 23, 2010 9:48 am
Posts: 8
Hi.

i'm new to Hibernate Annotations please help me.?

I want create the one-to-many relationship with two tables only .

For eg I have configured through hbm.xml its fine what i expected :

<?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="Admin" table="user" lazy="false">
<id name="userid" type="long" column="user_id">
<generator class="increment"/>
</id>
<bag name="roles" lazy="false" cascade="all">
<key column="user_id"/>
<one-to-many class="Role"/>
</bag>

<property name="username" type="string" column="user_name"/>
<property name="password" type="string" column="password"/>
<property name="firstname" type="string" column="first_name"/>
<property name="lastname" type="string" column="last_name"/>
</class>

<class name="Role" table="role" >
<id name="roleid" type="long" column="role_id">
<generator class="increment"/>
</id>
<property name="usergroupname" type="string" column="user_group_name"/>
<property name="status" type="string" column="status"/>
</class>
</hibernate-mapping>

I need same result with Annotations ,what i mentioned above configuration.

I hope I can get Quick Reply.

Thanks,
Malli.


Top
 Profile  
 
 Post subject: Re: Hibernate Annotations
PostPosted: Wed Mar 24, 2010 7:35 am 
Expert
Expert

Joined: Tue Jun 16, 2009 3:36 am
Posts: 990
Quote:
I want create the one-to-many relationship with two tables only .


Then with Annotations you must declare it as bidirectional OneToMany relation with inverse-owner (=use mappedBy attribute),
otherwise a 3thd table (a join-table) is needed.

Code:
@Entity
@Table(name="user")
public class Admin {

@Id @GeneratedValue(strategy = GenerationType.TABLE)              // Increment does not exist with annotations
public long userid;

@OneToMany(mappedBy="user_id", fetch = FetchType.EAGER")
public Set<Role>roles = new HashSet<Role>();
...

}


@Entity
@Table(name="role")
public class Role {
@Id @GeneratedValue(strategy = GenerationType.TABLE)              // Increment does not exist with annotations
public long roleid;

@ManyToOne
public Admin user_id;

...

}


Top
 Profile  
 
 Post subject: Re: Hibernate Annotations
PostPosted: Thu Mar 25, 2010 7:17 am 
Newbie

Joined: Tue Mar 23, 2010 9:48 am
Posts: 8
Hi,

Thanks for your quick reply ..but still i'm getting exception.

i'm pasting the my java files and My TestCae file please help me out .where i did mistakes>

1.) Admin.java
=======================
package com.config.entities.oneToMany.twoTables.questinAndChoicwe;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table (name="user")
public class Admin {

@Id
@GeneratedValue(strategy=GenerationType.TABLE)
@Column(name="user_id")
private long id;

@Column(name="admin_name")
private String name ;

@OneToMany(mappedBy="user_id", fetch = FetchType.EAGER)
private Set<Role> role = new HashSet<Role>();

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 Set<Role> getRole() {
return role;
}

public void setRole(Set<Role> role) {
this.role = role;
}

}

2.) Role.java

package com.config.entities.oneToMany.twoTables.questinAndChoicwe;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="role")
public class Role {

@Id
@GeneratedValue(strategy=GenerationType.TABLE)
@Column(name="role_id")
private long id;

@Column(name="role_name")
private String rolename ;

@ManyToOne
private Admin user_id;


public long getId() {
return id;
}

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

public String getRolename() {
return rolename;
}

public void setRolename(String rolename) {
this.rolename = rolename;
}

public Admin getUser_id() {
return user_id;
}

public void setUser_id(Admin userId) {
user_id = userId;
}

}

3.) AdminTest.java

package com.config.entities.oneToMany.twoTables.questinAndChoicwe;

import java.util.HashSet;
import java.util.Set;
import junit.framework.TestCase;
import com.config.daoimp.AnnoTaionDAOSupport;
import com.config.hibernatetemplate.XCalDataSource;

public class AdminTest extends TestCase {

public void testQuestion(){
AnnoTaionDAOSupport<Admin> lDAO=(AnnoTaionDAOSupport)XCalDataSource.clsAppContext.getBean("myUserDAO");
Admin lAdmin = new Admin();
lAdmin.setName("abc");
Role lRole = new Role();
lRole.setRolename("manager");
Set<Role> lRoleSet = new HashSet<Role>();
lAdmin.setRole(lRoleSet);
lDAO.saveUser(lAdmin);
}
}


TABLE STRUCTURE :
==================

CREATE TABLE user(user_id INT NOT NULL AUTO_INCREMENT ,admin_name VARCHAR(10) , PRIMARY KEY(user_id));

CREATE TABLE role(role_id INT NOT NULL AUTO_INCREMENT,
user_id INT NOT NULL ,role_name VARCHAR(10),
PRIMARY KEY(role_id),
CONSTRAINT `0-11` FOREIGN KEY(user_id) REFERENCES user (user_id));






EXCEPTION :
===================



java.lang.ExceptionInInitializerError
at com.config.entities.oneToMany.twoTables.questinAndChoicwe.AdminTest.testQuestion(AdminTest.java:14)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at junit.framework.TestCase.runTest(TestCase.java:154)
at junit.framework.TestCase.runBare(TestCase.java:127)
at junit.framework.TestResult$1.protect(TestResult.java:106)
at junit.framework.TestResult.runProtected(TestResult.java:124)
at junit.framework.TestResult.run(TestResult.java:109)
at junit.framework.TestCase.run(TestCase.java:118)
at junit.framework.TestSuite.runTest(TestSuite.java:208)
at junit.framework.TestSuite.run(TestSuite.java:203)
at org.junit.internal.runners.OldTestClassRunner.run(OldTestClassRunner.java:35)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:46)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mySessionFactory' defined in class path resource [com/config/spring/persistence_annotations.xml]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Collection has neither generic type or OneToMany.targetEntity() defined: com.config.entities.oneToMany.twoTables.questinAndChoicwe.Question.choice
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1338)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:423)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.config.hibernatetemplate.XCalDataSource.<clinit>(XCalDataSource.java:16)
... 20 more
Caused by: org.hibernate.AnnotationException: Collection has neither generic type or OneToMany.targetEntity() defined: com.config.entities.oneToMany.twoTables.questinAndChoicwe.Question.choice
at org.hibernate.cfg.annotations.CollectionBinder.getCollectionType(CollectionBinder.java:521)
at org.hibernate.cfg.annotations.CollectionBinder.bind(CollectionBinder.java:417)
at org.hibernate.cfg.AnnotationBinder.processElementAnnotations(AnnotationBinder.java:1614)
at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:754)
at org.hibernate.cfg.AnnotationConfiguration.processArtifactsOfType(AnnotationConfiguration.java:546)
at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:291)
at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1162)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:673)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1369)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1335)
... 35 more


Top
 Profile  
 
 Post subject: Re: Hibernate Annotations
PostPosted: Thu Mar 25, 2010 8:55 am 
Expert
Expert

Joined: Tue Jun 16, 2009 3:36 am
Posts: 990
Quote:
Collection has neither generic type or OneToMany.targetEntity()


This message say that hibernate is missing the information about the target entity in the OneToMany relation,
you must either declare the collection using generics (=specify the target type between <>):

Code:
@OneToMany(mappedBy="user_id", ...)
private java.util.Set<Role> role = new java.util.HashSet<Role>();


or by specifying the target Entity as annotation attribute:

Code:
@OneToMany(mappedBy="user_id", targetEntity="Role", ...)
private java.util.Set role = new java.util.HashSet();


Top
 Profile  
 
 Post subject: Re: Hibernate Annotations
PostPosted: Thu Mar 25, 2010 9:30 am 
Newbie

Joined: Tue Mar 23, 2010 9:48 am
Posts: 8
Hi,

Sorry still i'm facing same problem..


Quote:
@OneToMany(mappedBy="user_id", ...)
private java.util.Set<Role> role = new java.util.HashSet<Role>();


as per above my modified java file like this

@OneToMany(mappedBy="user_id",targetEntity=Role.class)
private Set<Role> role = new HashSet<Role>();


can you please rectify me ,where i have did the mistakes..?

And my TestCase is fine ..Or i have written wrong ?

can you provide me if you have any samples ?

Thanks,
Malli.


Top
 Profile  
 
 Post subject: Re: Hibernate Annotations
PostPosted: Thu Mar 25, 2010 9:37 am 
Expert
Expert

Joined: Tue Jun 16, 2009 3:36 am
Posts: 990
May there be another OntToMany relation which causes the problem?

Please enable following loggings in your log4j.properties file and report the output, thanks

Code:
log4j.logger.org.hibernate.cfg=INFO
log4j.logger.org.hibernate.cfg.Environment=INFO


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