d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Saving Picture On Jdbc Database > 100 Fg Reward If It Works.
Add Reply New Topic New Poll
Member
Posts: 4,478
Joined: Feb 10 2010
Gold: 1,806.00
May 10 2013 01:56pm
Thought I had this figured out. But this problem has broken my spirit.
If someone post a solution that works. I pay 100 fg. I will post the winner in this thread.
Any solution that doesnt work. I will also post the problem.

I have a JDBC database set up. Have the entity class and jpa class to.

Have never succeeded in saving the picture only the path of the picture.

Code
package holdem;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;

/**
*
* @author Sune Utoft Jensen
*/
@Entity
@Table(name = "GTSPILLER")
@XmlRootElement
@NamedQueries({
   @NamedQuery(name = "Gtspiller.findAll", query = "SELECT g FROM Gtspiller g"),
   @NamedQuery(name = "Gtspiller.findByIdnummer", query = "SELECT g FROM Gtspiller g WHERE g.idnummer = :idnummer"),
   @NamedQuery(name = "Gtspiller.findByNavn", query = "SELECT g FROM Gtspiller g WHERE g.navn = :navn"),
   @NamedQuery(name = "Gtspiller.findByRoll", query = "SELECT g FROM Gtspiller g WHERE g.roll = :roll"),
   @NamedQuery(name = "Gtspiller.findByStrategi", query = "SELECT g FROM Gtspiller g WHERE g.strategi = :strategi"),
   @NamedQuery(name = "Gtspiller.findByStack", query = "SELECT g FROM Gtspiller g WHERE g.stack = :stack")})
public class Gtspiller implements Serializable {
   private static final long serialVersionUID = 1L;
   @Id
   @Basic(optional = false)
   @Column(name = "IDNUMMER")
   private Integer idnummer;
   @Column(name = "NAVN")
   private String navn;
   // @Max(value=?)  @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
   @Column(name = "ROLL")
   private Double roll;
   @Lob
   @Column(name = "BILLEDE")
   private Serializable billede;
   @Column(name = "STRATEGI")
   private Integer strategi;
   @Column(name = "STACK")
   private Double stack;

   public Gtspiller() {
   }

   public Gtspiller(Integer idnummer) {
       this.idnummer = idnummer;
   }

   public Integer getIdnummer() {
       return idnummer;
   }

   public void setIdnummer(Integer idnummer) {
       this.idnummer = idnummer;
   }

   public String getNavn() {
       return navn;
   }

   public void setNavn(String navn) {
       this.navn = navn;
   }

   public Double getRoll() {
       return roll;
   }

   public void setRoll(Double roll) {
       this.roll = roll;
   }

   public Serializable getBillede() {
       return billede;
   }

   public void setBillede(Serializable billede) {
       this.billede = billede;
   }

   public Integer getStrategi() {
       return strategi;
   }

   public void setStrategi(Integer strategi) {
       this.strategi = strategi;
   }

   public Double getStack() {
       return stack;
   }

   public void setStack(Double stack) {
       this.stack = stack;
   }

   @Override
   public int hashCode() {
       int hash = 0;
       hash += (idnummer != null ? idnummer.hashCode() : 0);
       return hash;
   }

   @Override
   public boolean equals(Object object) {
       // TODO: Warning - this method won't work in the case the id fields are not set
       if (!(object instanceof Gtspiller)) {
           return false;
       }
       Gtspiller other = (Gtspiller) object;
       if ((this.idnummer == null && other.idnummer != null) || (this.idnummer != null && !this.idnummer.equals(other.idnummer))) {
           return false;
       }
       return true;
   }

   @Override
   public String toString() {
       return "holdem.Gtspiller[ idnummer=" + idnummer + " ]";
   }
   
}


Code
package holdem;

import holdem.exceptions.NonexistentEntityException;
import holdem.exceptions.PreexistingEntityException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
*
* @author Sune Utoft Jensen
*/
public class GtspillerJpaController implements Serializable {

   public GtspillerJpaController(EntityManagerFactory emf) {
       this.emf = emf;
   }
   private EntityManagerFactory emf = null;

   public EntityManager getEntityManager() {
       return emf.createEntityManager();
   }

   public void create(Gtspiller gtspiller) throws PreexistingEntityException, Exception {
       EntityManager em = null;
       try {
           em = getEntityManager();
           em.getTransaction().begin();
           em.persist(gtspiller);
           em.getTransaction().commit();
       } catch (Exception ex) {
           if (findGtspiller(gtspiller.getIdnummer()) != null) {
               throw new PreexistingEntityException("Gtspiller " + gtspiller + " already exists.", ex);
           }
           throw ex;
       } finally {
           if (em != null) {
               em.close();
           }
       }
   }

   public void edit(Gtspiller gtspiller) throws NonexistentEntityException, Exception {
       EntityManager em = null;
       try {
           em = getEntityManager();
           em.getTransaction().begin();
           gtspiller = em.merge(gtspiller);
           em.getTransaction().commit();
       } catch (Exception ex) {
           String msg = ex.getLocalizedMessage();
           if (msg == null || msg.length() == 0) {
               Integer id = gtspiller.getIdnummer();
               if (findGtspiller(id) == null) {
                   throw new NonexistentEntityException("The gtspiller with id " + id + " no longer exists.");
               }
           }
           throw ex;
       } finally {
           if (em != null) {
               em.close();
           }
       }
   }

