2013-01-08 10 views
14

Hibernate/JPAの配列を扱うためにUserTypeを実装するクラスを記述しようとしています。 私は解決策を構築するのに mapping a postgres array with hibernateHibernate/JPA/HSQL : How to create a Dialect mapping for User Type ARRAYの投稿を使用しましたが、動作させることができません。 私はテストするために新しいSpring Rooプロジェクトを作成しました。ここで(すべてのJavaクラスがパッケージテストに配置されている)別のファイルは、以下のとおりです。HibernateとPostgreSQLにUserTypeを持つ配列 - > MappingException

  • persistence.xmlの

    <?xml version="1.0" encoding="UTF-8" standalone="no"?> 
    <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> 
        <persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL"> 
        <provider>org.hibernate.ejb.HibernatePersistence</provider> 
        <properties> 
        <!-- <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/> --> 
        <property name="hibernate.dialect" value="test.PostgreSQLDialectArray"/> 
        <!-- value="create" to build a new database on each run; value="update" to modify an existing database; value="create-drop" means the same as "create" but also drops tables when Hibernate closes; value="validate" makes no changes to the database --> 
        <property name="hibernate.hbm2ddl.auto" value="create"/> 
        <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy"/> 
        <property name="hibernate.connection.charSet" value="UTF-8"/> 
        <!-- Uncomment the following two properties for JBoss only --> 
        <!-- property name="hibernate.validator.apply_to_ddl" value="false" /--> 
        <!-- property name="hibernate.validator.autoregister_listeners" value="false" /--> 
        </properties> 
        </persistence-unit> 
    </persistence> 
    
  • TestArray.java

    package test; 
    
    import java.math.BigInteger; 
    import java.security.SecureRandom; 
    
    import org.springframework.context.ApplicationContext; 
    import org.springframework.context.support.ClassPathXmlApplicationContext; 
    import org.springframework.roo.addon.javabean.RooJavaBean; 
    import org.springframework.roo.addon.serializable.RooSerializable; 
    import org.springframework.roo.addon.tostring.RooToString; 
    
    @RooJavaBean 
    @RooToString 
    @RooSerializable 
    public class TestArray { 
    
    
        private static final long serialVersionUID = 1L; 
        private SecureRandom random = new SecureRandom(); 
    
    
        public String nextSessionId() 
        { 
         return new BigInteger(130, random).toString(32); 
        } 
    
        public static void main(String[] args) { 
         ApplicationContext context; 
    context = new ClassPathXmlApplicationContext("classpath:META-INF/spring/applicationContext.xml"); 
         int[] array = new int[1428]; 
         TestArray test = new TestArray(); 
         Blabla blabla = new Blabla(); 
         int nb = 1428; 
    
         for(int i = 0 ; i < nb ; i++) 
         array[i] = test.random.nextInt(); 
    
          //   blabla.setTest(array); 
          //   blabla.persist(); 
          //  System.out.println(Arrays.toString(blabla.getTest())); 
    
         System.out.println(java.sql.Types.ARRAY); 
         System.out.println("Done"); 
        } 
    } 
    
  • Blabla.java

    package test; 
    
    import org.hibernate.annotations.Type; 
    import org.springframework.roo.addon.entity.RooEntity; 
    import org.springframework.roo.addon.javabean.RooJavaBean; 
    import org.springframework.roo.addon.tostring.RooToString; 
    
    @RooJavaBean 
    @RooToString 
    @RooEntity 
    public class Blabla { 
    
        @Type(type = "test.IntArrayUserType") 
        private int[] array; 
    } 
    
  • PostgreSQLDialectArray

    package test; 
    
    import java.sql.Types; 
    
    
    public class PostgreSQLDialectArray extends org.hibernate.dialect.PostgreSQLDialect{ 
    
        public PostgreSQLDialectArray() { 
         super(); 
         registerHibernateType(Types.ARRAY, "array"); 
        } 
    } 
    
  • IntArrayUserType.java(mapping a postgres array with hibernateよりも基本的に同じ)

    package test; 
    import java.io.Serializable; 
    import java.sql.Array; 
    import java.sql.Connection; 
    import java.sql.PreparedStatement; 
    import java.sql.ResultSet; 
    import java.sql.SQLException; 
    
    import org.hibernate.HibernateException; 
    import org.hibernate.usertype.UserType; 
    
    
    
    public class IntArrayUserType implements UserType { 
    
        protected static final int SQLTYPE = java.sql.Types.ARRAY; 
    
        private int[] toPrimitive(Integer[] array){ 
         int[] a = new int[array.length]; 
         for(int i = 0 ; i < array.length ; i++) 
          a[i] = array[i]; 
         return a; 
        } 
    
        private Integer[] toObject(int[] array){ 
         Integer[] a = new Integer[array.length]; 
         for(int i = 0 ; i < array.length ; i++) 
          a[i] = array[i]; 
         return a; 
        } 
    
        @Override 
        public Object nullSafeGet(final ResultSet rs, final String[] names, final Object owner) throws HibernateException, SQLException { 
         Array array = rs.getArray(names[0]); 
         Integer[] javaArray = (Integer[]) array.getArray(); 
         return toPrimitive(javaArray); 
        } 
    
        @Override 
        public void nullSafeSet(final PreparedStatement statement, final Object object, final int i) throws HibernateException, SQLException { 
         System.out.println("test null safe set..."); 
         Connection connection = statement.getConnection(); 
    
         int[] castObject = (int[]) object; 
         Integer[] integers = toObject(castObject); 
         Array array = connection.createArrayOf("integer", integers); 
    
         statement.setArray(i, array); 
         System.out.println("test null safe set..."); 
        } 
    
        @Override 
        public Object assemble(final Serializable cached, final Object owner) throws HibernateException { 
         return cached; 
        } 
    
        @Override 
        public Object deepCopy(final Object o) throws HibernateException { 
         return o == null ? null : ((int[]) o).clone(); 
        } 
    
        @Override 
        public Serializable disassemble(final Object o) throws HibernateException { 
         return (Serializable) o; 
        } 
    
        @Override 
        public boolean equals(final Object x, final Object y) throws HibernateException { 
         return x == null ? y == null : x.equals(y); 
        } 
    
        @Override 
        public int hashCode(final Object o) throws HibernateException { 
         return o == null ? 0 : o.hashCode(); 
        } 
    
        @Override 
        public boolean isMutable() { 
         return false; 
        } 
    
        @Override 
        public Object replace(final Object original, final Object target, final Object owner) throws HibernateException { 
         return original; 
        } 
    
        @Override 
        public Class<int[]> returnedClass() { 
         return int[].class; 
        } 
    
        @Override 
        public int[] sqlTypes() { 
         return new int[] { SQLTYPE }; 
        } 
    } 
    

