-->
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: Problem when mapping with annotations
PostPosted: Sun Feb 25, 2007 5:17 pm 
Newbie

Joined: Sun Feb 25, 2007 9:25 am
Posts: 4
Hello everybody, good afternoon. I'm having a little trouble in configuring an application with Java 5 + Spring + Hibernate. My hibernate versions are:

Hibernate version: 3.2

Mapping documents: I don't like XML configuration very much, so I'm using hibernate annotations, version 3.2

I'm trying to make a system, were it's first part is a user login. Everything seens well in the view and controller (I pass through my Validation class with no problem). My bean it's like this:
Code:
package br.com.beans;

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

import org.hibernate.validator.Length;
import org.hibernate.validator.NotNull;

@Entity
@Table (name="usuario")
public class Usuario {
   private Integer id;
   private String login;
   private String email;
   private char sexo;
   private String senha;
   
   /* ------------------ Constructors -------------------- */
   
   public Usuario(){}
   
   public Usuario(String login, String senha){
      this.login = login;
      this.senha = senha;
   }
   
   /* ---------------- Getters e Setters ---------------- */
   
   @Id
   @GeneratedValue(strategy=GenerationType.AUTO)
   public Integer getId() {
      return id;
   }
   @Column
   @NotNull
   public String getLogin() {
      return login;
   }
...


I'm using a mySQL 5 database, and there I have a table called "usuario" (low case) with one register already there (to test validation code), which I want the bean above to map.

I've created the hibernate configuration file just like this:
Code:
<!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.url">
         jdbc:mysql://localhost:3306/my_database
      </property>
      <property name="hibernate.connection.driver_class">
         com.mysql.jdbc.Driver
      </property>
      <property name="hibernate.connection.username">user</property>
      <property name="hibernate.connection.password">pass</property>
      <property name="hibernate.connection.pool_size">0</property>
      <property name="hibernate.dialect">
         org.hibernate.dialect.MySQLInnoDBDialect
      </property>
      <property name="hibernate.show_sql">false</property>
     
      <!-- "Import" the mapping resources here -->
      <mapping class="br.com.beans.Usuario"/>
     
