-->
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: Odd Criteria problem
PostPosted: Wed Sep 08, 2004 5:06 am 
Regular
Regular

Joined: Fri Jul 16, 2004 3:04 pm
Posts: 52
Location: Wiltshire UK
Hi I have found an odd problem with a Criteria query. In the following code the test fails at
Quote:
assertNotNull("account2 should not be null, id=" + id, account2);
the Criteria query using the email address works, but the one using the id field doesn't work! I can see the record in the database with the id I am looking up. My findById() & getAccountForEmailAddress() methods look almost identical & I can't work out why the getAccountForEmailAddress() method works & the findById() method doesn't?


Any help appreciated.

Thanks
Paul


Test Method
Code:
public void testSaveFindDeleteObject() throws Exception {
        Account account = TestConstants.getTestAccount();
        Long id = account.getId();
        assertNotNull("id should not be null",id);
        try {
            HibernateUtil.saveObject(account);
        } catch (PersistenceException e) {
            fail(e.getMessage());
        }

        Account debugAccount = ACCOUNT_MANAGER.getAccountForEmailAddress(TestConstants.TEST_EMAIL_ADDRESS);
        assertNotNull("debugAccount is null",debugAccount);
        Long debugId = debugAccount.getId();
        assertEquals("id should equal debugId",id,debugId);

        Account account2 = null;
        try {
            account2 = (Account) HibernateUtil.findById(id, Account.class);
        } catch (PersistenceException e) {
            fail(e.getMessage());
        }
        assertNotNull("account2 should not be null, id=" + id, account2); // fails here
        assertEquals("account should equal account2", account, account2);

        try {
            HibernateUtil.deleteObject(account2);
        } catch (PersistenceException e) {
            fail(e.getMessage());
        }

        Account account3 = null;
        try {
            account3 = (Account) HibernateUtil.findById(id, Account.class);
        } catch (PersistenceException e) {
            fail(e.getMessage());
        }
        assertNull("account3 should be null", account3);

    }



Hibernate version:2.1.6

Mapping documents:
Code:
<hibernate-mapping>

    <class name="com.easylists.Account" table="ACCOUNT">

        <id name="hibernateId" type="long" column="HIBERNATE_ID">
            <meta attribute="scope-set">protected</meta>
            <generator class="native"/>
        </id>

        <version name="version" column="VERSION"/>

        <property name="id" type="long">
            <column name="ID" not-null="true"/>
        </property>

        <property name="active" type="boolean">
            <column name="ACTIVE" not-null="true"/>
        </property>

        <property name="hasBeenActivated" type="boolean">
            <column name="HAS_BEEN_ACTIVATED" not-null="true"/>
        </property>

        <property name="createdDate" type="java.util.Date">
            <column name="CREATED_DATE" not-null="true"/>
        </property>

        <property name="expiryDate" type="java.util.Date">
            <column name="EXPIRY_DATE"/>
        </property>

        <property name="title" type="string">
            <meta attribute="use-in-tostring">true</meta>
            <column name="TITLE" not-null="true"/>
        </property>

        <property name="forename" type="string">
            <meta attribute="use-in-tostring">true</meta>
            <column name="FORENAME" not-null="true"/>
        </property>

        <property name="surname" type="string">
            <column name="SURNAME" not-null="true"/>
        </property>

        <property name="emailAddress" type="string">
            <column name="EMAIL_ADDRESS" not-null="true" unique="true" index="EMAIL_IDX"/>
        </property>

        <property name="password" type="string">
            <column name="PASSWORD" not-null="true"/>
        </property>

        <property name="quota" type="int">
            <column name="QUOTA"/>
        </property>

        <one-to-one name="address" class="com.easylists.Address" constrained="true" cascade="all"/>
       
    </class>

</hibernate-mapping>


Account Class
Code:
public class Account implements Serializable {
    /**
     * only to be used by Hibernate
     */
    private Long hibernateId;

    /**
     * identifier field
     */
    private Long id;

    /**
     * nullable persistent field
     */
    private boolean active;

    /**
     * nullable persistent field
     */
    private boolean hasBeenActivated;

    /**
     * nullable persistent field
     */
    private Date createdDate;

    /**
     * nullable persistent field
     */
    private Date expiryDate;

    /**
     * nullable persistent field
     */
    private String title;

    /**
     * nullable persistent field
     */
    private String forename;

    /**
     * nullable persistent field
     */
    private String surname;

    /**
     * nullable persistent field
     */
    private String emailAddress;

    /**
     * nullable persistent field
     */
    private String password;

    /**
     * nullable persistent field
     */
    private int quota;

    /**
     * nullable persistent field
     */
    private int version;

    /**
     * nullable persistent field
     */
    private com.easylists.Address address;

    /**
     * default constructor
     */
    public Account() {
    }

