-->
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.  [ 10 posts ] 
Author Message
 Post subject: Java 1.5, Enum type
PostPosted: Sun Jan 30, 2005 2:15 pm 
Beginner
Beginner

Joined: Wed Jan 26, 2005 5:34 am
Posts: 41
Location: France, Paris
Hibernate version: 3.0beta3

Hi,

is there somewhere an example to map my an Enum type (java 1.5) with hibernate 3.0 ? (Maybe is it not yet implemented ?) I'd like store the string in the database and do not map the string against an integer like specifiy in the documentation about net.sf.hibernate.PersistentEnum.

My Enum is:
Code:
    /**
     * Enumeration of the supported network types.
     */
    public enum NetworkType {
        /**
         * Constant for Internet.
         */
        IN,
        /**
         * Constant for unknown network type.
         */
        UNKNOWN;

        /**
         * Parses the string argument as an <code>NetworkType</code>. Does not
         * throw exception as <code>valueOf</code> method. If no constant name
         * match the string, returns <code>UNKNOWN</code>.
         *
         * @param s a string containing the <code>NetworkType</code>
         *          representation
         * @return the network type with the specified name,
         *         UNKNOWN if the specified name does not match any
         *         enum constant
         */
        public static NetworkType parseNetworkType(String s) {
            NetworkType nt = UNKNOWN;
            if ("IN".equals(s)) {
                nt = IN;
            }
            return nt;
        }
    }


Best regards

_________________
Vincent


Top
 Profile  
 
 Post subject:
PostPosted: Mon Jan 31, 2005 6:09 pm 
Hibernate Team
Hibernate Team

Joined: Sun Sep 14, 2003 3:54 am
Posts: 7256
Location: Paris, France
It is not yet implemented, you can still implement you own user type

_________________
Emmanuel


Top
 Profile  
 
 Post subject:
PostPosted: Tue Feb 01, 2005 5:45 pm 
Beginner
Beginner

Joined: Wed Jan 26, 2005 5:34 am
Posts: 41
Location: France, Paris
Quote:
It is not yet implemented, you can still implement you own user type

I tried, but according to the documentation about UserType interface, i must create a public default constructor... javac doesn't want to compile with a public default contructor on enum :-/

_________________
Vincent


Top
 Profile  
 
 Post subject:
PostPosted: Tue Feb 01, 2005 5:57 pm 
Beginner
Beginner

Joined: Wed Jan 26, 2005 5:34 am
Posts: 41
Location: France, Paris
Oops, i've misunderstood the hibernate documentation; i've to separate my Enum and my EnumType (which implements UserType). That's it (or i'm too tired ? ;-) )

I'll try tomorrow.

_________________
Vincent


Top
 Profile  
 
 Post subject: Small answer
PostPosted: Thu Feb 03, 2005 11:00 am 
Beginner
Beginner

Joined: Wed Jan 26, 2005 5:34 am
Posts: 41
Location: France, Paris
Maybe someone will be interested by my small code to persist an Enum.

My Enum that i want to persist is ConnectionData.NetworkType.

Code:
public class NetworkTypeUserType extends EnumUserType {
    public NetworkTypeUserType() {
        super(ConnectionData.NetworkType.class.getName());
    }
}


Code:
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;

public class EnumUserType implements UserType {
    private Class clazz = null;
    /**
     * Sole constructor
     */
    protected EnumUserType(String s) {
        try {
            this.clazz = Class.forName(s);
        } catch (java.lang.ClassNotFoundException e) {
            // Nothing
        }
    }

    private static final int[] SQL_TYPES = {Types.VARCHAR};
    public int[] sqlTypes() {
        return SQL_TYPES;
    }

    public Class returnedClass() {
        return clazz;
    }

    public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner) throws HibernateException, SQLException {
        String name = resultSet.getString(names[0]);
        Object result = null;
        if (!resultSet.wasNull()) {
            result = Enum.valueOf(clazz, name);
        }
        return result;
    }

   public void nullSafeSet(PreparedStatement preparedStatement, Object value, int index) throws HibernateException, SQLException {
        if (null == value) {
            preparedStatement.setNull(index, Types.VARCHAR);
        } else {
            preparedStatement.setString(index, value.toString());
        }
    }

    public Object deepCopy(Object value) throws HibernateException{
        return value;
    }

    public boolean isMutable() {
        return false;
    }

    public Object assemble(Serializable cached, Object owner) throws HibernateException {
        return cached;
    }

    public Serializable disassemble(Object value) throws HibernateException {
        return (Serializable)value;
    }

    public Object replace(Object original, Object target, Object owner) throws HibernateException {
        return original;
    }
    public int hashCode(Object x) throws HibernateException {
        return x.hashCode();
    }
    public boolean equals(Object x, Object y) throws HibernateException {
        if (x == y)
            return true;
        if (null == x || null == y)
            return false;
        return x.equals(y);
    }
}

_________________
Vincent


Top
 Profile  
 
 Post subject:
PostPosted: Thu Mar 10, 2005 8:22 am 
Beginner
Beginner

Joined: Thu Aug 26, 2004 5:53 am
Posts: 37
hibernate 3 also supports parameterized user types.

This should allow you to not have to define a concrete subclass of EnumUserType for every enum that you require.

See the docs 5.2.3. Custom value types

An example :

Code:
<typedef class="com.mycompany.usertypes.EnumUserType" name="NetworkType">
    <param name="enumClassName">com.mycompany.domain.ConnectionData.NetworkType</param>