   </session-factory>
</hibernate-configuration>


I've a DAO class, which extends HibernateDaoSupport, and I instanciate it like this:

Code:
public UsuarioDAO(){
   factory = new AnnotationConfiguration()
         .configure()
         .buildSessionFactory();
}


Where "factory" its a private SessionFactory variable. I'm also using Jboss 4.0.5, and in its logs I see the following:
Code:
...
INFO  [Version] Hibernate Annotations 3.2.0.GA
INFO  [Configuration] configuring from resource: /hibernate.cfg.xml
INFO  [Configuration] Configuration resource: /hibernate.cfg.xml
[Configuration] Configured SessionFactory: null
[AnnotationBinder] Binding entity from annotated class: br.com.beans.Usuario
INFO  [EntityBinder] Bind entity br.com.beans.Usuario on table usuario
...


Which made me think everything was ok with the mapping part (for now I've only that bean). However, when I try some code to interact with the database, for example, retrieve a list, with this code
Code:
List result = session.createQuery("from "+Usuario.class.getName()).list();


I get the following warn on my jboss log:
Code:
WARN  [QuerySplitter] no persistent classes found for query class: from br.com.beans.Usuario


To test, I also created an insert code:
Code:
Usuario teste = new Usuario("teste", "teste");
teste.setEmail("teste@teste.com");
teste.setSexo('M');
getHibernateTemplate().save(teste);


Which gives the following error:
Code:
ERROR [[locadora]] Servlet.service() for servlet locadora threw exception
org.hibernate.MappingException: Unknown entity: br.com.beans.Usuario


And I have no clue up to now were I'm I doing wrong. I tried also to change DAO initialization to:
Code:
AnnotationConfiguration cfg = new AnnotationConfiguration();
cfg.configure();
cfg.addAnnotatedClass(Usuario.class);
factory = cfg.buildSessionFactory();


Just to see what'd happen, but nothin changed, still got the same erros. Could anyone help me to find what is causing the error?

Thanks for the attention, and I'm sorry if I made any english writing mistake, I need some more praticing (portuguese is my natural language ^^)


Top
 Profile  
 
 Post subject:
PostPosted: Mon Feb 26, 2007 12:06 am 
Expert
Expert

Joined: Tue Jan 30, 2007 12:45 am
Posts: 283
Location: India
Hi Ryoko,


Your HBM file is not register with session factory.

it should be register in
<mapping resource/>

But no idea how annotaion work.

_________________
Dharmendra Pandey


Top
 Profile  
 
 Post subject:
PostPosted: Mon Feb 26, 2007 7:28 pm 
Newbie

Joined: Sun Feb 25, 2007 9:25 am
Posts: 4
That's my big trouble, I'm not using *.hbm files, I'm trying it with annotations. I've already done some systems with XML mapping, but I didn't like that very much, so I'm trying with annotations now.

But, I'm stucked at this problem, and, up to now, didn't find anyone who have an ideia of what it's wrong.

But thanks for replying.

Anyone have any ideia?


Top
 Profile  
 
 Post subject:
PostPosted: Tue Feb 27, 2007 8:46 pm 
Newbie

Joined: Sun Feb 25, 2007 9:25 am
Posts: 4
Well, it's turning out to be very complicated problem. Discussing with a friend, I've made some changes in my files, starting with the hibernate configuration, I've removed the line
Code:
<mapping class="br.com.froes.helpdesk.beans.Usuario"/>


And now my hibernate.cfg.xml file it's just like this:
Code:
<!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.url">
         jdbc:mysql://localhost:3306/helpdesk
      </property>
      <property name="hibernate.connection.driver_class">
         com.mysql.jdbc.Driver
      </property>
      <property name="hibernate.connection.username">user</property>
      <property name="hibernate.connection.password">pass</property>
      <property name="hibernate.connection.pool_size">0</property>
      <property name="hibernate.dialect">
         org.hibernate.dialect.MySQLInnoDBDialect
      </property>
      <property name="hibernate.show_sql">false</property>
      
   </session-factory>
</hibernate-configuration>


I've have read in some tutorials that you need to put the mapping tag even when you're using annotations, but, well, even removing the line, my jboss console doesn't show any errors on startup, and I still can see the following info:
Code:
[Version] Hibernate Annotations 3.2.0.GA
[Configuration] configuring from resource: /hibernate.cfg.xml
[Configuration] Configuration resource: /hibernate.cfg.xml
[Configuration] Configured SessionFactory: null
[AnnotationBinder] Binding entity from annotated class: br.com.beans.Usuario
[EntityBinder] Bind entity br.com.beans.Usuario on table usuario


If the mapping is wrong, shoudn't it be throwing some errors, like some bind exception or something like this?

In the other hand, I still get the same error. I changed the query on my DAO to:
Code:
List result = session.createQuery("from Usuario usuario").list();


And the error message remains:
Code:
org.hibernate.hql.ast.QuerySyntaxException: Usuario is not mapped [from Usuario usuario]
   at org.hibernate.hql.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:158)
   at org.hibernate.hql.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:87)
   at org.hibernate.hql.ast.tree.FromClause.addFromElement(FromClause.java:70)
   at org.hibernate.hql.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:255)
   at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3056)
...


It doesn't make difference, in the constructor if I try this:
Code:
public UsuarioDAO(){
      factory = new AnnotationConfiguration()
            .configure()
            .buildSessionFactory();
   }


Or this:
Code:
public UsuarioDAO(){
      AnnotationConfiguration cfg = new AnnotationConfiguration();
      cfg.configure();
      cfg.addAnnotatedClass(Usuario.class);
      factory = cfg.buildSessionFactory();
   }


The error remains the same. I've passed thought others foruns, and up to now, no solution. Have anyone ever created an application using annotations instead of XML files? I'm I missing some point in the configuration?

Thanks!


Top
 Profile  
 
 Post subject:
PostPosted: Tue Feb 27, 2007 10:26 pm 
Newbie

Joined: Sun Oct 08, 2006 8:03 am
Posts: 14
I use annotations, and want to get away from XML as much as possible.
But I still need to put one line for each mapped class in the hibernate.cfg.xml.
Here's my file, with some class names changed to mirror yours.
Note the 3 <mapping> elements near the end.

Code:
<!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="dialect">
         org.hibernate.dialect.MySQLDialect
      </property>
      <property name="hbm2ddl.auto">update</property>
      <property name="show_sql">true</property>
      <property name="hibernate.generate_statistics">true</property>
      <property name="hibernate.cache.provider_class">
         org.hibernate.cache.EhCacheProvider
      </property>
      <mapping class="br.com.beans.Usario" />
      <mapping class="br.com.beans.Address" />
      <mapping class="br.com.beans.Account" />
   </session-factory>