    public Account(Long id) {
        if (id == null) {
            throw new IllegalArgumentException("id must not be null");
        }
        this.id = id;
    }

    protected Long getHibernateId() {
        return hibernateId;
    }

    protected void setHibernateId(Long hibernateId) {
        this.hibernateId = hibernateId;
    }

    protected int getVersion() {
        return this.version;
    }

    protected void setVersion(int version) {
        this.version = version;
    }

    public Long getId() {
        return this.id;
    }

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

    public boolean isActive() {
        return this.active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }

    public boolean isHasBeenActivated() {
        return this.hasBeenActivated;
    }

    public void setHasBeenActivated(boolean hasBeenActivated) {
        this.hasBeenActivated = hasBeenActivated;
    }

    public Date getCreatedDate() {
        return this.createdDate;
    }

    public void setCreatedDate(Date createdDate) {
        this.createdDate = createdDate;
    }

    public Date getExpiryDate() {
        return this.expiryDate;
    }

    public void setExpiryDate(Date expiryDate) {
        this.expiryDate = expiryDate;
    }

    public String getTitle() {
        return this.title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getForename() {
        return this.forename;
    }

    public void setForename(String forename) {
        this.forename = forename;
    }

    public String getSurname() {
        return this.surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public String getEmailAddress() {
        return this.emailAddress;
    }

    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
    }

    public String getPassword() {
        return this.password;
    }

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

    public int getQuota() {
        return this.quota;
    }

    public void setQuota(int quota) {
        this.quota = quota;
    }

    public Address getAddress() {
        return this.address;
    }

    public void setAddress(com.easylists.Address address) {
        this.address = address;
    }   

    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Account)) return false;

        final Account account = (Account) o;

        if (!emailAddress.equals(account.emailAddress)) return false;
        if (!id.equals(account.id)) return false;

        return true;
    }

    public int hashCode() {
        int result;
        result = id.hashCode();
        result = 29 * result + emailAddress.hashCode();
        return result;
    }

}



Util Class
Code:
public class HibernateUtil {
    private static final Logger LOGGER = Logger.getLogger(HibernateUtil.class);
    private static SessionFactory factory = null;

    public static SessionFactory getSessionFactory() throws HibernateException {
        if (factory == null) {
            Configuration config = new Configuration();
            config.addClass(Account.class);
            config.addClass(Address.class);
            factory = config.buildSessionFactory();
        }
        return factory;
    }

    public static Session openSession() throws HibernateException {
        return getSessionFactory().openSession();
    }

    public static void closeSession(Session session) {
        if (session != null) {
            try {
                session.close();
            }
            catch (HibernateException e) {
                // user can't do anything here, so no point throwing exception up
                LOGGER.error("Unable to close Hibernate Session", e);
            }
        }
    }

    public static void saveObject(Object ob) throws PersistenceException {
        try {
            Session session = null;
            Transaction tx = null;
            try {
                session = HibernateUtil.openSession();
                tx = session.beginTransaction();
                session.saveOrUpdate(ob);
                tx.commit();
            }
            catch (StaleObjectStateException e) {
                if (tx != null) {
                    tx.rollback();
                }
                throw new StalePersistentObjectException(e);
            }
            catch (HibernateException e) {
                if (tx != null) {
                    tx.rollback();
                }
                throw new PersistenceException(e);
            }
            finally {
                closeSession(session);
            }
        }
        catch (HibernateException e) {
            throw new PersistenceException(e);
        }
    }

    public static void deleteObject(Object ob) throws PersistenceException {
        try {
            Session session = null;
            Transaction tx = null;
            try {
                session = HibernateUtil.openSession();
                tx = session.beginTransaction();
                session.delete(ob);
                tx.commit();
            }
            catch (HibernateException e) {
                if (tx != null) {
                    tx.rollback();
                }
                throw new PersistenceException(e);
            }
            finally {
                closeSession(session);
            }
        }
        catch (HibernateException e) {
            throw new PersistenceException(e);
        }
    }


    public static Object findById(Long id, Class type) throws PersistenceException {
        LOGGER.debug("HibernateUtil.findById");
        LOGGER.debug("id = " + id);
        LOGGER.debug("type = " + type);
        Session session = null;
        try {
            session = HibernateUtil.openSession();
            Criteria criteria = session.createCriteria(type);
            criteria.add(Expression.eq("id", id));
            return criteria.uniqueResult();
        } catch (HibernateException e) {
            throw new PersistenceException(e);
        } finally {
            HibernateUtil.closeSession(session);
        }
    }
}


ACCOUNT_MANAGER.getAccountForEmailAddress(String emailAddress); method
Code:
public Account getAccountForEmailAddress(String emailAddress) throws PersistenceException {
        Session session = null;
        try {
            session = HibernateUtil.openSession();
            Criteria criteria = session.createCriteria(Account.class);
            criteria.add(Expression.eq("emailAddress", emailAddress));
            return (Account) criteria.uniqueResult();
        }
        catch (HibernateException e) {
            throw new PersistenceException(e);
        }
        finally {
            HibernateUtil.closeSession(session);
        }
    }



