-->
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: IllegalArgumentException occurred while calling setter of
PostPosted: Sat Jan 27, 2007 2:42 pm 
Newbie

Joined: Sat Jan 27, 2007 2:03 pm
Posts: 6
Location: Dallas, TX - USA
I am getting this error when running a jUnit to test everything (mapping, tables, etc). What am I doing wrong?


Here are the details:


Hibernate version: 3.2

Database MySQL Driver: mysql-connector-java-5.0.4-bin.jar

Full stack trace of exception:

org.hibernate.PropertyAccessException: IllegalArgumentException occurred while calling setter of rg.model.UserRole.userId
at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:104)
at org.hibernate.tuple.AbstractEntityTuplizer.setPropertyValues(AbstractEntityTuplizer.java:330)
at org.hibernate.tuple.PojoEntityTuplizer.setPropertyValues(PojoEntityTuplizer.java:188)
at org.hibernate.persister.entity.AbstractEntityPersister.setPropertyValues(AbstractEntityPersister.java:3232)
at org.hibernate.engine.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:126)
at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:842)
at org.hibernate.loader.Loader.doQuery(Loader.java:717)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:224)
at org.hibernate.loader.Loader.doList(Loader.java:2145)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2029)
at org.hibernate.loader.Loader.list(Loader.java:2024)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:375)
at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:308)
at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:153)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1129)
at org.hibernate.impl.QueryImpl.list(QueryImpl.java:79)
at rg.dao.hibernate.HibernateTest.testEverything(HibernateTest.java:54)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.internal.runners.TestMethodRunner.executeMethodBody(TestMethodRunner.java:99)
at org.junit.internal.runners.TestMethodRunner.runUnprotected(TestMethodRunner.java:81)
at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34)
at org.junit.internal.runners.TestMethodRunner.runMethod(TestMethodRunner.java:75)
at org.junit.internal.runners.TestMethodRunner.run(TestMethodRunner.java:45)
at org.junit.internal.runners.TestClassMethodsRunner.invokeTestMethod(TestClassMethodsRunner.java:71)
at org.junit.internal.runners.TestClassMethodsRunner.run(TestClassMethodsRunner.java:35)
at org.junit.internal.runners.TestClassRunner$1.runUnprotected(TestClassRunner.java:42)
at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34)
at org.junit.internal.runners.TestClassRunner.run(TestClassRunner.java:52)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:38)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
Caused by: java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:42)
... 36 more


ERROR logs:
01/27/07 11:32:06 AM org.hibernate.property.BasicPropertyAccessor$BasicSetter 94 ERROR: IllegalArgumentException in class: rg.model.UserRole, setter method of property: userId
01/27/07 11:32:06 AM org.hibernate.property.BasicPropertyAccessor$BasicSetter 94 ERROR: IllegalArgumentException in class: rg.model.UserRole, setter method of property: userId
01/27/07 11:32:06 AM org.hibernate.property.BasicPropertyAccessor$BasicSetter 98 ERROR: expected type: java.lang.Long, actual value: rg.model.User$$EnhancerByCGLIB$$4ad2997d
01/27/07 11:32:06 AM org.hibernate.property.BasicPropertyAccessor$BasicSetter 98 ERROR: expected type: java.lang.Long, actual value: rg.model.User$$EnhancerByCGLIB$$4ad2997d