</hibernate-configuration>


John.


Top
 Profile  
 
 Post subject: Spring + JPA/Hibernate
PostPosted: Wed Aug 13, 2008 5:50 pm 
Newbie

Joined: Wed Aug 13, 2008 3:51 pm
Posts: 2
Well, this seems to be an old topic but I'm facing a similar problem in one of my Web projects.

I'm trying to integrate Spring with JPA/Hibernate Annotations and I'm using the following platform (a list of JAR files is available in the end of this post):
    Java 1.5.0_12
    JBOSS 4.2.2.GA
    Spring Framework 2.5.5
    Hibernate 3.2.6
    Hibernate Annotations 3.3.1.GA
    Hibernate EntityManager 3.3.2.GA
    Hibernate Search 3.0.1.GA

In a few words I'm not able to retrieve the contents of the only single row available in the DB table. The application always return zero rows from the DB as the following error is displayed on the server log:

Code:
2008-08-13 18:16:51,654 INFO  [STDOUT] 18:16:51,654 WARN  [QuerySplitter] no persistent classes found for query class:  from br.com.certisign.domain.UserImpl



I have configured a Oracle DB using a persistence.xml file and created a entity class UserImpl using JPA annotations. Theres also a DAO UserDaoImpl that extends the JpaDaoSupport utility class available in Spring. The UserDaoImpl.get (String) method (see below) is the one that triggers the DB query and returns nothing but a null List of users.

My code follows.


persistence.xml:
Code:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
   version="1.0">
   <persistence-unit name="poc">
      <provider>org.hibernate.ejb.HibernatePersistence</provider>
      <properties>
         <!-- Only scan and detect annotated entities -->
         <property name="hibernate.archive.autodetection" value="class"/>
         
         <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle9iDialect"/>
         <property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver"/>
         <property name="hibernate.connection.url" value="jdbc:oracle:thin:@192.168.15.90:1521:ICPDESEN"/>
         <property name="hibernate.connection.username" value="teste"/>
         <property name="hibernate.connection.password" value="teste"/>
         
         <property name="hibernate.c3p0.min_size" value="0"/>
         <property name="hibernate.c3p0.max_size" value="10"/>
         <property name="hibernate.c3p0.timeout" value="1000"/>
         <property name="hibernate.c3p0.max_statements" value="50"/>
         <property name="hibernate.c3p0.idle_test_period" value="3000"/>
      </properties>
   </persistence-unit>
</persistence>



My entity class is the one below, UserImpl.java. I guess the name is not that good but it's a test anyway.
Code:
package br.com.certisign.domain;

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

import br.com.certisign.support.logging.Describable;

@Entity
@Table(name = "POC_USER")
public class UserImpl implements User, Describable {
   private Long id;
   private String firstName;
   private String lastName;
   private String username;
   private String password;

   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   public Long getId() {
      return id;
   }

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

   @Column(name = "firstName")
   public String getFirstName() {
      return firstName;
   }

   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }

   @Column(name = "lastName")
   public String getLastName() {
      return lastName;
   }

   public void setLastName(String lastName) {
      this.lastName = lastName;
   }

   @Column(name = "username")
   public String getUsername() {
      return username;
   }

   public void setUsername(String username) {
      this.username = username;
   }

   @Column(name = "password")
   public String getPassword() {
      return password;
   }

   public void setPassword(String password) {
      this.password = password;
   }

   public String describe() {
      StringBuffer description = new StringBuffer("[").append(
            this.getClass().getCanonicalName()).append(": ").append("id=")
            .append(id).append(", firstName=").append(firstName).append(
                  ", lastName:").append(lastName).append(", username=")
            .append(username).append(", password=").append(password)
            .append("]");
      return description.toString();
   }
}



I have also created a Spring DAO (UserDaoImpl) as follows:
Code:
package br.com.certisign.persistence;

import java.util.List;

import org.springframework.orm.jpa.support.JpaDaoSupport;

import br.com.certisign.domain.User;

public class UserDaoImpl extends JpaDaoSupport implements UserDao {

   public void save(User user) {
      getJpaTemplate().persist(user);
   }
   
   @SuppressWarnings("unchecked")
   public List<User> get(String username) {
      return getJpaTemplate().find(" from br.com.certisign.domain.UserImpl ");
   }
}