Name and version of the database you are using:MySQL 4


Top
 Profile  
 
 Post subject:
PostPosted: Wed Sep 08, 2004 7:49 am 
Hibernate Team
Hibernate Team

Joined: Tue Aug 26, 2003 12:50 pm
Posts: 5130
Location: Melbourne, Australia
Show the SQL for the query that fails.


Top
 Profile  
 
 Post subject: Is this a bug?
PostPosted: Wed Sep 08, 2004 2:42 pm 
Regular
Regular

Joined: Fri Jul 16, 2004 3:04 pm
Posts: 52
Location: Wiltshire UK
Hi Gavin, it looks like Hibernate is translating my id field into it's id field. I have named the id field which Hibernate uses hibernateId in my mapping document, & am using id for my own primary key field. But the Criteria seems to be translating the id parameter into the hibernateId property. I will change my field names to pk in my classes for now to get around this, but am interested, is id a reserved value for naming fields in Hibernate or is this a bug? SQL follows.

Thanks
Paul

Hibernate: select this.HIBERNATE_ID as HIBERNAT1_1_, this.VERSION as VERSION1_, this.ID as ID1_, this.ACTIVE as ACTIVE1_, this.HAS_BEEN_ACTIVATED as HAS_BEEN5_1_, this.CREATED_DATE as CREATED_6_1_, this.EXPIRY_DATE as EXPIRY_D7_1_, this.TITLE as TITLE1_, this.FORENAME as FORENAME1_, this.SURNAME as SURNAME1_, this.EMAIL_ADDRESS as EMAIL_A11_1_, this.PASSWORD as PASSWORD1_, this.QUOTA as QUOTA1_, address1_.HIBERNATE_ID as HIBERNAT1_0_, address1_.VERSION as VERSION0_, address1_.ID as ID0_, address1_.HOUSE_NUMBER as HOUSE_NU4_0_, address1_.HOUSE_NAME as HOUSE_NAME0_, address1_.STREET as STREET0_, address1_.TOWN_OR_CITY as TOWN_OR_7_0_, address1_.COUNTY_OR_STATE as COUNTY_O8_0_, address1_.POSTCODE as POSTCODE0_, address1_.COUNTRY as COUNTRY0_ from ACCOUNT this left outer join ADDRESS address1_ on this.HIBERNATE_ID=address1_.HIBERNATE_ID where this.HIBERNATE_ID=?


Top
 Profile  
 
 Post subject:
PostPosted: Wed Sep 08, 2004 8:20 pm 
Hibernate Team
Hibernate Team

Joined: Tue Aug 26, 2003 12:50 pm
Posts: 5130
Location: Melbourne, Australia
This is expected behavior.


Top
 Profile  
 
 Post subject:
PostPosted: Thu Sep 09, 2004 3:46 am 
Regular
Regular

Joined: Fri Jul 16, 2004 3:04 pm
Posts: 52
Location: Wiltshire UK
Hi Gavin, thanks for your reply. It does not seem to mention in the documentation that you should not name any properties 'id', perhaps this could be included when the documentation is updated.

This forum is excellent, Hibernate is excellent, the Hibernate Team are excellent!

Many thanks to you all
Paul :-)


Top
 Profile  
 
 Post subject:
PostPosted: Thu Sep 09, 2004 3:51 am 
Hibernate Team
Hibernate Team

Joined: Mon Aug 25, 2003 9:11 pm
Posts: 4592
Location: Switzerland
http://www.hibernate.org/hib_docs/refer ... yhql-where

_________________
JAVA PERSISTENCE WITH HIBERNATE
http://jpwh.org
Get the book, training, and consulting for your Hibernate team.


Top
 Profile  
 
 Post subject:
PostPosted: Thu Sep 09, 2004 4:29 am 
Hibernate Team
Hibernate Team

Joined: Tue Aug 26, 2003 12:50 pm
Posts: 5130
Location: Melbourne, Australia
Yeah, but he is right, we should say it closer up the front of the docs. We had this question a couple of times recently.


Top
 Profile  
 
 Post subject:
PostPosted: Thu Sep 09, 2004 4:40 am 
Regular
Regular

Joined: Fri Jul 16, 2004 3:04 pm
Posts: 52
Location: Wiltshire UK
Hi Guys, thanks for this. It would be useful if it was mentioned in the documentation for the mapping files http://www.hibernate.org/hib_docs/reference/en/html_single/#mapping-declaration-property, as this is where us newbies start :-)

Am eagerly awaiting Hibernate in Action being published here in the UK on Sept 20th :-)

Paul


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.