   public void destroy(Integer id) throws NonexistentEntityException {
       EntityManager em = null;
       try {
           em = getEntityManager();
           em.getTransaction().begin();
           Gtspiller gtspiller;
           try {
               gtspiller = em.getReference(Gtspiller.class, id);
               gtspiller.getIdnummer();
           } catch (EntityNotFoundException enfe) {
               throw new NonexistentEntityException("The gtspiller with id " + id + " no longer exists.", enfe);
           }
           em.remove(gtspiller);
           em.getTransaction().commit();
       } finally {
           if (em != null) {
               em.close();
           }
       }
   }

   public List<Gtspiller> findGtspillerEntities() {
       return findGtspillerEntities(true, -1, -1);
   }

   public List<Gtspiller> findGtspillerEntities(int maxResults, int firstResult) {
       return findGtspillerEntities(false, maxResults, firstResult);
   }

   private List<Gtspiller> findGtspillerEntities(boolean all, int maxResults, int firstResult) {
       EntityManager em = getEntityManager();
       try {
           CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
           cq.select(cq.from(Gtspiller.class));
           Query q = em.createQuery(cq);
           if (!all) {
               q.setMaxResults(maxResults);
               q.setFirstResult(firstResult);
           }
           return q.getResultList();
       } finally {
           em.close();
       }
   }

   public Gtspiller findGtspiller(Integer id) {
       EntityManager em = getEntityManager();
       try {
           return em.find(Gtspiller.class, id);
       } finally {
           em.close();
       }
   }

   public int getGtspillerCount() {
       EntityManager em = getEntityManager();
       try {
           CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
           Root<Gtspiller> rt = cq.from(Gtspiller.class);
           cq.select(em.getCriteriaBuilder().count(rt));
           Query q = em.createQuery(cq);
           return ((Long) q.getSingleResult()).intValue();
       } finally {
           em.close();
       }
   }
   
}


Below is the kind of things I have tried. Have worked more than 30 hours on this. Cant get it to work

Code
      public void savepic(String a, int b) throws IOException//a navn og b sæde
      {
         
  EntityManagerFactory  factory = Persistence.createEntityManagerFactory("Contact DB");
  EntityManager em = factory.createEntityManager();
  em.getTransaction().begin();
          Gtspiller dyr = em.find(Gtspiller.class, b);    
  File fi = new File("D:\\portræt\\"+a+".gif");
 byte[] content = new byte[(int)fi.length()];
  dyr.setBillede(content);
  updatebillede(1,content);
     em.getTransaction().commit();
  em.close();
 
      }




Member
Posts: 2,757
Joined: Nov 26 2007
Gold: 1,214.81
May 10 2013 02:21pm
this is how i do it...

Code
File fi = new File( "yourimage.gif" );
   BufferedImage bufferedImage = ImageIO.read( fi );

   WritableRaster raster = bufferedImage.getRaster( );
   DataBufferByte data = (DataBufferByte) raster.getDataBuffer( );

   //Store base64 encoded bytes (returns string) in database
   Base64.encodeBytes( data.getData( ) );


i couldn't post Base64.java cus it's too long. But you can find it on google.

This post was edited by labatymo on May 10 2013 02:22pm
Member
Posts: 4,478
Joined: Feb 10 2010
Gold: 1,806.00
May 10 2013 02:35pm
@labatymo

dont quite undestand the base64 thing.

Im using netbeans. Can I import it or do I need to make a class like this ?

http://www.wikihow.com/Encode-a-String-to-Base64-With-Java
Member
Posts: 2,757
Joined: Nov 26 2007
Gold: 1,214.81
May 10 2013 08:08pm
Quote (tigeranden @ May 10 2013 04:35pm)
@labatymo

dont quite undestand the base64 thing.

Im using netbeans. Can I import it or do I need to make a class like this ?

http://www.wikihow.com/Encode-a-String-to-Base64-With-Java


You can probably find a jar to import, but it's easier if you just create a class called Base64 and copy paste from another one you find on the Internet. Base64 is just a way to encode large amounts of data so it's easier to store in a database. You can use Base64 to decode it back to a byte array and create the image
Member
Posts: 4,478
Joined: Feb 10 2010
Gold: 1,806.00
May 12 2013 03:55am
This is what I ended up with. with help from elsewhere

Thank you labatymo for help. Tell me what is a fair payment.

package jpablob;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

/*
* CREATE TABLE picture (id INTEGER NOT NULL, image BLOB, PRIMARY KEY(id));
*/
@Entity
@Table(name="picture")
public class Picture {
private int id;
private byte[] image;
@Id
@Column(name="id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="image")
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
}



<persistence xmlns="http://java.sun.com/ (...)
xmlns:xsi="http://www.w3.org/ (...)
xsi:schemaLocation="http://java.sun.com/ (...) http://java.sun.com/ (...)
version="2.0">
<persistence-unit name="test">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>jpablob.Picture</class>
<exclude-unlisted-classes/>
<properties>
<!--<property name="show_sql">true</property>-->
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost/Test"/>
<property name="hibernate.connection.username" value=""/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.pool_size" value="5"/>
</properties>
</persistence-unit>
</persistence>



package jpablob;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class TestSave {
public static void main(String[] args) {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("test");
EntityManager em = factory.createEntityManager();
Picture p = new Picture();
p.setId(1);
p.setImage(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
em.getTransaction().begin();
em.persist(p);
em.getTransaction().commit();
em.close();
}
}



package jpablob;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class TestLoad {
public static void main(String[] args) {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("test");
EntityManager em = factory.createEntityManager();
Picture p = em.find(Picture.class, 1);
em.close();
System.out.println(p.getId());
for(byte b : p.getImage()) {
System.out.print(" " + b);
}
System.out.println();
}
}
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll