1

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

Code:

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;
    }

}

I am getting the following exception.

[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)
user414967
  • 5,225
  • 10
  • 40
  • 61
  • Could you post the whole stacktrace of the error and not just the message? – Guillaume Polet Mar 12 '12 at 08:09
  • edited my question and added the stacktrace of the error. – user414967 Mar 12 '12 at 08:13
  • It is strange . It seems that eclipse link cannot generate the next value for the id column. What is the database do you use ? How about changing `long` to `Long`? – Ken Chan Mar 12 '12 at 08:36
  • I use mysql. and changed from long to Long. but still got the same issue. – user414967 Mar 12 '12 at 08:51
  • mysql supports automatically generating the value for primary key column. How about changing to use `@GeneratedValue(strategy=GenerationType.IDENTITY )` to force mySQL generate the next value used for the primary key instead of eclipseLink generates it for you? . Make sure the `id` column of the `Horoscope_Details` table uses the `AUTO_INCREMENT` keywords " http://www.w3schools.com/sql/sql_autoincrement.asp – Ken Chan Mar 12 '12 at 08:59
  • Good. Do you just change to use `@GeneratedValue(strategy=GenerationType.IDENTITY )` and the problem solve? If yes , it sounds strange as I suppose `@GeneratedValue(strategy=GenerationType.AUTO)` will automatically change to `@GeneratedValue(strategy=GenerationType.IDENTITY )` for mySQL. – Ken Chan Mar 12 '12 at 09:08
  • Yes. I made change from @GeneratedValue(strategy=GenerationType.AUTO) to @GeneratedValue(strategy=GenerationType.IDENTITY ). Now problem got solved..And one more doubt..How mcuh size of the image we can save to the database? – user414967 Mar 12 '12 at 09:12
  • mySQL documentation said that "The maximum size of a BLOB or TEXT object is determined by its type, but the largest value you actually can transmit between the client and server is determined by the amount of available memory and the size of the communications buffers." , from here: http://dev.mysql.com/doc/refman/5.5/en/blob.html – Ken Chan Mar 12 '12 at 09:25

1 Answers1

0

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

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?

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

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>
Matt Handy
  • 29,855
  • 2
  • 89
  • 112
  • No. thats not the error. I removed that attribute and tried running. still gets the same error. I think it is the issue with the bytes[]. I dont know what wrong with that. do you have any running code with you? – user414967 Mar 12 '12 at 08:28
  • You could configure eclipselink that it logs all SQL statements. Updated my answer. – Matt Handy Mar 12 '12 at 08:32
  • Yaa I got the problem. the problem with the primary key autogenerated value. Now it works fine. thanks – user414967 Mar 12 '12 at 08:39