如何通过Hibernate在DB中保存byte []

时间:2015-04-30 13:25:43

标签: java oracle hibernate

错误:ORA-01461:只能插入一个LONG值才能插入LONG列

- >弹簧工具套件

- > oracle数据库11g快递版

- > ojdbc6

- >休眠工具

- > hibernate-release-4.3.9.Final,文件夹中的所有内容“必需”

antlr-2.7.7
dom4j-1.6.1
hibernate-commons-annotations-4.0.5.Final
hibernate-core-4.3.9.Final
hibernate-jpa-2.1-api-1.0.0.Final
jandex-1.1.0.Final
javassist-3.18.1-GA
jboss-logging-3.1.3.GA
jboss-logging-annotations-1.2.0.Beta1
jboss-transaction-api_1.2_spec-1.0.0.Final

实体:

package firstPack.secondPack.testPack;

public class SaveMe {
    int id;
    byte[] bytedImg;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public byte[] getBytedImg() {
        return bytedImg;
    }
    public void setBytedImg(byte[] bytedImg) {
        this.bytedImg = bytedImg;
    }
}

SaveMe.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Apr 30, 2015 10:26:33 AM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="firstPack.secondPack.testPack.SaveMe" table="ASAVEME">
        <id name="id" type="int">
            <column name="ID" />
            <generator class="assigned" />
        </id>
        <property name="bytedImg" type="binary" length="20000000">
            <column name="BYTEDIMG"></column>
        </property>
    </class>
</hibernate-mapping>

的hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
        <property name="hibernate.connection.username">SYSTEM</property>
        <property name="hibernate.default_schema">SYSTEM</property>
        <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="hibernate.current_session_context_class">thread</property>
        <property name="hibernate.show_sql">true</property>

        <mapping resource="firstPack/secondPack/testPack/SaveMe.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

服务器端

    package firstPack.secondPack.testPack;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;


public class HibClass {
    static final SessionFactory sessionFactory;
    private static StandardServiceRegistry serviceRegistry;
    private static Configuration configuration;
    static{
        try {
            configuration=new Configuration().configure();
            serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
                    configuration.getProperties()).build();
            sessionFactory= configuration.buildSessionFactory(serviceRegistry);

        } catch (Throwable e) {
            e.printStackTrace();
            System .err.println("Initial SessionFactory creation failed." + e);
            throw new ExceptionInInitializerError(e);
        }
    }
    public void saveIt(SaveMe saveMe) {
        System.out.println("Array length = "+saveMe.getBytedImg().length);
        try {
            Session sessin = sessionFactory.getCurrentSession();
            sessin.beginTransaction();
            sessin.save(saveMe);
            sessin.getTransaction().commit();
            System.out.println("It Have Been Commited");
        } catch (Throwable e) {
            System.out.println(e.getMessage());
            System.out.println("Failed at the DataBase");
            e.printStackTrace();
        }

    }
}

测试它我编写了Applet,并在本地运行它,因此它可以访问服务器端

package firstPack.secondPack.testPack;

public class MyApplet extends JApplet{
    @Override
    public void init() {
        super.init();
        populateGui();
    }
    JPanel mainPanel;
    JPanel imgPanel;
    JPanel buttonPanel;
    JButton button;
    Image img;
    byte[] bytedImg;
    int id=1;
    SaveMe saveMe;
    HibClass hibClass;
    private void populateGui() {
        hibClass=new HibClass();
        fetchImg();
        imgPanel=new JPanel(){
            @Override
            public void paint(Graphics g) {
                super.paint(g);
                g.drawImage(img, 0, 0, null);
            }
        };
        imgPanel.setPreferredSize(
                new Dimension(img.getWidth(null), img.getHeight(null))
                );
        button=new JButton("Save");
        button.addActionListener(
                new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent arg0) {
                        saveMe=new SaveMe();
                        saveMe.setBytedImg(bytedImg);
                        saveMe.setId(id);
                        hibClass.saveIt(saveMe);
                    }
                }
                );
        buttonPanel=new JPanel();
        buttonPanel.add(button);
        mainPanel=new JPanel();
        mainPanel.add(imgPanel);
        mainPanel.add(button);
        this.setContentPane(mainPanel);

    }
    private void fetchImg() {
        JFileChooser flCh = new JFileChooser("Choose Map Image");
        flCh.addChoosableFileFilter(new FileNameExtensionFilter(
                "only image file", "jpeg", "jpg", "gif", "png"));
        flCh.setAcceptAllFileFilterUsed(false);

        flCh.setCurrentDirectory(new File(System.getProperty("user.dir")));

        int result = flCh.showOpenDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            try {
                File file=flCh
                        .getSelectedFile();
                img=(Image) ImageIO.read(file);
                bytedImg=new byte[
                                           (int)file.length()
                                           ];
                FileImageInputStream inputStr=
                        new FileImageInputStream(file);
                inputStr.read(bytedImg);
                inputStr.close();
            } catch (IOException e) {
                System.out.println("Error at opening Image File");
                e.printStackTrace();
            }

        } else {
            System.out.println("File has not bean choosen");
        }
    }
}
结果