Hibernate Configuration (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">
<!--
* @(#)  $Id: hibernate.cfg.xml,v 1.7 2007/01/27 17:39:51 rubens_carlos Exp $
-->
<hibernate-configuration>
  <session-factory>

    <!--  properties  -->
    <property name="myeclipse.connection.profile">MySQL DBTEST</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
    <property name="hibernate.connection.username">rubens</property>
    <property name="hibernate.connection.password">rubens</property>
    <property name="hibernate.current_session_context_class">thread</property>
    <property name="hibernate.connection.pool_size">1</property>
    <property name="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    <property name="hibernate.use_sql_comments">true</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.format_sql">true</property>
    <property name="hibernate.lazy">false</property>
    <property name="hibernate.cglib.use_reflection_optimizer">false</property>

    <!--  mappings  -->
    <mapping resource="rg/dao/hibernate/User.hbm.xml" />
    <mapping resource="rg/dao/hibernate/UserRole.hbm.xml" />
    <mapping resource="rg/dao/hibernate/Person.hbm.xml" />
    <mapping resource="rg/dao/hibernate/Phone.hbm.xml" />
    <mapping resource="rg/dao/hibernate/Address.hbm.xml" />
    <mapping resource="rg/dao/hibernate/Internet.hbm.xml" />
  </session-factory>
</hibernate-configuration>


Hibernate Configuration (hibernate.properties):
hibernate.cglib.use_reflection_optimizer = false

Mapping documents (User.hbm.xml):
Code:
<?xml version="1.0" encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<!--
* @(#)  $Id: User.hbm.xml,v 1.11 2007/01/27 17:39:51 rubens_carlos Exp $
-->
<hibernate-mapping package="rg.model">
  <class name="User" table="USER">
    <id name="id" column="ID" type="long" unsaved-value="0">
      <generator class="identity" />
    </id>
    <natural-id>
      <property name="userName" column="USER_NAME" type="string"
        not-null="true" />
    </natural-id>
    <property name="password" column="PASSWORD" type="string"
      not-null="true" />
    <property name="active" column="ACTIVE" type="boolean" />
    <property name="lastLogin" column="LAST_LOGIN" type="timestamp" />
    <sql-insert>INSERT INTO USER
                (USER_NAME, PASSWORD, ACTIVE, LAST_LOGIN)
                VALUES
                (?, PASSWORD(?), ?, SYSDATE())</sql-insert>
  </class>
</hibernate-mapping>


Mapping documents (UserRole.hbm.xml):
Code:
<?xml version="1.0" encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<!--
* @(#)  $Id: UserRole.hbm.xml,v 1.9 2007/01/27 17:39:51 rubens_carlos Exp $
-->
<hibernate-mapping package="rg.model">
  <class name="UserRole" table="USER_ROLE">
    <id name="id" column="ID" type="long" unsaved-value="0">
      <generator class="identity" />
    </id>
    <natural-id>
      <many-to-one name="userId" column="USER_ID" class="User" />
    </natural-id>
    <property name="roleName" column="ROLE_NAME" type="string"
      not-null="true" />
    <property name="privilege" column="PRIVILEGE" type="string"
      not-null="true" />
  </class>
</hibernate-mapping>


Create Table SQL Code (MySQL):
Code:
--
-- @(#) $Id: create_tables.sql,v 1.19 2007/01/27 17:40:33 rubens_carlos Exp $
--
USE TEST;

--
-- User: user id, password, email, ...
--
CREATE TABLE IF NOT EXISTS USER (
  ID                   BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  USER_NAME            VARCHAR (60) NOT NULL,
-- PASSWORD must be greater than 41 bytes to hold a hashed encrypted value.
  PASSWORD             VARCHAR (50) NOT NULL,
  ACTIVE               BOOLEAN  DEFAULT FALSE NOT NULL,
  LAST_LOGIN           DATETIME NULL,
  CONSTRAINT USER_PK
    PRIMARY KEY (ID),
  CONSTRAINT USER_UNQ
    UNIQUE (USER_NAME) );

--
-- User Roles: role user has on the system.
--
CREATE TABLE IF NOT EXISTS USER_ROLE (
  ID                   BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  USER_ID              BIGINT UNSIGNED NOT NULL,
  ROLE_NAME            ENUM('ADMIN', 'USER', 'OTHER') DEFAULT 'USER' NOT NULL,
  PRIVILEGE            ENUM('WRITE', 'READ', 'OTHER') DEFAULT 'READ' NOT NULL,
  CONSTRAINT USER_ROLE_PK
    PRIMARY KEY (ID),
  CONSTRAINT USER_ROLE_FK
    FOREIGN KEY (USER_ID)
    REFERENCES USER (ID)
    ON DELETE CASCADE );


HibernateTest.java
Code:
/**
* @(#) $Id: HibernateTest.java,v 1.3 2007/01/24 22:57:10 rubens_carlos Exp $
*/
package rg.dao.hibernate;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.junit.Test;
import org.junit.runner.JUnitCore;

import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.Query;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.persister.entity.EntityPersister;

/**
* @author Rubens Gomes
*/
public final class HibernateTest {

    /**
     * This code has been pulled from Hibernate site.  A simple junit
     * that iterates the whole Hibernate configuration checking if
     * the SQL tables and columns are right.
     *
     */
    @Test
    public void testEverything() {
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        if(sessionFactory == null)
            throw new NullPointerException("cannot retrieve Hibernate factory.");

        Map metadata = sessionFactory.getAllClassMetadata();
        if(metadata == null)
            throw new NullPointerException("cannot retrieve Class Metadata.");

        for (Iterator i=metadata.values().iterator(); i.hasNext();) {
            Session session = sessionFactory.openSession();
            List results = null;
            try {
                EntityPersister persister = (EntityPersister) i.next();
                ClassMetadata classMeta = persister.getClassMetadata();
                if (classMeta == null)
                    throw new NullPointerException("cannot retrieve class meta data");

                String className = classMeta.getEntityName();
                Query query = session.createQuery("from " + className + " c");
                if (query == null)
                    throw new NullPointerException("query is null");

                results = query.list();
            } finally {
                if(session != null) {
                    session.close();
                    session = null;
                }
                if(results != null){
                    results.clear();
                    results=null;
                }
            }
        }
    }

    /**
     * A main method in case IDE cannot run above tests.
     * @param args  no strings are to be passed.
     */
    public static void main(String args[]) {
        JUnitCore.main("rg.dao.hibernate.HibernateTest");
    }
}


Code for UserRole.java:
Code:
/**
* @(#) $Id: UserRole.java,v 1.8 2007/01/27 17:39:51 rubens_carlos Exp $
*/
package rg.model;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.CompareToBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

/**
* Persistent Object for corresponding User Role Table.
*
* @author Rubens Gomes
*/
public class UserRole extends BaseObject {

    static final long serialVersionUID = 1;

    private Long id;
    private Long userId;

    private String roleName;
    private String privilege;

    /**
     * no-arg constructor.
     */
    UserRole() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @return the id
     */
    public Long getId() {
        return this.id;
    }

    /**
     * @param id the id to set
     */
    public void setId(Long id) {
        this.id = id;
    }

    /**
     * @return the privilege
     */
    public String getPrivilege() {
        return this.privilege;
    }

    /**
     * @param privilege the privilege to set
     */
    public void setPrivilege(String privilege) {
        this.privilege = privilege;
    }

    /**
     * @return the roleName
     */
    public String getRoleName() {
        return this.roleName;
    }

    /**
     * @param roleName the roleName to set
     */
    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }


    /**
     * @return the userId
     */
    public Long getUserId() {
        return this.userId;
    }

    /**
     * @param userId the userId to set
     */
    public void setUserId(Long userId) {
        this.userId = userId;
    }

    /**
     * @see java.lang.Comparable#compareTo(Object)
     */
    public int compareTo(final Object object) {
        UserRole myClass = (UserRole) object;
        return new CompareToBuilder()
            .append(this.privilege, myClass.privilege)
            .append(this.roleName, myClass.roleName)
            .toComparison();
    }

    /**
     * @see java.lang.Object#equals(Object)
     */
    public boolean equals(final Object object) {
        if (!(object instanceof UserRole)) {
            return false;
        }
        UserRole rhs = (UserRole) object;
        return new EqualsBuilder()
            .append(this.privilege, rhs.privilege)
            .append(this.roleName, rhs.roleName)
            .isEquals();
    }

    /**
     * @see java.lang.Object#toString()
     */
    public String toString() {
        return new ToStringBuilder(this, ToStringStyle.DEFAULT_STYLE)
            .append("roleName", this.roleName)
            .append("privilege", this.privilege)
            .toString();
    }

    /**
     * @see java.lang.Object#hashCode()
     */
    public int hashCode() {
        return new HashCodeBuilder(386303675, -2076996339)
            .append(this.privilege)
            .append(this.roleName)
            .toHashCode();
    }

}


Code for User.java:
Code:
/**
* @(#) $Id: User.java,v 1.8 2007/01/27 17:39:51 rubens_carlos Exp $
*/
package rg.model;

import java.util.Date;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.CompareToBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

/**
* Persistent Object for corresponding User Table.
*
* @author Rubens Gomes
*/
public class User extends BaseObject {

    static final long serialVersionUID = 1;

    private Long id;

    private String userName;
    private String password;
    private boolean active;
    private Date lastLogin;

    /**
     * no-arg constructor.
     */
    User() {
        super();
        // TODO Auto-generated constructor stub
    }


    /**
     * @return the userName
     */
    public String getUserName() {
        return this.userName;
    }


    /**
     * @param userName the userName to set
     */
    public void setUserName(String userName) {
        this.userName = userName;
    }


    /**
     * @return the lastLogin
     */
    public Date getLastLogin() {
        return this.lastLogin;
    }


    /**
     * @param lastLogin the lastLogin to set
     */
    public void setLastLogin(Date lastLogin) {
        this.lastLogin = lastLogin;
    }


    /**
     * @return the password
     */
    public String getPassword() {
        return this.password;
    }


    /**
     * @param password the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }


    /**
     * @return the active
     */
    public boolean isActive() {
        return this.active;
    }


    /**
     * @param active the active to set
     */
    public void setActive(boolean active) {
        this.active = active;
    }



    /**
     * @return the id
     */
    public Long getId() {
        return this.id;
    }


    /**
     * @param id the id to set
     */
    public void setId(Long id) {
        this.id = id;
    }


    /**
     * @see java.lang.Comparable#compareTo(Object)
     */
    public int compareTo(final Object object) {
        User myClass = (User) object;
        return new CompareToBuilder()
            .append(this.active, myClass.active)
            .append(this.password, myClass.password)
            .append(this.userName, myClass.userName)
            .append(this.lastLogin, myClass.lastLogin)
            .toComparison();
    }


    /**
     * @see java.lang.Object#equals(Object)
     */
    public boolean equals(final Object object) {
        if (!(object instanceof User)) {
            return false;
        }
        User rhs = (User) object;
        return new EqualsBuilder()
            .append(this.active, rhs.active)
            .append(this.password, rhs.password)
            .append(this.userName, rhs.userName)
            .append(this.lastLogin, rhs.lastLogin)
            .isEquals();
    }


    /**
     * @see java.lang.Object#hashCode()
     */
    public int hashCode() {
        return new HashCodeBuilder(-1756432983, 155700371)
            .append(this.active)
            .append(this.password)
            .append(this.userName)
            .append(this.lastLogin)
            .toHashCode();
    }


    /**
     * @see java.lang.Object#toString()
     */
    public String toString() {
        return new ToStringBuilder(this, ToStringStyle.DEFAULT_STYLE)
            .append("lastLogin", this.lastLogin)
            .append("active", this.active)
            .append("password", this.password)
            .append("userName", this.userName)
            .toString();
    }
}


Thanks.

_________________
--
Rubens Gomes
www.rubens-gomes.com


Top
 Profile  
 
 Post subject:
PostPosted: Mon Jan 29, 2007 7:50 pm 
Expert
Expert

Joined: Thu Dec 23, 2004 9:08 pm
Posts: 2008
Your mapping from UserRole to User is declared as a many-to-one called userId, class="User". So Hibernate loads the appropriate instance of User, and calls userrule.setUserId(user). That's not going to work.

Change the name of the many-to-one to user (not userId), and change the methods in UserRole to
Code:
public User getUser() { ... }
public void setUser(User user) { ... }
Alternatively, you could map userId as a property, but I don't see any reason to do that.

_________________
Code tags are your friend. Know them and use them.


Top
 Profile  
 
 Post subject:
PostPosted: Tue Jan 30, 2007 8:05 pm 
Newbie

Joined: Sat Jan 27, 2007 2:03 pm
Posts: 6
Location: Dallas, TX - USA
Works great now.

Thank you!

Rubens.

_________________
--
Rubens Gomes
www.rubens-gomes.com


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.