そして今、スタックトレース:

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [META-INF/spring/applicationContext.xml]: Cannot resolve reference to bean 'entityManagerFactory' while setting bean property 'entityManagerFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [META-INF/spring/applicationContext.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: persistenceUnit] Unable to build EntityManagerFactory 
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328) 
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106) 
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1325) 
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086) 
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517) 
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) 
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291) 
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) 
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288) 
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190) 
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580) 
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895) 
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425) 
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139) 
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83) 
at test.TestArray.main(TestArray.java:29) 
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [META-INF/spring/applicationContext.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: persistenceUnit] Unable to build EntityManagerFactory 
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1420) 
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519) 
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) 
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291) 
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) 
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288) 
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190) 
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:322) 
... 15 more 
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: persistenceUnit] Unable to build EntityManagerFactory 
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:915) 
at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:74) 
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:225) 
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:308) 
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477) 
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417) 
... 22 more 
Caused by: org.hibernate.MappingException: No Dialect mapping for JDBC type: 2003 
at org.hibernate.dialect.TypeNames.get(TypeNames.java:77) 
at org.hibernate.dialect.TypeNames.get(TypeNames.java:100) 
at org.hibernate.dialect.Dialect.getTypeName(Dialect.java:296) 
at org.hibernate.mapping.Column.getSqlType(Column.java:208) 
at org.hibernate.mapping.Table.sqlCreateString(Table.java:418) 
at org.hibernate.cfg.Configuration.generateSchemaCreationScript(Configuration.java:1099) 
at org.hibernate.tool.hbm2ddl.SchemaExport.<init>(SchemaExport.java:106) 
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:372) 
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1872) 
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:906) 
... 27 more 