apr 30, 2015 2:56:15 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
apr 30, 2015 2:56:15 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.9.Final}
apr 30, 2015 2:56:15 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
apr 30, 2015 2:56:15 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
apr 30, 2015 2:56:15 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
apr 30, 2015 2:56:15 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
apr 30, 2015 2:56:15 PM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: firstPack/secondPack/testPack/SaveMe.hbm.xml
apr 30, 2015 2:56:16 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
apr 30, 2015 2:56:16 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
apr 30, 2015 2:56:16 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [oracle.jdbc.driver.OracleDriver] at URL [jdbc:oracle:thin:@localhost:1521:xe]
apr 30, 2015 2:56:16 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=SYSTEM, password=****}
apr 30, 2015 2:56:16 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
apr 30, 2015 2:56:16 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
apr 30, 2015 2:56:16 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
apr 30, 2015 2:56:16 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
apr 30, 2015 2:56:16 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
apr 30, 2015 2:56:17 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
apr 30, 2015 2:56:17 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
apr 30, 2015 2:56:17 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
apr 30, 2015 2:56:17 PM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: ASAVEME
apr 30, 2015 2:56:17 PM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: ASAVEME
apr 30, 2015 2:56:17 PM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: ASAVEME
apr 30, 2015 2:56:17 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Array length = 332200
Hibernate: insert into SYSTEM.ASAVEME (BYTEDIMG, ID) values (?, ?)
apr 30, 2015 2:56:31 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1461, SQLState: 72000
could not execute statement
Failed at the DataBase
apr 30, 2015 2:56:31 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: ORA-01461: can bind a LONG value only for insert into a LONG column

apr 30, 2015 2:56:31 PM org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
org.hibernate.exception.GenericJDBCException: could not execute statement
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:211)
    at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:62)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3124)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3581)
    at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:104)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:465)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:351)
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
    at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1258)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
    at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
    at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
    at firstPack.secondPack.testPack.HibClass.saveIt(HibClass.java:32)
    at firstPack.secondPack.testPack.MyApplet$2.actionPerformed(MyApplet.java:56)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$500(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: java.sql.SQLException: ORA-01461: can bind a LONG value only for insert into a LONG column

    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:447)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)
    at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:951)
    at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:513)
    at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:227)
    at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:208)
    at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:1046)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1336)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3613)
    at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3694)
    at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1354)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
    ... 49 more

在Data Source Explorer中,创建的表有

BYTEDIMG[RAW(255)Nullable]
ID[NUMBER(10,0)PK]

所以...

长度

<property name="bytedImg" type="binary" length="20000000">
        <column name="BYTEDIMG"></column>
</property>

大约是20M,

Array length = 332200

为什么有

ERROR: ORA-01461: can bind a LONG value only for insert into a LONG column

为什么行“BYTEDIMG”的类型为“RAW(255)”,而不是“BLOB”

1 个答案:

答案 0 :(得分:0)

自问题

ERROR: ORA-01461: can bind a LONG value only for insert into a LONG column

起因于有人试图保存超过默认值的对象&#34; CHUNK&#34;尺寸,我不确定它是多少(4000或4500)

解决方案是增加默认的CHUNK大小,但不应该在&#34; property&#34;但在&#34;列&#34; TAG

<property name="bytedImg" type="binary" length="20000000">
        <column name="BYTEDIMG"></column>
</property>

<property name="bytedImg"  type="binary" >
        <column name="BYTEDIMG" length="20000000"></column>
</property>

现在它大约是20M