JPA OneToMany ManyToOne #OneToOne or #ManyToOne on references an unknown entity: - java

I am just not getting the point here. Whats going on with the following code, where is the error? I have to Classes: Ressource and Reservation. A Resource can have multiple Reserverations and the relation is bidirectional. To me, eveything seems find and I have looked at a bunch ressources and documentations - ah yep, also at a lot of examples and I cant get to the rootcause of this.
Any body of you gets the issue, or could somebody at least tell me that nothing is wrong with it:)
package org.ademi.model;
import java.io.Serializable;
import java.util.Calendar;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.Entity;
#Entity
#Table(name="Ressource")
public class Ressource implements Serializable{
private static final long serialVersionUID = 12L;
/**
* A Ressource is available from a specific Date.
*/
private Calendar availableFrom;
/**
* A Ressource is available until specific Date.
*/
private Calendar availableTo;
/**
* This is a unique Ressource ID.
*/
private int id;
/**
* A set of reservations that belong to this ressource
*/
private List<Reservation> reservations;
/**
* A list of Days, when the ressource is available
*/
private List<Day> daysAvailable;
/**
* This is specifying the intervall aloud for the reservation;
*/
private Intervall intervall;
/**
* Type of the ressource
*/
private String type;
/**
* Name of the ressource
*/
private String name;
public Ressource(String name, String type, Calendar availableFrom, Calendar availableto, List<Day> daysAvailable, Intervall intervall){
this.availableFrom = availableFrom;
this.availableTo = availableto;
this.daysAvailable = daysAvailable;
}
#Temporal(TemporalType.DATE)
public Calendar getAvailableFrom() {
return availableFrom;
}
public void setAvailableFrom(Calendar availableFrom) {
this.availableFrom = availableFrom;
}
#Temporal(TemporalType.DATE)
public Calendar getAvailableTo() {
return availableTo;
}
public void setAvailableTo(Calendar availableTo) {
this.availableTo = availableTo;
}
#Id
#GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#OneToMany(mappedBy="Reservation",cascade = CascadeType.ALL)
public List<Reservation> getReservations() {
return reservations;
}
public void setReservations(List<Reservation> reservations) {
this.reservations = reservations;
}
#Enumerated(EnumType.STRING)
public Intervall getIntervall() {
return intervall;
}
public void setIntervall(Intervall intervall) {
this.intervall = intervall;
}
#ElementCollection(targetClass=Day.class)
#Enumerated(EnumType.STRING)
#CollectionTable(name="daysAvailable")
#Column(name="daysAvailable")
public List<Day> getDaysAvailable() {
return daysAvailable;
}
public void setDaysAvailable(List<Day> daysAvailable) {
this.daysAvailable = daysAvailable;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package org.ademi.model;
import java.io.Serializable;
import java.util.Calendar;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name="Reservation")
public class Reservation implements Serializable{
private static final long serialVersionUID = 1L;
/**
* A unique ID belonging to a reservation.
*/
private int id;
/**
* Timesstamp for the beginning of the reservation
*/
private Calendar reservationStarts;
/**
* Amount of Intervalls for the reservation
*/
private int reservedIntervalls;
/**
* A short summary Title describing the reservation
*/
private String title;
/**
* The resource which is reserved in this reservation.
*/
private Ressource ressource;
public Reservation(String title, Ressource ressource, Calendar reservationStarts, int reservedIntervalls){
this.title = title;
this.ressource = ressource;
this.reservationStarts = reservationStarts;
this.reservedIntervalls = reservedIntervalls;
}
#Id
#GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Temporal(TemporalType.TIMESTAMP)
public Calendar getReservationStarts() {
return reservationStarts;
}
public void setReservationStarts(Calendar reservationStarts) {
this.reservationStarts = reservationStarts;
}
public int getReservedIntervalls() {
return reservedIntervalls;
}
public void setReservedIntervalls(int reservedIntervalls) {
this.reservedIntervalls = reservedIntervalls;
}
#ManyToOne
#JoinColumn(name="ressource_ID")
public Ressource getRessource() {
return ressource;
}
public void setRessource(Ressource ressource) {
this.ressource = ressource;
}
}
My persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence
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_1_0.xsd"
version="1.0">
<persistence-unit name="iplandb">
<properties>
<!--
<property name="hibernate.ejb.cfgfile" value="/hibernate.cfg.xml"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
-->
<property name="hibernate.archive.autodetection" value="class, hbm"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.password" value="kbausbes"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/iplandb"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.c3p0.min_size" value="5"/>
<property name="hibernate.c3p0.max_size" value="20"/>
<property name="hibernate.c3p0.timeout" value="300"/>
<property name="hibernate.c3p0.max_statements" value="50"/>
<property name="hibernate.c3p0.idle_test_period" value="3000"/>
</properties>
</persistence-unit>
</persistence>
A simple TestingClass
package org.ademi.client;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import org.ademi.model.Day;
import org.ademi.model.Intervall;
import org.ademi.model.Ressource;
public class TestClient {
public static void main(String[] args){
EntityManagerFactory emf = Persistence
.createEntityManagerFactory("iplandb");
/* Create EntityManager */
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
ArrayList<Day> a = new ArrayList<Day>();
a.add(Day.FRIDAY);
Ressource r = new Ressource("ilir", "ademi", new GregorianCalendar(), new GregorianCalendar(),a, Intervall.EIGHT );
em.persist(r);
em.flush();
}
}
And this is the Exceptions I am getting:
Exception in thread "main" javax.persistence.PersistenceException: [PersistenceUnit: iplandb] Unable to configure EntityManagerFactory
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:265)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:125)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:52)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:34)
at org.ademi.client.TestClient.main(TestClient.java:20)
Caused by: org.hibernate.AnnotationException: #OneToOne or #ManyToOne on org.ademi.model.Reservation.ressource references an unknown entity: org.ademi.model.Ressource
at org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(ToOneFkSecondPass.java:81)
at org.hibernate.cfg.AnnotationConfiguration.processEndOfQueue(AnnotationConfiguration.java:456)
at org.hibernate.cfg.AnnotationConfiguration.processFkSecondPassInOrder(AnnotationConfiguration.java:438)
at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:309)
at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1162)
at org.hibernate.ejb.Ejb3Configuration.buildMappings(Ejb3Configuration.java:1226)
at org.hibernate.ejb.EventListenerConfigurator.configure(EventListenerConfigurator.java:173)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:854)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:191)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:253)
... 4 more

