将图像保存到数据库时,JPA中的类广播异常 [英] classcast exception in JPA while saving images to the database

查看:67
本文介绍了将图像保存到数据库时,JPA中的类广播异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用JPA将图像写入数据库时​​,我遇到了一些问题。我低于classcastexception。我也附上了代码。

I am facing some issues when I write images to the database using JPA. I am getting below classcastexception. I have attached the code as well.

[EL Warning]: 2012-03-12 
12:02:58.757--UnitOfWork(23191477)--java.lang.ClassCastException: 
java.lang.String cannot be cast to java.lang.Number

代码:

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;

@Entity
@Table(name="Horoscope_Details")
public class HoroscopeDetails {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long id;
    public long getId() {
        return id;
    }



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



    public String getStar() {
        return star;
    }



    public void setStar(String star) {
        this.star = star;
    }



    public byte[] getPicture() {
        return picture;
    }



    public void setPicture(byte[] picture) {
        this.picture = picture;
    }



    private String star;

    @Lob @Basic(fetch = FetchType.LAZY)
    @Column(length=1048576) 
    private byte[] picture;





}




package main;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.persistence.EntityManager;

import com.vemanchery.timesheet.emf.EMF;
import com.vemanchery.timesheet.model.HoroscopeDetails;

public class Main2 {

    /**
     * @param args
     */
    public static void main(String[] args) {

        // save image into database
        File file = new File("C:\\images\\1.jpg");
        byte[] bFile = null;;
        try {
            bFile = readImageOldWay(file);
        } catch (IOException e1) {

            e1.printStackTrace();
        }

    /*  try {
            FileInputStream fileInputStream = new FileInputStream(file);
            // convert file into array of bytes
            fileInputStream.read(bFile);
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }*/

        EntityManager entityManager = EMF.getEntityManager();
        entityManager.getTransaction().begin();
        HoroscopeDetails horoscopeDetails = new HoroscopeDetails();
        horoscopeDetails.setPicture(bFile);
        horoscopeDetails.setStar("lll");
        System.out.println("done!!");
        entityManager.persist(horoscopeDetails);
        entityManager.getTransaction().commit();
        entityManager.flush();
        entityManager.close();

    }

    public static byte[] readImageOldWay(File file) throws IOException {
        Logger.getLogger(Main.class.getName()).log(Level.INFO,
                "[Open File] " + file.getAbsolutePath());
        InputStream is = new FileInputStream(file);
        // Get the size of the file
        long length = file.length();
        // You cannot create an array using a long type.
        // It needs to be an int type.
        // Before converting to an int type, check
        // to ensure that file is not larger than Integer.MAX_VALUE.
        if (length > Integer.MAX_VALUE) {
            // File is too large
        }
        // Create the byte array to hold the data
        byte[] bytes = new byte[(int) length];
        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length
                && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }
        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file "
                    + file.getName());
        }
        // Close the input stream and return bytes
        is.close();
        return bytes;
    }

}

我收到以下异常。

[EL Warning]: 2012-03-12 13:41:33.672--UnitOfWork(23667197)--java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Number
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Number
    at org.eclipse.persistence.sequencing.QuerySequence.updateAndSelectSequence(QuerySequence.java:278)
    at org.eclipse.persistence.sequencing.StandardSequence.getGeneratedVector(StandardSequence.java:71)
    at org.eclipse.persistence.sequencing.DefaultSequence.getGeneratedVector(DefaultSequence.java:163)
    at org.eclipse.persistence.sequencing.Sequence.getGeneratedVector(Sequence.java:257)
    at org.eclipse.persistence.internal.sequencing.SequencingManager$Preallocation_Transaction_NoAccessor_State.getNextValue(SequencingManager.java:468)
    at org.eclipse.persistence.internal.sequencing.SequencingManager.getNextValue(SequencingManager.java:1067)
    at org.eclipse.persistence.internal.sequencing.ClientSessionSequencing.getNextValue(ClientSessionSequencing.java:70)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.assignSequenceNumber(ObjectBuilder.java:349)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.assignSequenceNumber(ObjectBuilder.java:308)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.assignSequenceNumber(UnitOfWorkImpl.java:465)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNotRegisteredNewObjectForPersist(UnitOfWorkImpl.java:4231)
    at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.registerNotRegisteredNewObjectForPersist(RepeatableWriteUnitOfWork.java:513)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4176)
    at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:440)
    at main.Main2.main(Main2.java:48)


推荐答案


java.lang.String无法转换为java.lang.Number

java.lang.String cannot be cast to java.lang.Number

您的映射可能是错误的。您在交易中仅设置一个字符串( setStar( lll))。持久层尝试将此字符串转换为数字。也许您的列数据类型是数字格式?

Your mapping could be wrong. You set only one String in your transaction (setStar("lll")). The persistence layer tries to cast this String to a Number. Maybe your column datatype is a number format?

如果不应保留该值,则应明确使用 @Transient

If the value should not be persisted you should explicitely use the @Transient annotation with the field.

更新:如果您想了解JPA生成的SQL,请将以下内容添加到您的 persistence.xml <持久性单元> 元素:

UPDATE: If you want to know the SQL generated by JPA, add the following to your persistence.xml inside the <persistence-unit> element:

<properties>
        property name="eclipselink.logging.level.sql" value="FINE" />
</properties>

这篇关于将图像保存到数据库时,JPA中的类广播异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