JPA - problem z połączeniem kolumn

0

Witam.
Problem z łączeniem kolumn.
Mam osobę która ma kilka książek, a więc relacja @OneToMany.

Kod Main:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jpa;

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

/**
 *
 * @author Michal
 */
public class JPA {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("JPAPU");
        EntityManager em = emf.createEntityManager();
        
        Osoba osoba= new Osoba();
        osoba.setImie("Jan");
        osoba.setNazwisko("Kowalski");
        
        Ksiazka ksiazka = new Ksiazka();
        ksiazka.setTytol("Moja pierwsza książka.");
        ksiazka.setRok("1992");
        
        
        em.getTransaction().begin();
        try {
            em.persist(osoba);
            em.persist(ksiazka);
            em.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            em.getTransaction().rollback();
        } finally {
            em.close();
        }
    }
}

 

Kod Osoby:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jpa;

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

/**
 *
 * @author Michal
 */
@Entity
public class Osoba implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String imie;
    private String nazwisko;
    private Set<Ksiazka> ksiazka;

    @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 Osoba)) {
            return false;
        }
        Osoba other = (Osoba) 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 "jpa.Osoba[ id=" + id + " ]";
    }
    
    public Long getId() {
        return id;
    }

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

    public String getImie() {
        return imie;
    }

    public void setImie(String imie) {
        this.imie = imie;
    }

    public String getNazwisko() {
        return nazwisko;
    }

    public void setNazwisko(String nazwisko) {
        this.nazwisko = nazwisko;
    }

    public Set<Ksiazka> getKsiazka() {
        return ksiazka;
    }

    public void setKsiazka(Set<Ksiazka> ksiazka) {
        this.ksiazka = ksiazka;
    }
    
}

Kod Ksiazka:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jpa;

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

/**
 *
 * @author Michal
 */
@Entity
public class Ksiazka implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String tytol;
    private String rok;

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

    @Override
    public String toString() {
        return "jpa.Ksiakzka[ id=" + getId() + " ]";
    }

    /**
     * @return the id
     */
    public Long getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(Long id) {
        this.id = id;
    }

    /**
     * @return the tytol
     */
    public String getTytol() {
        return tytol;
    }

    /**
     * @param tytol the tytol to set
     */
    public void setTytol(String tytol) {
        this.tytol = tytol;
    }

    /**
     * @return the rok
     */
    public String getRok() {
        return rok;
    }

    /**
     * @param rok the rok to set
     */
    public void setRok(String rok) {
        this.rok = rok;
    }
    
}

Bardzo proszę o pomoc.

0

Brakuje ci id właściciela książki, czy tylko pominąłeś w encji?

NetBeans umie generować encje dla tabel SQL razem z relacjami na podstawie utworzonej tablicy w bazie. Czyżby te adnotacje wszystkie nie były wymagane?

U osoby:

@OneToMany(cascade = CascadeType.ALL, mappedBy ="ksiazka", fetch=FetchType.EAGER)
private Ksiazka ksiazka;	

Przy książce:

@JoinColumn(name="osoba", referencedColumnName="id")
@ManyToOne(optional=false, fetch=FetchType.EAGER)
private Osoba osoba;

Kod na podstawie książki "JavaEE 6, Programowanie aplikacji www". Sporo w niej błędów i starych rozwiązań (jak przypisywanie walidatorów i ziaren zarządzanych w xml zamiast adnotacji), ale zła nie jest, jak się ma internet:p
Też się dopiero uczę.

BTW. tytuł, nie tytół:)

0

Więc problem dalej nie rozwiązany :(
Zmieniłem wszystko na rozwiązanie które sprawdziłem i działa. ale jak przerobiłem to na swój kod to nie działa :(

Kod teraz wygląda tak

package jpa;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="AUTORZY")
public class Autor implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Column(name = "numer_autora")
    private Long id;
    @Column(name="imie")
    private String imie;
    @Column(name="nazwisko")
    private String nazwisko;
    @JoinColumn(name="ksiazka")
    @ManyToOne
    private Ksiazka ksiazka;    

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

    @Override
    public String toString() {
        return "jpa.Autor[ id=" + getId() + " ]";
    }

    /**
     * @return the id
     */
    public Long getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(Long id) {
        this.id = id;
    }

    /**
     * @return the imie
     */
    public String getImie() {
        return imie;
    }

    /**
     * @param imie the imie to set
     */
    public void setImie(String imie) {
        this.imie = imie;
    }

    /**
     * @return the nazwisko
     */
    public String getNazwisko() {
        return nazwisko;
    }

    /**
     * @param nazwisko the nazwisko to set
     */
    public void setNazwisko(String nazwisko) {
        this.nazwisko = nazwisko;
    }

    /**
     * @return the ksiazka
     */
    public Ksiazka getKsiazka() {
        return ksiazka;
    }

    /**
     * @param ksiazka the ksiazka to set
     */
    public void setKsiazka(Ksiazka ksiazka) {
        this.ksiazka = ksiazka;
    }
    
}

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jpa;

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

/**
 *
 * @author Michal
 */
@Entity
@Table(name="Ksiazki")
public class Ksiazka implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @Column(name="ksiazka")
    private String tytul;

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

    @Override
    public String toString() {
        return "jpa.Ksiazka[ id=" + getId() + " ]";
    }

    /**
     * @return the id
     */
    public Long getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(Long id) {
        this.id = id;
    }

    /**
     * @return the tytul
     */
    public String getTytul() {
        return tytul;
    }

    /**
     * @param tytul the tytul to set
     */
    public void setTytul(String tytul) {
        this.tytul = tytul;
    }
}

/*

  • To change this template, choose Tools | Templates
  • and open the template in the editor.
    */
    package jpa;

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

/**
*

  • @Author Michal
    */
    public class JPA {

    public static void main(String[] a) {
    JPA tryInsert = new JPA();
    Ksiazka ksiazka = new Ksiazka();
    ksiazka.setTytul("Dupa");
    tryInsert.persist(ksiazka);
    Autor autor = new Autor();
    autor.setId(1L);
    autor.setImie("Jurek");
    autor.setNazwisko("Gryzipiórek");
    autor.setKsiazka(ksiazka);
    tryInsert.persist(autor);
    }

    public void persist(Object object) {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("JPAPU");
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();
    try {
    em.persist(object);
    em.getTransaction().commit();
    } catch (Exception e) {
    e.printStackTrace();
    em.getTransaction().rollback();
    } finally {
    em.close();
    }
    }
    }


No i oczywiście błąd.

run:
Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named JPAPU: Provider named oracle.toplink.essentials.PersistenceProvider threw unexpected exception at create EntityManagerFactory: 
oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException
Local Exception Stack: 
Exception [TOPLINK-30005] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while searching for persistence archives with ClassLoader: sun.misc.Launcher$AppClassLoader@d9f9c3
Internal Exception: javax.persistence.PersistenceException: Exception [TOPLINK-28018] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.EntityManagerSetupException
Exception Description: predeploy for PersistenceUnit [JPAPU] failed.
Internal Exception: Exception [TOPLINK-30007] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while loading class: jpa.Osoba to check whether it implements @Entity, @Embeddable, or @MappedSuperclass.
Internal Exception: java.lang.ClassNotFoundException: jpa.Osoba
	at oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(PersistenceUnitLoadingException.java:143)
	at oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider.createEntityManagerFactory(EntityManagerFactoryProvider.java:169)
	at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:110)
	at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:83)
	at jpa.JPA.persist(JPA.java:31)
	at jpa.JPA.main(JPA.java:21)
Caused by: javax.persistence.PersistenceException: Exception [TOPLINK-28018] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.EntityManagerSetupException
Exception Description: predeploy for PersistenceUnit [JPAPU] failed.
Internal Exception: Exception [TOPLINK-30007] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while loading class: jpa.Osoba to check whether it implements @Entity, @Embeddable, or @MappedSuperclass.
Internal Exception: java.lang.ClassNotFoundException: jpa.Osoba
	at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:643)
	at oracle.toplink.essentials.internal.ejb.cmp3.JavaSECMPInitializer.callPredeploy(JavaSECMPInitializer.java:171)
	at oracle.toplink.essentials.internal.ejb.cmp3.JavaSECMPInitializer.initPersistenceUnits(JavaSECMPInitializer.java:239)
	at oracle.toplink.essentials.internal.ejb.cmp3.JavaSECMPInitializer.initialize(JavaSECMPInitializer.java:255)
	at oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider.createEntityManagerFactory(EntityManagerFactoryProvider.java:155)
	... 4 more
Caused by: Exception [TOPLINK-28018] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.EntityManagerSetupException
Exception Description: predeploy for PersistenceUnit [JPAPU] failed.
Internal Exception: Exception [TOPLINK-30007] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while loading class: jpa.Osoba to check whether it implements @Entity, @Embeddable, or @MappedSuperclass.
Internal Exception: java.lang.ClassNotFoundException: jpa.Osoba
	at oracle.toplink.essentials.exceptions.EntityManagerSetupException.predeployFailed(EntityManagerSetupException.java:228)
	... 9 more
Caused by: Exception [TOPLINK-30007] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while loading class: jpa.Osoba to check whether it implements @Entity, @Embeddable, or @MappedSuperclass.
Internal Exception: java.lang.ClassNotFoundException: jpa.Osoba
	at oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException.exceptionLoadingClassWhileLookingForAnnotations(PersistenceUnitLoadingException.java:160)
	at oracle.toplink.essentials.ejb.cmp3.persistence.PersistenceUnitProcessor.isEntity(PersistenceUnitProcessor.java:319)
	at oracle.toplink.essentials.internal.ejb.cmp3.metadata.MetadataProcessor.buildEntityClassSetFromAnnotations(MetadataProcessor.java:491)
	at oracle.toplink.essentials.internal.ejb.cmp3.metadata.MetadataProcessor.buildEntityList(MetadataProcessor.java:462)
	at oracle.toplink.essentials.ejb.cmp3.persistence.PersistenceUnitProcessor.processORMetadata(PersistenceUnitProcessor.java:366)
	at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:607)
	... 8 more
Caused by: java.lang.ClassNotFoundException: jpa.Osoba
	at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
	at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
	at oracle.toplink.essentials.ejb.cmp3.persistence.PersistenceUnitProcessor.isEntity(PersistenceUnitProcessor.java:316)
	... 12 more


 The following providers:
oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider
Returned null to createEntityManagerFactory.

	at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:154)
	at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:83)
	at jpa.JPA.persist(JPA.java:31)
	at jpa.JPA.main(JPA.java:21)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

0

Działa ;]

Błędem okazał się dodatkowy stary wpis w pliku persistence.xml.

1 użytkowników online, w tym zalogowanych: 0, gości: 1