Results 1 to 3 of 3

Thread: Mapping a null property to a primitive

  1. #1

    Default Mapping a null property to a primitive

    Hi all,

    I have been looking for a while to find a possible solution to the problem of retrieving an int (a primitive type) from a database table. The database table contains some nulls and that's where I got "IllegalArgumentException"

    This is the mapping of the property posX (in the table this is a FLOAT) which I plan to map to a fload primitive type

    the mapping for the class contains:
    <property name="posX" column="posX" />

    the java class contains
    private long posX;

    plus the usual getter/setter for this field.

    In the Generic DAO class the following piece of code is giving an error in the "return criteria.list();" line. Guess that the problem is that there an assignment of a null value to a primitive field.

    Is there a way to "shield" the application against this kind of problems ?

    How can I define the posX field / or modify the hibernate mapping file to avoid this problem ?

    public List<T> findByCriterion(final Criterion... criterions) {
    return getHibernateTemplate().executeFind(new HibernateCallback() {
    public Object doInHibernate(Session session) throws HibernateException, SQLException {
    Criteria criteria = session.createCriteria(getPersistentClass());
    criteria.add(Restrictions.disjunction());
    for (Criterion criterion : criterions) {
    criteria.add(criterion);
    }
    return criteria.list();
    }
    });
    }




    Thank you in advance for any solutions.

    Davide

  2. #2
    Join Date
    Apr 2005
    Posts
    11

    Default

    Can't you change the primitive posX to a Integer object. This shouldn't be a problem when you're using java 5 or higher, cause of the autoboxing feature in java 5.

    Anyway what value would you like to give the posX field in the database field contains a NULL value? Can't you just asign 0 (zero) in de database to every NULL value.
    You can possibly also eliminate them using a where clause in your query.

  3. #3

    Default

    Thank you ceasaro, implemented your suggestion.

    Basically I made the error to use a long for float values So now the posX is defined as Float wrapper. Now the getter and setter have been changed as this.

    Code:
     //nullable persistent field
       private Float posX;
     public Float getPosX() {
          if (posX == null) {
             return (float) 0;
          } else {
             return posX;
          }
       }
    
       public void setPosX(Float posX) {
          this.posX = posX;
       }
    Now I am able to get the zero back from the NULL values.

    Thank you again.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •