-->
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: UserType or CompositeUserType
PostPosted: Sun Jan 18, 2004 9:57 am 
Beginner
Beginner

Joined: Fri Jan 16, 2004 11:05 am
Posts: 33
I have a class which represents a unique key. It holds a long which is the key as well as methods to get or allocate this key. I originally implemented this as a UserType. This worked great, but for some reason one-to-many relationships will not work. No error is thrown, it just returns a collection of size 0. So my question is, should I be using a CompositeUserType? Or should what I have work and I am doing something wrong?

Thanks in advance


Top
 Profile  
 
 Post subject:
PostPosted: Sun Jan 18, 2004 10:10 am 
Beginner
Beginner

Joined: Fri Jan 16, 2004 11:05 am
Posts: 33
I thought maybe I should post my code.


The UserType:
Code:
package com.sp.util;

import com.sp.util.unqekey.SpUnqeKey;

import net.sf.hibernate.HibernateException;
import net.sf.hibernate.UserType;

import java.io.IOException;
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

/**
* SpUnqeKeyType
*
* This class represents a SpUnqeKey database type transmute.
*/
public class SpUnqeKeyType implements Serializable, UserType
{
    //~ Static fields/initializers *********************************************
    private static final int[]          types = new int[] { Types.NUMERIC };

    //~ Methods ****************************************************************

    /**
     * isMutable
     *
     * Checks to see if this field is mutable.
     *
     * @return boolean indicating if the field is mutable.
     */
    public boolean isMutable(
    )
    {

        return false;
    }

    /**
     * deepCopy
     *
     * Creates a deep copy of the object.
     *
     * @param obj   The object to copy from.
     *
     * @return      A copy of the given object.
     *
     * @throws net.sf.hibernate.HibernateException
     */
    public Object deepCopy(
      Object                            obj
    ) throws HibernateException
    {

        SpUnqeKey                       newKey;
        SpUnqeKey                       oldKey;

        oldKey     = ( SpUnqeKey )obj;

        newKey = new SpUnqeKey( oldKey );

        return newKey;
    }

    /**
     * equals
     *
     * Default equals over ride.
     *
     * @param key0  The first key to compare.
     * @param key1  The second key to compare.
     *
     * @return      boolean indicating the equality of the given keys.
     *
     * @throws net.sf.hibernate.HibernateException
     */
    public boolean equals(
      Object                            key0
    , Object                            key1
    ) throws HibernateException
    {
        return ( ( SpUnqeKey )key0 ).equals( ( SpUnqeKey )key1 );
    }

    /**
     * nullSafeGet
     *
     * Retrieves the object while doing checks for null values.
     *
     * @param rs        The result set holding the applicable row.
     * @param name      An array of names to retrieve.
     * @param owner     Not used.
     *
     * @return          The new key retrieved from the database.
     *
     * @throws net.sf.hibernate.HibernateException
     * @throws java.sql.SQLException
     */
    public Object nullSafeGet(
      ResultSet                         rs
    , String[]                          name
    , Object                            owner
    ) throws HibernateException, SQLException
    {

        SpUnqeKey                       newKey;
        BigDecimal                      keyValue;;
       
        newKey = new SpUnqeKey();
        keyValue = rs.getBigDecimal( name[0] );
       
        if( keyValue == null )
        {
            return null;
        }
       
        newKey.setKey( keyValue.longValue() );

        return newKey;
    }

    /**
     * nullSafeSet
     *
     * Sets the database raw value.
     *
     * @param st        The PreparedStatement to use for the set.
     * @param value     The SpUnqeKey to set from.
     * @param index     The index of the column.
     *
     * @throws net.sf.hibernate.HibernateException
     * @throws java.sql.SQLException
     */
    public void nullSafeSet(
      PreparedStatement                 st
    , Object                            value
    , int                               index
    ) throws HibernateException, SQLException
    {

        if( value != null )
        {
            st.setLong(
                index,
                ( ( SpUnqeKey )value ).getKey()
             );
        }
        else
        {
            st.setNull(
                index,
                Types.NUMERIC
             );
        }
    }

    /**
     * returnedClass
     *
     * The transmute class.
     *
     * @return SpUnqeKey.class
     */
    public Class returnedClass(
    )
    {

        return SpUnqeKey.class;
    }

    /**
     * sqlTypes
     *
     * The raw sql types this transmute works with.
     *
     * @return
     */
    public int[] sqlTypes(
    )
    {
        return types;
    }

    /**
      * writeObject
      *
      * This function does nothing. It is here to satisfy implementation requirements.
      * 
      * @param out  Not used.
      *
      * @throws IOException
      */
    private void writeObject(java.io.ObjectOutputStream out)
        throws IOException
    {
    }
   
    /**
      * readObject
      *
      * This function does nothing. It is here to satisfy implementation requirements.
      * 
      * @param in   Not used.
      *
      * @throws IOException
      * @throws ClassNotFoundException
      */
    private void readObject(java.io.ObjectInputStream in)
        throws IOException, ClassNotFoundException
    {
    }

}



The Unique Key Class:
Code:
package com.sp.util.unqekey;

import java.io.Serializable;
import java.util.logging.Logger;
import java.util.logging.Level;

import com.sp.util.SpException;

/**
* @todo Add exception handling.
* @todo Add properties for configurable data
* SpUnqeKey
*
* A unique key object.
*/
public class SpUnqeKey implements Serializable
{
    //~ Static fields **********************************************************
    public static long                  MAX_VALUE;
    public static long                  MIN_VALUE;
    private static SpUnqeKeyGrp         keyGrp;
    private static final Logger         _logger     = Logger.getLogger( "SP.UTIL.SpUnqeKey" );
   
    //~ Static initialization **************************************************
    static
    {
        MAX_VALUE   = Long.MAX_VALUE;
        MIN_VALUE   = Long.MIN_VALUE;
        keyGrp      = new SpUnqeKeyGrp( "SpUnqeKeyGrp" );
    }

   
    //~ Instance fields ********************************************************
    protected long                      key;
    protected boolean                   valid;

    //~ Constructors ***********************************************************
    /**
      * SpUnqeKey
      *
      * Contstructs a SpUnqeKey object.
      * 
      *
      */
    public SpUnqeKey()
    {
        this.valid      = false;
        this.key        = 0;
    }

    /**
      * SpUnqeKey
      *
      * Contstructs a SpUnqeKey object.
      * 
      * @param keyGroup The key group to this key belongs to.
      */
    public SpUnqeKey(
      SpUnqeKeyGrp                      keyGroup
    )
    {
        SpUnqeKey.keyGrp   = keyGroup;
        this.valid      = false;
        this.key        = 0;
    }

    /**
      * SpUnqeKey
      *
      * Contstructs a SpUnqeKey object.
      * 
      * @param keyGroup The key group to this key belongs to.
      * @param key      The key to initialize.
      */
    public SpUnqeKey(
      SpUnqeKeyGrp                      keyGroup
    , String                            key
    )
    {
        SpUnqeKey.keyGrp    = keyGroup;
        this.valid          = true;
        this.key            = 0;
        setKey( key );
    }

    /**
      * SpUnqeKey
      *
      * Contstructs a SpUnqeKey object.
      * 
      * @param keyGroup The key group to this key belongs to.
      * @param key      The key to initialize.
      */
    public SpUnqeKey(
      SpUnqeKeyGrp                      keyGroup
    , long                              key
    )
    {
        SpUnqeKey.keyGrp    = keyGroup;
        this.valid          = true;
        this.key            = 0;
        setKey( key );
    }

    /**
      * SpUnqeKey
      *
      * Contstructs a SpUnqeKey object.
      * 
      * @param key      The key to initialize.
      */
    public SpUnqeKey(
      SpUnqeKey                         key
    )
    {
        SpUnqeKey.keyGrp    = key.getKeyGroup();
        this.valid          = key.isValid();
        this.key            = key.getKey();
    }

    /**
      * SpUnqeKey
      *
      * Contstructs a SpUnqeKey object.
      * 
      * @param key      The key to initialize.
      */
    public SpUnqeKey(
      long                              key
    )
    {
        this.valid          = true;
        this.key            = key;
    }

    /**
      * allocate
      *
      * Sets the raw key from the underlying allocator.
      * 
      * @return boolean indication success of allocation.
      */
    public boolean allocate(
    )throws SpException
    {
        long                            key;

        //
        // Invalidate the object.
        //
        invalidate();

        //
        // Allocate a key from the key group.  Any errors reported by
        // the key group are collected by this object.
        //
        key = getKeyGroup().allocateKey();
       
        if( key == -1 )
        {
            //mError = GetKeyGroup()->GetError();
            return false;
        }
       
        //
        // Update the object with the key value.
        //
        this.valid = true;
        setKey( key );
       
        if( _logger.isLoggable( Level.FINEST ) )
        {
            _logger.log(Level.FINEST, "Key allocated from key group " + getKeyGroup().getName() );
        }

        //
        // Return "success" to caller.
        //
        return true;
    }

    /**
      * getKey
      *
      * Gets the raw key value.
      * 
      * @return The raw key.
      */
    public long getKey(
    )
    {

        return this.key;
    }

    /**
      * getKeyGroup
      *
      * Gets the key group this key belongs to.
      * 
      * @return The key group.
      */
    public SpUnqeKeyGrp getKeyGroup()
    {
        return SpUnqeKey.keyGrp;
    }

    /**
      * invalidate
      *
      * Invalidates this key.
      * 
      *
      */
    public void invalidate()
    {
        this.valid  = false;
        this.key    = 0;
    }

    /**
      * isValid
      *
      * @return Boolean indicating if the key is valid.
      */
    public boolean isValid()
    {
        return this.valid;
    }

    /**
      * setKey
      *
      * Sets the raw key.
      * 
      * @param key The raw key to set.
      */
    public void setKey(
      long                              key
    )
    {
        this.key = key;
    }

    /**
      * setKey
      *
      * Sets the raw key.
      * 
      * @param key The raw key to set.
      *
      * @return boolean indicating success of operation.
      */
    public boolean setKey(
      String                              key
    )
    {
        //
        // Invalidate the object so that it starts off as invalid.
        //
        invalidate();

        //
        // If the string contains <INVALID>, just leave it as invalid.
        //
        if( key.equals( "<INVALID>" ) )
        {
            return true;
        }

        try
        {
            //
            // Convert the string into internal form. 
            // If the conversion fails, fail the set.
            //
            this.key = Long.valueOf( key ).longValue();
        }
        catch( NumberFormatException nfe )
        {
            StringBuffer                sbErr;
            NumberFormatException       newExcep;
           
            sbErr = new StringBuffer();
            sbErr.append( "Unable to set key using string '" );
            sbErr.append( key );
            sbErr.append( "', conversion error " );
            sbErr.append( nfe.getLocalizedMessage() );
           
            newExcep = new NumberFormatException( sbErr.toString() );
           
            _logger.log( Level.SEVERE, "Set key from String failed.", newExcep );
            throw newExcep;
        }
       
       
        if ( _logger.isLoggable( Level.FINEST ) )
        {
            _logger.log( Level.FINEST, "Key has been set from string '" + key + "'" );
        }
        this.valid = true;
        return true;
    }

    /**
      * setKeyGroup
      *
      * Sets the key group to associate with this key.
      * 
      * @param keyGroup The key group to set.
      */
    public void setKeyGroup(
    SpUnqeKeyGrp                     keyGroup
    )
    {
        invalidate();
        SpUnqeKey.keyGrp = keyGroup;
    }
   
    /**
      * setToMax
      *
      * Sets the maximum value this key can hold.
      */
    public void setToMax()
    {
        valid   = true;
        key     = SpUnqeKey.MAX_VALUE;

        if (_logger.isLoggable(Level.FINEST))
        {
            _logger.log( Level.FINEST, "Key has been set to maximum value" );
        }
    }

    /**
      * setToMin
      *
      * Sets the minimum value this key can hold.
      */
    public void setToMin()
    {
        valid   = true;
        key     = SpUnqeKey.MIN_VALUE;

        if (_logger.isLoggable(Level.FINEST))
        {
            _logger.log( Level.FINEST, "Key has been set to minimum value" );
        }
    }

    /**
      * toString
      *
      * Creates a string representation of this key.
      * 
      * @return The string holding the values of this key.
      */
    public String toString()
    {
        StringBuffer buffer = new StringBuffer();
        buffer.append("[SpUnqeKey:");
        buffer.append(" keyGrp: ");
        buffer.append(keyGrp);
        buffer.append(" key: ");
        buffer.append(key);
        buffer.append(" valid: ");
        buffer.append(valid);
        buffer.append("]");
        return buffer.toString();
    }
   
    /**
      * getAllocatedKey
      *
      * A lazy initializer for creating a pre-allocated key.
      * 
      * @return An allocated valid key.
      */
    public static SpUnqeKey getAllocatedKey(
    )throws SpException
    {
        SpUnqeKey                       newKey;
       
        newKey = new SpUnqeKey();
        newKey.allocate();
       
        return newKey;
    }
}


Top
 Profile  
 
 Post subject:
PostPosted: Sun Jan 18, 2004 10:55 am 
Beginner
Beginner

Joined: Fri Jan 16, 2004 11:05 am
Posts: 33
I have switched this column to map to a BigInteger and everything works fine. The call to get a collection returns the expected size.


Any help would be greatly appreciated.


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.