だから私はその方言を推測私が作成したものはまったく使われていない間違っていますが、私は理由を知らない。私は@Typeアノテーションがマッピングを行うべきだと思うが、いくつかのタグを見たことがあるが、この例でそれらが必要かどうかわからない。私はこの問題に悩まされており、私は絶望的になっています。このプログラムのデバッグを手伝ってもらえますか?お願いします。 ありがとうございます。

編集0:

persistence.xmlファイルが正しい方言を見つけるように見えるが、関数getTypeNameメソッド(2003)registerHibernateType(Types.ARRAY、 "アレイ")を行った後、上記のエラーがスローされます。ところで、私はHibernate 3.6.4.Finalとpostgresql 8.4-702.jdbc3を使用しています。

編集1:

私はPostgreSQLDialectArrayコンストラクタに次の行を追加しました:

registerColumnType(Types.ARRAY, "integer[$l]"); 

を部分的に問題を解決するために思われます。しかし、今、私は別のエラーが出る:

どうやら
2013-01-09 11:14:30,281 [main] ERROR org.hibernate.tool.hbm2ddl.SchemaExport - Unsuccessful: create table blabla (id int8 not null, array int[255], name varchar(255), test int4 not null, version int4, primary key (id)) 
2013-01-09 11:14:30,282 [main] ERROR org.hibernate.tool.hbm2ddl.SchemaExport - ERREUR: erreur de syntaxe sur ou près de « array » 
    Position: 40 

、まだそれの配列を持つテーブルを作成する方法を知らないハイバネート...

編集2:

に思えますpostgresqlは私のカラムが "array"と呼ばれているのを気に入らなかった。私はそれを変更し、それは働いた。テーブルは、整数の配列でhibernateによって作成されます。

しかし、UserTypeの実装に問題があるため、hibernateで配列を保存することはできません。どうやら、配列の作成はcreateArrayOfで失敗します。私はこの問題について、ラッパーの代わりに基本的な接続にアクセスするように指示するいくつかのスレッドを読んでいます。この問題はかなり異なるので、私はこのスレッドにリンクする新しいスレッドを開こうと思っています。

スタックトレース:

Exception in thread "main" java.lang.AbstractMethodError: org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.createArrayOf(Ljava/lang/String;[Ljava/lang/Object;)Ljava/sql/Array; 
at test.IntArrayUserType.nullSafeSet(IntArrayUserType.java:59) 
at org.hibernate.type.CustomType.nullSafeSet(CustomType.java:140) 
at org.hibernate.persister.entity.AbstractEntityPersister.dehydrate(AbstractEntityPersister.java:2184) 
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2430) 
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2874) 
at org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:79) 
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273) 
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:265) 
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:184) 
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321) 
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51) 
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216) 
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383) 
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133) 
at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:76) 
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:467) 
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:754) 
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723) 
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:393) 
at org.springframework.transaction.aspectj.AbstractTransactionAspect.ajc$afterReturning$org_springframework_transaction_aspectj_AbstractTransactionAspect$3$2a73e96c(AbstractTransactionAspect.aj:78) 
at test.Blabla_Roo_Entity.ajc$interMethod$test_Blabla_Roo_Entity$test_Blabla$persist(Blabla_Roo_Entity.aj:56) 
at test.Blabla.persist(Blabla.java:1) 
at test.Blabla_Roo_Entity.ajc$interMethodDispatch1$test_Blabla_Roo_Entity$test_Blabla$persist(Blabla_Roo_Entity.aj) 
at test.TestArray.main(TestArray.java:39) 

編集3:

最後に、次のような変形した後、整数配列のためのUserType作品:

  • はApplicationContextのこの行を追加します。 xml:

    <bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="dataSource">
    ....
    <property name="accessToUnderlyingConnectionAllowed" value="true" />
    </bean>

  • IntArrayUserType

    から
    @Override 
        public void nullSafeSet(final PreparedStatement statement, final Object object, final int i) throws HibernateException, SQLException { 
         Connection connection = statement.getConnection(); 
         int[] castObject = (int[]) object; 
         Integer[] integers = toObject(castObject); 
         Connection conn = ((DelegatingConnection) connection).getInnermostDelegate(); 
         Array array = conn.createArrayOf("integer", integers); 
         statement.setArray(i, array); 
        } 
    