</typedef>

<property name="type" type="NetworkType"/>


It would require re-writing your EnumUserType to use a setter instead of a constructor arg.


Top
 Profile  
 
 Post subject:
PostPosted: Thu Mar 10, 2005 8:30 am 
Beginner
Beginner

Joined: Thu Aug 26, 2004 5:53 am
Posts: 37
Here is your code modified that should do this :

Code:
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Properties;

import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.usertype.ParameterizedType;
import org.hibernate.usertype.UserType;

public class EnumUserType implements UserType, ParameterizedType {
   
   private Class clazz = null;
   
   public void setParameterValues(Properties params) {
      String enumClassName = params.getProperty("enumClassName");
      if (enumClassName == null) {
         throw new MappingException("enumClassName parameter not specified");
      }
      
      try {
            this.clazz = Class.forName(enumClassName);
        } catch (java.lang.ClassNotFoundException e) {
         throw new MappingException("enumClass " + enumClassName + " not found", e);
        }
   }
   
    private static final int[] SQL_TYPES = {Types.VARCHAR};
    public int[] sqlTypes() {
        return SQL_TYPES;
    }

    public Class returnedClass() {
        return clazz;
    }

    public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner) throws HibernateException, SQLException {
        String name = resultSet.getString(names[0]);
        Object result = null;
        if (!resultSet.wasNull()) {
            result = Enum.valueOf(clazz, name);
        }
        return result;
    }

   public void nullSafeSet(PreparedStatement preparedStatement, Object value, int index) throws HibernateException, SQLException {
        if (null == value) {
            preparedStatement.setNull(index, Types.VARCHAR);
        } else {
            preparedStatement.setString(index, value.toString());
        }
    }

    public Object deepCopy(Object value) throws HibernateException{
        return value;
    }

    public boolean isMutable() {
        return false;
    }

    public Object assemble(Serializable cached, Object owner) throws HibernateException {
        return cached;
    }

    public Serializable disassemble(Object value) throws HibernateException {
        return (Serializable)value;
    }

    public Object replace(Object original, Object target, Object owner) throws HibernateException {
        return original;
    }
    public int hashCode(Object x) throws HibernateException {
        return x.hashCode();
    }
    public boolean equals(Object x, Object y) throws HibernateException {
        if (x == y)
            return true;
        if (null == x || null == y)
            return false;
        return x.equals(y);
    }
}
[/code]


Top
 Profile  
 
 Post subject:
PostPosted: Thu Mar 10, 2005 8:38 am 
Hibernate Team
Hibernate Team

Joined: Tue Sep 09, 2003 2:10 pm
Posts: 3246
Location: Passau, Germany
It would be great if you could add this to the wiki, those things get lost quickly on the forum.


Top
 Profile  
 
 Post subject:
PostPosted: Thu Mar 10, 2005 11:00 am 
Beginner
Beginner

Joined: Thu Aug 26, 2004 5:53 am
Posts: 37
http://www.hibernate.org/272.html


Top
 Profile  
 
 Post subject:
PostPosted: Thu Mar 10, 2005 1:58 pm 
Hibernate Team
Hibernate Team

Joined: Tue Aug 26, 2003 12:50 pm
Posts: 5130
Location: Melbourne, Australia
Here is my version of this, note it can be used as an identifier or discriminator type:

Code:
package org.hibernate.demo;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Properties;

import org.hibernate.HibernateException;
import org.hibernate.usertype.EnhancedUserType;
import org.hibernate.usertype.ParameterizedType;

/**
* @author Gavin King
*/
public class EnumUserType implements EnhancedUserType, ParameterizedType {
   
   private Class<Enum> enumClass;

   public void setParameterValues(Properties parameters) {
      String enumClassName = parameters.getProperty("enum");
      try {
         enumClass = (Class<Enum>) Class.forName(enumClassName);
      }
      catch (ClassNotFoundException cnfe) {
         throw new HibernateException("Enum class not found", cnfe);
      }
   }

   public Object assemble(Serializable cached, Object owner)
   throws HibernateException {
      return cached;
   }

   public Object deepCopy(Object value) throws HibernateException {
      return value;
   }

   public Serializable disassemble(Object value) throws HibernateException {
      return (Enum) value;
   }

   public boolean equals(Object x, Object y) throws HibernateException {
      return x==y;
   }

   public int hashCode(Object x) throws HibernateException {
      return x.hashCode();
   }

   public boolean isMutable() {
      return false;
   }

   public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
   throws HibernateException, SQLException {
      String name = rs.getString( names[0] );
      return rs.wasNull() ? null : Enum.valueOf(enumClass, name);
   }

   public void nullSafeSet(PreparedStatement st, Object value, int index)
   throws HibernateException, SQLException {
      if (value==null) {
         st.setNull(index, Types.VARCHAR);
      }
      else {
         st.setString( index, ( (Enum) value ).name() );
      }
   }

   public Object replace(Object original, Object target, Object owner)
   throws HibernateException {
      return original;
   }

   public Class returnedClass() {
      return enumClass;
   }

   public int[] sqlTypes() {
      return new int[] { Types.VARCHAR };
   }

   public Object fromXMLString(String xmlValue) {
      return Enum.valueOf(enumClass, xmlValue);
   }

   public String objectToSQLString(Object value) {
      return '\'' + ( (Enum) value ).name() + '\'';
   }

   public String toXMLString(Object value) {
      return ( (Enum) value ).name();
   }

}


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 10 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.