This is my applicationContext.xml file:
Code:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">

   <!-- Injected UserDao. -->
   <bean id="userDao" class="br.com.certisign.persistence.UserDaoImpl">
      <property name="entityManagerFactory" ref="entityManagerFactory"/>
   </bean>
   
   <!-- Action configuration -->
   <!-- Injected authentication service. -->
   <bean id="authenticationService" class="br.com.certisign.webpoc.service.AuthenticationServiceImpl">
      <property name="userDao" ref="userDao"/>
   </bean>

   <!-- Service configuration -->
   <!-- Persistence configuration. -->
   <bean id="entityManagerFactory"
         class = "org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"/>
   
   <!-- Overall configuration -->
   <!-- Injected User. -->
   <bean id="user" class="br.com.certisign.domain.UserImpl"/>

   <!-- AspectJ autoproxing configuration. -->
   <aop:aspectj-autoproxy />
</beans>



Here's a list of JAR files used in this project (there's also some Struts 2 and Sitemesh stuff):
    ant-antlr-1.6.5.jar
    antlr-2.7.6.jar
    asm-attrs.jar
    asm.jar
    aspectjrt.jar
    aspectjweaver.jar
    c3p0-0.9.1.jar
    TestCore.jar (THE DAO AND ENTITY CLASSES ARE INCLUDED IN THIS JAR)
    cglib-2.1.3.jar
    commons-beanutils-1.6.jar
    commons-collections-2.1.1.jar
    commons-logging-1.1.jar
    commons-validator-1.3.0.jar
    dom4j-1.6.1.jar
    ejb3-persistence.jar
    freemarker-2.3.8.jar
    hibernate-annotations.jar
    hibernate-commons-annotations.jar
    hibernate-entitymanager.jar
    hibernate-search.jar
    hibernate-validator.jar
    hibernate3.jar
    javassist.jar
    jta.jar
    log4j-1.2.15.jar
    lucene-core-2.3.2.jar
    ognl-2.6.11.jar
    ojdbc14.jar
    sitemesh-2.3.jar
    spring.jar
    struts2-core-2.0.11.jar
    struts2-sitemesh-plugin-2.0.11.1.jar
    struts2-spring-plugin-2.0.11.1.jar
    xwork-2.0.4.jar


Could you help me with that, please?

Thanks in advance,
Marcel


Top
 Profile  
 
 Post subject:
PostPosted: Thu Aug 14, 2008 2:28 am 
Newbie

Joined: Thu Jul 17, 2008 2:00 am
Posts: 4
Location: INDIA
Have u included the following code in your applicationContext.xml???

<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

<tx:annotation-driven transaction-manager="transactionManager" />


Top
 Profile  
 
 Post subject:
PostPosted: Fri Aug 15, 2008 10:35 am 
Newbie

Joined: Wed Aug 13, 2008 3:51 pm
Posts: 2
First of all, thanks for your help but I tried adding both tags to my applicationContext.xml but nothing changed.

By the way, I do not have any transaction management functionality in my code but I added the configuration anyway. I also tried without that with no success.

See the code below:
Code:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">

   <!-- Injected UserDao. -->
   <bean id="userDao" class="br.com.certisign.persistence.UserDaoImpl">
      <property name="entityManagerFactory" ref="entityManagerFactory"/>
   </bean>

   <!-- Added postprocessor and txn support as suggested in the Hibernate Forum -->   
   <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
   <bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
   <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
      <property name="entityManagerFactory" ref="entityManagerFactory"/>
      <property name="jpaDialect" ref="jpaDialect"/>
   </bean>
   <tx:annotation-driven transaction-manager="transactionManager" />
   
   <!-- Action configuration -->
   <!-- Injected authentication service. -->
   <bean id="authenticationService" class="br.com.certisign.webpoc.service.AuthenticationServiceImpl">
      <property name="userDao" ref="userDao"/>
   </bean>

   <!-- Service configuration -->
   <!-- Persistence configuration. -->
   <bean id="entityManagerFactory"
         class = "org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"/>
   
   <!-- Overall configuration -->
   <!-- Injected User. -->
   <bean id="user" class="br.com.certisign.domain.UserImpl"/>

   <!-- AspectJ autoproxing configuration. -->
   <aop:aspectj-autoproxy />
</beans>


Any other suggestion?

Besides that I've got another question:

I added that row manually to the DB, I have not used the getJpaTemplate().persist(...) method to do that. Does it matter? I guess not...

Thanks again!


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.