をnullSafeSetを変更するが、テーブルのblablaからすべてのエントリを取得するときに問題がまだある。 関数findAllBlablasが正しく動作せず、返ります最初のエントリ...

編集4:

は実際には、それは素晴らしい仕事が、Eclipseのコンソールには、すべてのデータを印刷することができませんでした。それで全部です!

+0

(http://stackoverflow.com/questions/1647583/mapping-a-postgres-array-with-hibernate)HibernateでPostgresのアレイをマッピング]の可能な重複 – borchvm

答えて

1

編集3のソリューションの横に、dbcpやc3p0のような接続プールを使用しないと完璧に動作します。 - dbcpを使用しています。

可能な解決策は、c3p0を使用する場合はproxoolを使用することです。これにより、proxoolはcreateArrayOf()を処理できるため、問題はありません。

もう一つは、このようになります:

C3P0ProxyConnection connection = (C3P0ProxyConnection) _statement.getConnection(); 
    Method method = Connection.class.getMethod("createArrayOf", new Class[] { String.class, Object[].class }); 
    Array array = (Array) connection.rawConnectionOperation(
     method, C3P0ProxyConnection.RAW_CONNECTION, new Object[] {"integer", intArray}); 
    _statement.setArray(_i, array); 

あなたは、JDBCクラスから基本的な機能を取得する必要があります。そのためにgetMethodとそれを取得し、反射でそれを使用してください。

1
__________ HibernateSessionFactory.xml ___________________________ 

    <property name="hibernateProperties"> 
     <props> 
      <!-- <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop> --> 
      <prop key="hibernate.dialect">com.test.model.PostgreSQLDialectArray</prop>    
      <prop key="hibernate.show_sql">true</prop> 
      <prop key="hibernate.format_sql">true</prop> 
      <prop key="hibernate.generate_statistics">false</prop> 
      <prop key="hibernate.connection.pool_size">10</prop> 
      <prop key="hibernate.archive.autodetection">class</prop> 
      <prop key="hibernate.hbm2ddl.auto">create</prop>     
      <prop key="cache.provider_class">org.hibernate.cache.NoCacheProvider</prop> 
     </props> 
    </property> 



    ______________ PostgreSQLDialectArray.java _______________________ 


package com.test.model; 

import java.sql.Types; 

public class PostgreSQLDialectArray extends org.hibernate.dialect.PostgreSQL82Dialect{ 

    public PostgreSQLDialectArray() { 

     super();  

     System.out.println("Register Hibernate Type ... "); 
     registerHibernateType(Types.ARRAY, "array"); 

     System.out.println("Register Column Type ... "); 
     registerColumnType(Types.ARRAY, "integer[]"); 

    } 
} 



_____________ CustomArrayType.java ______________________________ 


package com.test.model; 

import java.io.Serializable; 
import java.sql.Connection; 
import java.sql.PreparedStatement; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.sql.Types; 
import java.sql.Array; 

import org.hibernate.*; 
import org.hibernate.engine.spi.SessionImplementor; 
import org.hibernate.usertype.UserType; 

public class CustomArrayType implements UserType 
{ 

    protected static final int SQLTYPE = java.sql.Types.ARRAY; 

    private int[] toPrimitive(Integer[] array){ 
     int[] a = new int[array.length]; 
     for(int i = 0 ; i < array.length ; i++) 
      a[i] = array[i]; 
     return a; 
    } 

    private Integer[] toObject(int[] array){ 
     Integer[] a = new Integer[array.length]; 
     for(int i = 0 ; i < array.length ; i++) 
      a[i] = array[i]; 
     return a; 
    } 

    @Override 
    public Object nullSafeGet(final ResultSet rs, final String[] names, SessionImplementor session, final Object owner) throws HibernateException, SQLException { 
     Array array = rs.getArray(names[0]); 
     Integer[] javaArray = (Integer[]) array.getArray(); 
     return toPrimitive(javaArray); 
    } 

    @Override 
    public void nullSafeSet(final PreparedStatement statement, final Object object, final int i, SessionImplementor session) throws HibernateException, SQLException { 
     System.out.println("test null safe set..."); 
     Connection connection = statement.getConnection(); 

     int[] castObject = (int[]) object; 
     Integer[] integers = toObject(castObject); 
     Array array = connection.createArrayOf("integer", integers); 

     statement.setArray(i, array); 
     System.out.println("test null safe set..."); 
    } 

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

    @Override 
    public Object deepCopy(final Object o) throws HibernateException { 
     return o == null ? null : ((int[]) o).clone(); 
    } 

    @Override 
    public Serializable disassemble(final Object o) throws HibernateException { 
     return (Serializable) o; 
    } 

    @Override 
    public boolean equals(final Object x, final Object y) throws HibernateException { 
     return x == null ? y == null : x.equals(y); 
    } 

    @Override 
    public int hashCode(final Object o) throws HibernateException { 
     return o == null ? 0 : o.hashCode(); 
    } 

    @Override 
    public boolean isMutable() { 
     return false; 
    } 

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

    @Override 
    public Class<int[]> returnedClass() { 
     return int[].class; 
    } 

    @Override 
    public int[] sqlTypes() { 
     return new int[] { SQLTYPE }; 
    } 

} 



____________ MyClass.java ___________________________ 

package com.test.model; 

import static javax.persistence.GenerationType.IDENTITY; 

import java.io.Serializable; 
import java.sql.Time; 
import java.sql.Timestamp; 
import java.sql.Types; 
import java.util.Date; 
import java.util.List; 
import java.util.Set; 

import javax.persistence.CascadeType; 
import javax.persistence.Column; 
import javax.persistence.Entity; 
import javax.persistence.EnumType; 
import javax.persistence.Enumerated; 
import javax.persistence.FetchType; 
import javax.persistence.GeneratedValue; 
import javax.persistence.Id; 
import javax.persistence.JoinColumn; 
import javax.persistence.JoinTable; 
import javax.persistence.ManyToMany; 
import javax.persistence.ManyToOne; 
import javax.persistence.OneToMany; 
import javax.persistence.Table; 

import org.hibernate.annotations.Type; 

@Entity 
@Table(name = "MyClass") 
public class MyClass implements Serializable { 

    private static final long serialVersionUID = -2520209406925143850L; 

    @Id 
    @GeneratedValue(strategy = IDENTITY) 
    private Long id; 

    @Type(type = "com.test.model.CustomArrayType") 
    @Column(name = "arrayDay", nullable = true) 
    private int[] arrayDay;   

    public Long getId() { 
    return id; 
    } 

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

    public int[] getArrayDay() { 
     return arrayDay; 
    } 

    public void setArrayDay(int[] arrayDay) { 
     this.arrayDay = arrayDay; 
    } 

} 



______________ ArrayTypeTests.java ___________________________ 



package com.test; 

import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.springframework.beans.BeansException; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.context.ApplicationContext; 
import org.springframework.context.ApplicationContextAware; 
import org.springframework.test.context.ContextConfiguration; 
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 

import com.test.model.MyClass; 
import com.test.service.MyClassService; 

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = { "classpath:application-context.xml" }) 
public class ArrayTypeTests implements ApplicationContextAware { 

    @Autowired 
    private MyClassService myClassService; 

    public static ApplicationContext ctx; 

    @Test 
    public void test_() { 
     System.out.println("Test junit"); 
    } 

    @Test 
    public void test_arrayDays() { 

    System.out.println("\n - Start test_array - "); 
    MyClass myClass = myClassService.getMyClassById(1L); 
    if (myClass != null) { 
     int[] array = myClass.getArrayDay(); 
     System.out.println("\n valor1:" + array[0]); 
     System.out.println("\n valor2:" + array[1]); 
     System.out.println("\n\n test_array OK "); 
    } else { 
     System.out.println("\n ERROR"); 
    } 
    System.out.println("\n - End test_array - "); 

    } 

    @Override 
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { 
    ctx = applicationContext; 
    } 

} 
関連する問題