The class is annotated with #org.hibernate.annotations.Entity. It must be annotated with javax.persistence.Entity.
Fix your import.
Another problem is that mappedBy="Reservation" should be mappedBy="ressource". mappedBy contains the name of the property of the target class that is the owner side of the association.

Related

Java Hibernate delete Object

Today I did some experiments with hibernate.
First of all there is no deeper sense behind my program. I just wanted to try the framework.
I planed the following db tables:
Car (Auto)
Driver (Fahrer)
Wohnung (Flat)
Guest (Fahrgast)
with the following bidirectional mappings:
driver – flat onetoone
driver – car onetomany
car – guest manytomany
After preparing the single classes I wrote my worker to insert some demodata. Up to this point everything works as expected.
Finally I would like to remove one of my drivers. But hibernate tells me, that it would be re-saved by a certain guest. Unfortunately I don’t understand why.
I expected everything to be fine after removing the driver from the driver collection of the corresponding cars.
class car
package mycode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="auto")
public class Auto {
#Id #GeneratedValue
private int id;
#Column(name="nummernschild", nullable = false)
private String nummernschild;
#OneToMany(cascade=CascadeType.ALL, mappedBy="auto")
private List<Fahrer>fahrers = new ArrayList<Fahrer>();
#ManyToMany(cascade=CascadeType.ALL)
private List<Fahrgast>fahrgasts = new ArrayList<Fahrgast>();
public List<Fahrgast> getFahrgasts() {
return fahrgasts;
}
public void setFahrgasts(List<Fahrgast> fahrgasts) {
this.fahrgasts = fahrgasts;
}
public List<Fahrer> getFahrers() {
return fahrers;
}
public void setFahrers(List<Fahrer> fahrers) {
this.fahrers = fahrers;
}
private LocalDate kaufdatum;
public LocalDate getKaufdatum() {
return kaufdatum;
}
public void setKaufdatum(LocalDate kaufdatum) {
this.kaufdatum = kaufdatum;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNummernschild() {
return nummernschild;
}
public void setNummernschild(String nummernschild) {
this.nummernschild = nummernschild;
}
}
class driver
package mycode;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="fahrer")
public class Fahrer {
#Id #GeneratedValue()
private int id;
private String vorname, nachname;
private int alter;
#OneToOne (cascade=CascadeType.ALL)
#JoinColumn(name="id")
private Wohnung wohnung;
#ManyToOne(cascade=CascadeType.ALL)
private Auto auto;
public Auto getAuto() {
return auto;
}
public void setAuto(Auto auto) {
this.auto = auto;
}
public Wohnung getWohnung() {
return wohnung;
}
public void setWohnung(Wohnung wohnung) {
this.wohnung = wohnung;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getVorname() {
return vorname;
}
public void setVorname(String vorname) {
this.vorname = vorname;
}
public String getNachname() {
return nachname;
}
public void setNachname(String nachname) {
this.nachname = nachname;
}
public int getAlter() {
return alter;
}
public void setAlter(int alter) {
this.alter = alter;
}
}
class flat
package mycode;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
#Entity
#Table(name="wohnung")
public class Wohnung {
#Id #GeneratedValue(generator = "newGenerator")
#GenericGenerator(name="newGenerator", strategy="foreign" , parameters= {#Parameter(value="fahrer", name="property")})
private int id;
#Column(nullable=false)
private String ort, straße;
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name="id")
private Fahrer fahrer;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getOrt() {
return ort;
}
public void setOrt(String ort) {
this.ort = ort;
}
public String getStraße() {
return straße;
}
public void setStraße(String straße) {
this.straße = straße;
}
public Fahrer getFahrer() {
return fahrer;
}
public void setFahrer(Fahrer fahrer) {
this.fahrer = fahrer;
}
}
class guest
package mycode;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
#Entity
#Table(name="fahrgast")
public class Fahrgast {
#Id #GeneratedValue
private int id;
#Column(nullable=false)
private int kundennummmer;
private String vornname, nachname;
#ManyToMany(mappedBy="fahrgasts")
private List<Auto>autos = new ArrayList<Auto>();
public List<Auto> getAutos() {
return autos;
}
public void setAutos(List<Auto> autos) {
this.autos = autos;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getKundennummmer() {
return kundennummmer;
}
public void setKundennummmer(int kundennummmer) {
this.kundennummmer = kundennummmer;
}
public String getVornname() {
return vornname;
}
public void setVornname(String vornname) {
this.vornname = vornname;
}
public String getNachname() {
return nachname;
}
public void setNachname(String nachname) {
this.nachname = nachname;
}
}
class worker
package mycode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class Worker {
private Session session;
private SessionFactory sf;
public static void main(String[] args) {
Worker worker = new Worker();
worker.work();
}
private void init()
{
Configuration configuration = new Configuration().configure();
sf = configuration.buildSessionFactory();
session = sf.openSession();
}
private void work()
{
init();
Auto auto = new Auto();
auto.setNummernschild("HH:MK:"+1);
LocalDate ld = LocalDate.now();
auto.setKaufdatum(ld);
session.beginTransaction();
for (int i=0; i<10; i++)
{
auto = new Auto();
auto.setNummernschild("HH:MK:"+i);
ld = LocalDate.now();
auto.setKaufdatum(ld);
Auto auto2 = new Auto();
auto2.setNummernschild("HH:MK:"+i);
ld = LocalDate.now();
auto2.setKaufdatum(ld);
//auto.setId(i);
Fahrer fahrer = new Fahrer();
fahrer.setVorname("Hans");
fahrer.setNachname("Huber");
Fahrer fahrer2 = new Fahrer();
fahrer2.setVorname("Anna");
fahrer2.setNachname("Schmidt");
double temp = Math.random();
int alter = (int)(temp*50);
fahrer.setAlter(alter);
fahrer2.setAlter(alter);
fahrer.setAuto(auto);
fahrer2.setAuto(auto2);
Wohnung wohnung = createWohnung(i);
wohnung.setFahrer(fahrer);
fahrer.setWohnung(wohnung);
Wohnung wohnung2 = createWohnung(i*10);
fahrer2.setWohnung(wohnung2);
wohnung2.setFahrer(fahrer2);
auto.getFahrers().add(fahrer);
auto2.getFahrers().add(fahrer2);
double zufall = Math.random()*100;
int zu = (int)zufall;
for (int z=0; z<zu; z++)
{
Fahrgast fahrgast = new Fahrgast();
fahrgast.setVornname("Hans"+z);
fahrgast.setNachname("Dampf"+z);
double kundennummer = Math.random()*10000;
fahrgast.setKundennummmer((int)kundennummer);
fahrgast.getAutos().add(auto);
fahrgast.getAutos().add(auto2);
auto.getFahrgasts().add(fahrgast);
auto2.getFahrgasts().add(fahrgast);
}
// session.save(fahrer);
// session.save(fahrer2);
session.save(auto);
session.save(auto2);
}
Fahrer abfrage = session.get(Fahrer.class, 2);
List<Fahrer>fahrers = session.createCriteria(Fahrer.class).list();
List<Fahrer>tobedeletet = new ArrayList<Fahrer>();
for (Fahrer aktuell : fahrers)
{
Auto car = aktuell.getAuto();
List<Fahrer>cardriver = car.getFahrers();
Fahrer temp = null;
for (Fahrer driver: cardriver)
{
if (driver.getId()==abfrage.getId())
{
tobedeletet.add(aktuell);
temp = driver;
}
}
cardriver.remove(temp);
session.update(car);
}
for (Fahrer aktuell : tobedeletet)
{
session.remove(aktuell);
}
System.out.println(abfrage.getVorname()+ " "+abfrage.getNachname());
session.getTransaction().commit();
session.close();
sf.close();
}
private Wohnung createWohnung(int i)
{
Wohnung wohnung = new Wohnung();
wohnung.setOrt("bla"+i);
wohnung.setStraße("blub"+i);
return wohnung;
}
}
finally the configuration file
<?xml version='1.0' encoding='utf-8'?>
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property
name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://192.168.2.252:5432/test</property>
<property name="connection.username">postgres</property>
<property name="connection.password">postgres</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<mapping class="mycode.Auto"/>
<mapping class="mycode.Fahrer"/>
<mapping class="mycode.Wohnung"/>
<mapping class="mycode.Fahrgast"/>
</session-factory>
Can anybody tell me, how to delete one of my drivers?
The error message:
ERROR: HHH000346: Error during managed flush [deleted object would be re-saved by cascade (remove deleted object from associations): [mycode.Fahrgast#3]]
Exception in thread "main" javax.persistence.EntityNotFoundException: deleted object would be re-saved by cascade (remove deleted object from associations): [mycode.Fahrgast#3]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:126)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:155)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:162)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1441)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:491)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3201)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2411)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:467)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:146)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:220)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68)
at mycode.Worker.work(Worker.java:133)
at mycode.Worker.main(Worker.java:19)
First things first, hope you know that alter is a reserved word, alter table <table_name>;, so you have to change your column name in Fahrer class:
#Column(name = "_alter") // choose any name you want
private int alter;
After that, why do you need so many bidirectional relationships? And look, you have:
class Fahrer {
// ...
#ManyToOne(cascade = CascadeType.ALL)
private Auto auto;
That means, when you delete a fahrer, the auto is deleted to. Is this realy what you want?
Now look at your code:
// at first you check if the ID is equal to abfrage and add it to list
if (driver.getId() == abfrage.getId()) {
tobedeletet.add(aktuell);
temp = driver;
}
// at the end you formed a list tobedeleted witch contains elements with the same ID.
for (Fahrer aktuell : tobedeletet) {
session.remove(aktuell);
}
To be honest, I'm a java beginner, so I may miss something. But deleting an entity with the same ID value a few times is propably not necessary.
Your exception says: remove deleted object from associations
It sould be enough just to remove the fahrer from the Auto#fahrers collection and update auto:
auto.getFahrers().remove(fahrer);
// remove other fahrers
session.update(auto);
Because you have a cascade=CascadeType.ALL property on your auto-to-fahrers relationship in Auto class, after updating the Auto, Fahrer should be deleted automaticly.
More about here: https://stackoverflow.com/a/11649941/6521788
And few things to notice:
PLEASE, use one language in your code :). Auto car = aktuell.getAuto();. You get auto, but the variable is called car...
PostgreSQLDialect is deprecated, choose PostgreSQL9Dialect or others in your hibernate config;
auto is a reserved name, better use something else.
Thanks to Oles,
I updated my code to
List<Auto>autos = session.createCriteria(Auto.class).list();
List<Auto>toBeUpdated = new ArrayList<Auto>();
for (Auto fahzeug : autos)
{
List<Fahrer>fahrers2 = fahzeug.getFahrers();
for (Fahrer aktuell : fahrers2)
{
if (aktuell.getId()==abfrage.getId())
{
toBeUpdated.add(fahzeug);
}
}
}
for (Auto fahrzeug : toBeUpdated)
{
fahrzeug.getFahrers().remove(abfrage);
System.out.println("removed");
session.update(fahrzeug);
}
Unfortunately still something doesn’t work as expected. I can’t do the remove inside the fahrerloop, because that ends with a concurrentmodificationexception. With the code posted here, there are no further exceptions. The debugging view shows me, that there are no drivers left for one of the cars after the last loop. Especially the driver with the id 2 gets deleted from the driver list. Unfortunately the driver remains in the database. That shouldn’t be the case, if I understood the last answer correctly.

Another pojo class is not creating table in database in hibernate

TrainingDays.java
package com.hibernate;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "TrainingDays")
public class TrainingDays {
#Id
#GeneratedValue
private int TD_Id;
private String T_Days;
public int getTD_Id() {
return TD_Id;
}
public void setTD_Id(int tD_Id) {
TD_Id = tD_Id;
}
public String getT_Days() {
return T_Days;
}
public void setT_Days(String t_Days) {
T_Days = t_Days;
}
#OneToMany(cascade={CascadeType.ALL})
#JoinColumn(name="TD_Id")
private Set<TrainingTime> trainingTime;
public Set<TrainingTime> getTrainingTime() {
return trainingTime;
}
public void setTrainingTime(Set<TrainingTime> trainingTime) {
this.trainingTime = trainingTime;
}
}
TrainingTime.java
package com.hibernate;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "TrainingTime")
public class TrainingTime {
#Id
#GeneratedValue
private int TT_Id;
#ManyToOne
#JoinColumn(name = "TD_Id")
private TrainingDays trainingDays;
private String time;
private String desc;
public int getTT_Id() {
return TT_Id;
}
public void setTT_Id(int tT_Id) {
TT_Id = tT_Id;
}
public TrainingDays getTrainingDays() {
return trainingDays;
}
public void setTrainingDays(TrainingDays trainingDays) {
this.trainingDays = trainingDays;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
Hibernate.cfg.xml
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<property name="connection.url">jdbc:oracle:thin:#localhost:1521:xe</property>
<property name="connection.username">blueHeaven</property>
<property name="connection.password">123456</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<mapping class="com.hibernate.Rodie" />
<mapping class="com.hibernate.TrainingTime" />
<mapping class="com.hibernate.TrainingDays" />
</session-factory>
In the database TraningDays table is created but traningTime table is not created.
Can any one help?
Please correct your code as given:
class TrainingDays
#Entity
#Table(name = "TrainingDays")
public class TrainingDays {
#OneToMany(cascade={CascadeType.ALL},mappedBy = "trainingDays")
private Set<TrainingTime> trainingTime;
}
class TrainingTime
#Entity
#Table(name = "TrainingTime")
public class TrainingTime {
#ManyToOne
#JoinColumn(name = "TD_Id")
private TrainingDays trainingDays;
}
You need to specify "mappedBy" when you are creating bidirectional
relationship.
As the mapping is bidirectional. Please try like this.
TrainingDays.java
import java.io.Serializable;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "TrainingDays")
public class TrainingDays implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="TD_Id")
private int TD_Id;
#Column(name="T_Days")
private String T_Days;
#OneToMany(mappedBy="trainingDays")
private Set<TrainingTime> trainingTime;
public int getTD_Id() {
return TD_Id;
}
public void setTD_Id(int tD_Id) {
TD_Id = tD_Id;
}
public String getT_Days() {
return T_Days;
}
public void setT_Days(String t_Days) {
T_Days = t_Days;
}
public Set<TrainingTime> getTrainingTime() {
return trainingTime;
}
public void setTrainingTime(Set<TrainingTime> trainingTime) {
this.trainingTime = trainingTime;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
TrainingTime.java
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 = "TrainingTime")
public class TrainingTime implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="TT_Id")
private int TT_Id;
#Column(name="time")
private String time;
#Column(name="desc")
private String desc;
#ManyToOne
#JoinColumn(name="TD_Id")
private TrainingDays trainingDays;
public int getTT_Id() {
return TT_Id;
}
public void setTT_Id(int tT_Id) {
TT_Id = tT_Id;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public TrainingDays getTrainingDays() {
return trainingDays;
}
public void setTrainingDays(TrainingDays trainingDays) {
this.trainingDays = trainingDays;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
Always try to apply mappings after declaring all the columns.
I got the Solution of this issue,
in TrainingTime Pojo class i have created one variable named "Desc", and i found that this keyword is already reserved, so can name any variable like this.

#OrderBy not working properly in JPA

How does #OrderBy work?
It is not working here in the following code:
Employee.java
package com.semanticbits.pojo;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
#Entity
public class Employee {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int employeeId;
private String name;
private double salary;
#OneToMany(cascade=CascadeType.ALL)
#JoinColumn(name="EMP_ID")
#OrderBy("city DESC")
private List<Address> address;
//setters and getters
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public List<Address> getAddress() {
return address;
}
public void setAddress(List<Address> address) {
this.address = address;
}
}
Address.java
package com.semanticbits.pojo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Address {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int addressId;
private String street;
private String city;
private String state;
private int zipCode;
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getZipCode() {
return zipCode;
}
public void setZipCode(int zipCode) {
this.zipCode = zipCode;
}
}
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence 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_1_0.xsd" version="1.0">
<persistence-unit name="orderbyannotationdemo" transaction-type="RESOURCE_LOCAL">
<provider></provider>
<class>com.semanticbits.pojo.Employee</class>
<class>com.semanticbits.pojo.Address</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/shoaib"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<property name="eclipselink.logging.level" value="FINE"/>
<property name="eclipselink.ddl-generation" value="create-tables"/>
</properties>
</persistence-unit>
</persistence>
This is the test class......check out the city name and it is not storing address values in order in descending order in the ADDRESS table
JPAOrderByAnnotationTest
package com.semanticbits.test;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import com.semanticbits.pojo.Address;
import com.semanticbits.pojo.Employee;
public class JPAOrderByAnnotationTest {
/**
* #param args
*/
public static void main(String[] args) {
EntityManagerFactory factory=Persistence.createEntityManagerFactory("orderbyannotationdemo");
EntityManager manager=factory.createEntityManager();
Employee employee=new Employee();
employee.setName("Shoaib");
employee.setSalary(1452365);
Address addressOffice=new Address();
addressOffice.setCity("Hyderabad");
addressOffice.setStreet("Gachibowli");
addressOffice.setState("AP");
addressOffice.setZipCode(500016);
Address addressHome=new Address();
addressHome.setCity("Noida");
addressHome.setStreet("Chandai Chowk");
addressHome.setState("UP");
addressHome.setZipCode(415608);
Address addressCollege=new Address();
addressCollege.setCity("Antartica");
addressCollege.setState("Canada");
addressCollege.setStreet("New York");
addressCollege.setZipCode(402103);
List<Address> addresses=new ArrayList<Address>();
addresses.add(addressHome);
addresses.add(addressOffice);
addresses.add(addressCollege);
employee.setAddress(addresses);
manager.getTransaction().begin();
manager.persist(employee);
manager.getTransaction().commit();
manager.close();
}
}
I think you're misunderstanding what the #Orderby annotation actually does. According to the javadoc:
Specifies the ordering of the elements of a collection valued
association or element collection at the point when the association or
collection is retrieved.
[emphasis added] The annotation does not dictate insertion order. Continuing with your example, if you were to fetch an Employee:
Employee employee = manager.find(Employee.class, employeeId);
List<Address> addresses = employee.getAddress();
Then addresses would be sorted by city in descending order.
according to the spec you would have to use:
#OrderBy("address.city DESC")

My EJB throws a transaction required exception although another EJB setup in the same way with same persistence unit throws no excpetion

First here is my entire EJB file:
package enkia.pulse.indexing.beans;
import enkia.pulse.core.Category;
import enkia.pulse.core.Product;
import enkia.pulse.core.Review;
import enkia.pulse.core.Twitter;
import enkia.utils.HarvestingConstants;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.ejb.TimedObject;
import javax.ejb.Timer;
import javax.ejb.TimerService;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.UserTransaction;
import twitter4j.FilterQuery;
import twitter4j.Status;
import twitter4j.StatusDeletionNotice;
import twitter4j.StatusListener;
import twitter4j.TwitterException;
import twitter4j.TwitterStream;
import twitter4j.TwitterStreamFactory;
import twitter4j.auth.AccessToken;
/**
*
* #author joshua
*/
#Stateless
public class TwitterBean implements TwitterBeanLocal,
TimedObject {
List<String> _twitterTopics;
Map<String,Integer> _tagCatRel;
TimerService _timerService;
Timer _timer;
/** The session context needed to create the timer */
#Resource
private SessionContext _sc;
#PersistenceContext(unitName=HarvestingConstants.PERSISTENCE_UNIT)
EntityManager _entityManager;
/** A logging object for formatted output to the server log. */
private Logger _logger;
private int errors;
/**
* Constructs the logger
*/
public TwitterBean(){
_logger = Logger.getLogger(this.getClass().getName());
_logger.log(Level.INFO,"Instantiating Twitter Bean");
}
/**
* Attempts to retrieve the configuration object. Creates the harvester
* with the configuration and then sets a timer to run the harvester
* periodically
*/
public void initialize() {
_logger.log(Level.INFO,"Initializing Twitter bean.");
_twitterTopics = new LinkedList<String>();
_tagCatRel = new HashMap<String,Integer>();
_timerService = _sc.getTimerService();
_timer = _timerService.createTimer(0,1000*60*60,null); //restart every hour
_logger.log(Level.INFO,"Starting Twitter timer");
}
public void ejbTimeout(Timer timer) {
_logger.log(Level.INFO,"Running Twitter timer");
findTopics();
try {
setupStream();
} catch (TwitterException ex) {
Logger.getLogger(TwitterBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void setupStream() throws TwitterException{
StatusListener listener = new StatusListener(){
#Override
public void onStatus(Status status) {
insertStatus(status);
}
#Override
public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
//DO nothing
}
#Override
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
_logger.log(Level.INFO,"Track limitation notice: "+numberOfLimitedStatuses);
}
#Override
public void onScrubGeo(long l, long l1) {
_logger.log(Level.INFO,"Scrub GEO");
}
#Override
public void onException(Exception ex) {
ex.printStackTrace();
}
};
TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
twitterStream.setOAuthConsumer("secret", "secret");
twitterStream.setOAuthAccessToken(new AccessToken("secret","secret"));
FilterQuery query = new FilterQuery();
query = query.track(_twitterTopics.toArray(new String[_twitterTopics.size()]));
twitterStream.addListener(listener);
twitterStream.filter(query);
}
public void insertStatus(Status status){
String foundTag="";
for(String tag : _tagCatRel.keySet()){
if(status.getText().toLowerCase().contains(tag.toLowerCase())){
//found
foundTag=tag;
break;
}
}
if(foundTag.equals("")){
return;
}
Integer category = _tagCatRel.get(foundTag);
Query q=_entityManager.createNamedQuery("Category.findByCategoryId");
q.setParameter("categoryId",category);
Category c = (Category) q.getSingleResult();
Product p = new Product(c);
_entityManager.persist(p);
_entityManager.merge(p);
Review r = new Review();
r.setReview(status.getText());
r.setUrl("http://www.twitter.com/"+status.getUser().getScreenName()+"/statuses/"+status.getId());
r.setProcessed(0);
r.setDateCreated(status.getCreatedAt().getTime());
p.getPartNumber();
r.setProductId(p.getProductId());
_entityManager.persist(r);
_logger.log(Level.INFO,"Added tweet:" + r.getReview());
}
private void findTopics() {
_twitterTopics = new LinkedList<String>();
Query twitterQuery=_entityManager.createNamedQuery("Twitter.findAll");
String all="";
for(Object t: twitterQuery.getResultList()){
Twitter twitter=(Twitter) t;
for(String tag : twitter.getTags().split(" ")){
_twitterTopics.add(tag);
all+=tag+", ";
Integer test = twitter.getCategoryId();
_tagCatRel.put(tag,twitter.getCategoryId());
}
}
_logger.log(Level.INFO,"Tracking: "+all);
}
}
And my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.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_1_0.xsd">
<persistence-unit name="PulsePU" transaction-type="JTA">
<jta-data-source>pulseEJB</jta-data-source>
<class>enkia.pulse.core.Category</class>
<class>enkia.pulse.core.Department</class>
<class>enkia.pulse.core.Feature</class>
<class>enkia.pulse.core.Product</class>
<class>enkia.pulse.core.Review</class>
<class>enkia.pulse.core.ReviewSnippet</class>
<class>enkia.pulse.core.Sentiment</class>
<class>enkia.pulse.core.SentimentReview</class>
<class>enkia.pulse.core.Twitter</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties/>
</persistence-unit>
</persistence>
Lastly is my sun-resource.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 9.0 Resource Definitions //EN" "http://www.sun.com/software/appserver/dtds/sun-resources_1_3.dtd">
<resources>
<jdbc-resource enabled="true" jndi-name="pulseEJB" object-type="user" pool-name="mysqlPool"/>
<jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="mysqlPool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.DataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
<property name="serverName" value="endpoint"/>
<property name="portNumber" value="3306"/>
<property name="databaseName" value="pulse"/>
<property name="User" value="user"/>
<property name="Password" value="password"/>
<property name="URL" value="jdbc:mysql://endpoint/pulse"/>
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
I'm using Netbeans.
I instantiate my EJB in a webproject. I have another EJB setup the same that I instantiate there that works fine with container managed transaction. I also tried just saying "screw it" and used UserTransaction but that had problems with the merge and ended up with numerous unexpected problems, NPE on p right after "_entityManager.persist(p); _entityManager.merge(p);"
Any suggestions on where to look for differences between the two EJBs is appreciated as I'm out of ideas.
I also noticed netbeans is generating sources for two of my entity classes in the problematic EJB labeled "ap-source-output" but doesn't in the working EJB.
Generated Code I don't understand why being generated below:
package enkia.pulse.core;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
#Generated(value="EclipseLink-2.2.0.v20110202-r8913", date="2012-08-08T23:09:05")
#StaticMetamodel(Twitter.class)
public class Twitter_ {
public static volatile SingularAttribute<Twitter, Integer> id;
public static volatile SingularAttribute<Twitter, String> tags;
public static volatile SingularAttribute<Twitter, Integer> categoryId;
public static volatile SingularAttribute<Twitter, Long> lastStatus;
}
And
package enkia.pulse.core;
import enkia.pulse.core.Category;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
#Generated(value="EclipseLink-2.2.0.v20110202-r8913", date="2012-08-08T23:41:31")
#StaticMetamodel(Product.class)
public class Product_ {
public static volatile SingularAttribute<Product, String> productBrand;
public static volatile SingularAttribute<Product, Category> category;
public static volatile SingularAttribute<Product, String> model;
public static volatile SingularAttribute<Product, byte[]> image;
public static volatile SingularAttribute<Product, String> productName;
public static volatile SingularAttribute<Product, String> imageURL;
public static volatile SingularAttribute<Product, String> specifications;
public static volatile SingularAttribute<Product, Integer> productId;
public static volatile SingularAttribute<Product, String> partNumber;
}
While I'm at it I'll show the entity file too:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package enkia.pulse.core;
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.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
*
* #author fbarrow
*/
#Entity
#Table(name = "twitter")
#NamedQueries({
#NamedQuery(name = "Twitter.findAll", query = "SELECT t FROM Twitter t"),
#NamedQuery(name = "Twitter.findById", query = "SELECT t FROM Twitter t WHERE t.id = :id"),
#NamedQuery(name = "Twitter.findByCategoryId", query = "SELECT t FROM Twitter t WHERE t.categoryId = :categoryId"),
#NamedQuery(name = "Twitter.findByTags", query = "SELECT t FROM Twitter t WHERE t.tags = :tags"),
#NamedQuery(name = "Twitter.findByLastStatus", query = "SELECT t FROM Twitter t WHERE t.lastStatus = :lastStatus")})
public class Twitter implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Integer id;
#Column(name = "categoryId")
private Integer categoryId;
#Column(name = "tags")
private String tags;
#Column(name = "lastStatus")
private Long lastStatus;
public Twitter() {
}
public Twitter(Integer id) {
this.id = id;
}
public Twitter(Integer id, Integer categoryId, String tags, Long lastStatus) {
this.id = id;
this.categoryId = categoryId;
this.tags = tags;
this.lastStatus = lastStatus;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public Long getLastStatus() {
return lastStatus;
}
public void setLastStatus(Long lastStatus) {
this.lastStatus = lastStatus;
}
#Override
public int hashCode() {
Integer 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 Twitter)) {
return false;
}
Twitter other = (Twitter) 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 "enkia.pulse.core.Twitter[ id=" + id + " ]";
}
}
Error:
SEVERE: javax.persistence.TransactionRequiredException
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.doTxRequiredCheck(EntityManagerWrapper.java:163)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.doTransactionScopedTxCheck(EntityManagerWrapper.java:145)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.persist(EntityManagerWrapper.java:263)
at enkia.pulse.indexing.beans.TwitterBean.insertStatus(TwitterBean.java:154)
at enkia.pulse.indexing.beans.TwitterBean$1.onStatus(TwitterBean.java:99)
at twitter4j.StatusStreamImpl.onStatus(StatusStreamImpl.java:78)
at twitter4j.AbstractStreamImplementation$1.run(AbstractStreamImplementation.java:107)
at twitter4j.internal.async.ExecuteThread.run(DispatcherImpl.java:114)
Use of Timer to create TwitterStream, running an independent thread?
The timer calls setupStream, which creates a listener, and binds that listener to twitterStream, created via the TwitterStreamFactory. That code isn't shown, however from the context it would appear that the TwitterStream is running code asynchronously:
twitter4j.internal.async.ExecuteThread
is in your stack-trace, below the exception. My bet is you're managing your own threads, which is not running within the container's context - all bets are off for accessing container resources and interacting with the container in this model (which is why Java EE so strongly suggests that you do NOT run your own threading model).
Specifically, that code is NOT running within a container managed transaction.
You might explore having the the Timer Service launch the background task via an MDB, which will run asynchronously from your EJB, in a proper container.

Can't figure it out how to resolve javax.persistence.PersistenceException

We are trying to build a JSF application with JPA. For now, we want to make the login feature, but when we run the application on our glassfish server, there is the exception:
javax.persistence.PersistenceException: No Persistence provider for EntityManager named siteMami
We think the problem is somewhere from persistence.xml, maybe at the provider, please help us. Thanks! Here is the directory structure:
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
version="1.0">
<persistence-unit name="siteMami" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>model.Admin</class>
<class>model.User</class>
<class>model.Client</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost/siteMami" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="" />
</properties>
</persistence-unit>
</persistence>
User.java:
/**
*
*/
package model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
import javax.persistence.Transient;
#Entity
#Table(name = "useri")
#Inheritance(strategy = InheritanceType.JOINED)
public class User implements Serializable
{
#Transient
private static long serialVersionUID = 6837935606727700935L;
#Id
#GeneratedValue
#Column(name = "idUseri")
private long id;
#Column(unique = true)
private String username;
private String password;
/**
* #param id
* #param userName
* #param password
*/
public User(long id, String username, String password)
{
super();
this.id = id;
this.username = username;
this.password = password;
}
/**
* #return the id
*/
public long getId()
{
return id;
}
/**
* #return the userName
*/
public String getUsername()
{
return username;
}
/**
* #return the password
*/
public String getPassword()
{
return password;
}
public void setId(long id)
{
this.id = id;
}
public void setUsername(String userName)
{
this.username = userName;
}
public void setPassword(String password)
{
this.password = password;
}
}
UserManager.java:
package dao;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import model.User;
public class UserManager
{
private EntityManagerFactory factory;
public UserManager()
{
factory = Persistence.createEntityManagerFactory("siteMami");
}
public User getUser(String username, String password)
{
EntityManager entityManager = factory.createEntityManager();
EntityTransaction entityTransaction = entityManager.getTransaction();
entityTransaction.begin();
Query q = entityManager.createQuery("SELECT * FROM User WHERE User.username = '" + username + "' and User.password = '" + password + "'");
entityTransaction.commit();
return (User) q.getSingleResult();
}
}
It just popped out on the screenshot somehow: Your file is named
"persitence.xml" instead of
"persistence.xml".
After i changed the persistence.xml file name, i made a copy of META-INF in src and now it works. We have another exception for now, but we'll see. Thank you for your answer.

Categories