View Single Post
Old 08-03-2011, 13:17   #7
PGI-Bis
Senior Member
 
L'Avatar di PGI-Bis
 
Iscritto dal: Nov 2004
Città: Tra Verona e Mantova
Messaggi: 4553
In FetchData dichiari due campi, con e cmd, ma non assegni loro alcun valore.

Quando invochi close, usi quei due campi che sono "null", da cui la null pointer exception.

Nel metodo open crei due variabili locali che hanno lo stesso nome (con e cmd) ma sono due cose diverse (esistono in ambiti diversi).

Assegna ai campi con e cmd i valori delle variabili locali con e cmd:

...open(String c) ...
...
this.con = con;
this.cmd = cdm;
return res

Oppure ometti la dichiarazione delle variabili locali con e cmd nel metodo open:

//connessione
con = DriverManager.getConnection(url, "user", "pass");
cmd = con.createStatement();

Non trovando il tipo davanti al nome, il compilatore assegnerà i valori alle due cose che si chiamano "con" e "cmd" che sono in ambito, cioè i campi.

Nota che il codice che hai scritto è soggetto ad SQL injection.

Circa JPA, non è possibile dire se sia complicato o no, dipende dall'esperienza personale. C'è sicuramente meno da scrivere. Devi includere un'implementazione della api (ad esempio EclipseLink, TopLink o Hibernate), scrivi un descrittore xml che ha la forma:

Codice:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="NOME UNITA PERSISTENZA" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <properties>
      <property name="javax.persistence.jdbc.url" value="URL DI CONNESSIONE">
      <property name="javax.persistence.jdbc.password" value="rinoceratopo1976"/>
      <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
      <property name="javax.persistence.jdbc.user" value="postgres"/>
      <property name="eclipselink.ddl-generation" value="create-tables"/>
    </properties>
  </persistence-unit>
</persistence>
e lo ficchi in una cartella META-INF del classpath. A questo punto hai a disposizione la tua unità di persistenza nel programma.

La usi non diversamente da come faresti con driver, connessioni e compagnia bella: Dichiari un singleton:

Codice:
package test;

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

public class PersistenceLayer {

    //testPU è il nome dell'unità dichiarato nel descrittore xml
    private static final EntityManagerFactory emf = Persistence.createEntityManagerFactory("testPU");
    private static final EntityManager em = emf.createEntityManager();

    public static EntityManager getEntityManager() {
        return em;
    }

    public static void dispose() {
        try {
            em.close();
        } finally {
            emf.close();
        }
    }
}
E chiami "dispose" quando chiudi il tuo programma. Il tuo appliglio per parlare col database è quel getEntityManager. Puoi farci un tot di cose, nel caso più semplice salvi delle istanze di classi java dette entità che sono dei javabean annotati, ad esempio:

Codice:
package test;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class TestEntity implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    private String nome;
    private String cognome;

    /**
     * Instance initializer
     */
    public TestEntity() {
    }

    public String getCognome() {
        return cognome;
    }

    public void setCognome(String cognome) {
        this.cognome = cognome;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public Long getId() {
        return id;
    }

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

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.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 TestEntity)) {
            return false;
        }
        TestEntity other = (TestEntity) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "test.TestEntity[id=" + id + "]";
    }
}
Dirai ad esempio:

TestEntity x = new TestEntity();
x.setNome("pippo");
x.setCognome("rossi");
PersistenceLayer.getEntityManager().persist(x);

E morta lì.

Se usi Netbeans è tutto guidato (e immagino che lo stesso sia per Eclipse).
__________________
Uilliam Scecspir ti fa un baffo? Gioffri Cioser era uno straccione? E allora blogga anche tu, in inglese come me!
PGI-Bis è offline   Rispondi citando il messaggio o parte di esso