JPAContainer in a generic class? - java

I'm trying create a generic class for automate the creation of jpacontainer in my project but doesn't work and returns some errors. The errors refer No EntityProvider has been set.
I'm trying this.
/** class init jpacontainer */
public class PersistJPAContainer<T> extends JPAContainer<T>{
private static final long serialVersionUID = 1L;
private static final String PERSISTENCE_UNITNAME = "ps_unitname";
public PersistJPAContainer(Class<T> entityClass) {
super(entityClass);
JPAContainer<?> container = JPAContainerFactory.make(entityClass, PERSISTENCE_UNITNAME);
}
}
/** my app UI */
public class AcademiaonlineUI extends UI {
private final JPAContainer<Empresa> datasource = new PersistJPAContainer<Empresa>(Empresa.class);
#Override
protected void init(VaadinRequest request) {
Table tabela = new Table("Empresa", datasource);
VerticalLayout vLayout = new VerticalLayout();
vLayout.addComponent(tabela);
setContent(vLayout);
}
}
/** errors */
Mar 17, 2014 11:14:30 AM com.vaadin.server.DefaultErrorHandler doDefault
SEVERE:
java.lang.IllegalStateException: No EntityProvider has been set
at com.vaadin.addon.jpacontainer.JPAContainer.doGetEntityProvider(JPAContainer.java:313)
at com.vaadin.addon.jpacontainer.JPAContainer.size(JPAContainer.java:912)
at com.vaadin.ui.AbstractSelect.size(AbstractSelect.java:762)
at com.vaadin.ui.Table.refreshRenderedCells(Table.java:1654)
at com.vaadin.ui.Table.attach(Table.java:4171)
at com.vaadin.server.AbstractClientConnector.attach(AbstractClientConnector.java:583)
at com.vaadin.ui.AbstractComponent.attach(AbstractComponent.java:572)
at com.vaadin.ui.AbstractComponent.setParent(AbstractComponent.java:479)
at com.vaadin.ui.AbstractSingleComponentContainer.setContent(AbstractSingleComponentContainer.java:137)
at com.vaadin.ui.UI.setContent(UI.java:1162)
at br.com.academiaonline.AcademiaonlineUI.init(AcademiaonlineUI.java:24)
at com.vaadin.ui.UI.doInit(UI.java:614)
at com.vaadin.server.communication.UIInitHandler.getBrowserDetailsUI(UIInitHandler.java:223)
at com.vaadin.server.communication.UIInitHandler.synchronizedHandleRequest(UIInitHandler.java:73)
at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:37)
at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1382)
at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:238)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:724)
//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="ps_unitname" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>br.com.academiaonline.beans.Empresa</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:h2:~/AODB"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value="master"/>
<!-- Cria a base de dados automaticamente -->
<property name="eclipselink.ddl-generation" value="create-or-extend-tables" />
<property name="eclipselink.ddl-generation.output-mode" value="database" />
<!-- Exibe log de erros no console do eclipse -->
<property name="eclipselink.logging.level" value="FINE"/>
</properties>
</persistence-unit>
</persistence>
Any idea ?

Try some thing like this in your Constructor
public class CustomJPA extends JPAContainer {
private static final long serialVersionUID = -1752491307148335890L;
private static final String PU_UNIT="ps_unitname";
public CustomJPA(Class<T> entityClass, String persitenceUnitName) {
super(entityClass);
EntityManager entityManager = JPAContainerFactory.createEntityManagerForPersistenceUnit(persitenceUnitName);
setEntityProvider(new CachingMutableLocalEntityProvider<T>(entityClass,entityManager));
}
public CustomJPA(Class<T> entityClass) {
super(entityClass);
EntityManager entityManager =JPAContainerFactory.createEntityManagerForPersistenceUnit(PU_UNIT);
setEntityProvider(new CachingMutableLocalEntityProvider<T>(entityClass,entityManager));
}
}
Where ever I have to initalise my Container, I do it some thing like this
JPAContainer<Bean> myBean= new CustomJPA<Bean>(Bean.class);
Hope this helps. I feel that you are writing some redundant code.
NOTE:
I have not tested this snippet of code.
Try to use appropriate class as your EnityProvider, I used the
default one in this example
BTW, is this what you are expecting??

now works...after some tests finally works.
I did so.
public class PersistJPAContainer<T> extends JPAContainer<T>{
private static final long serialVersionUID = 1L;
private static final String PERSISTENCE_UNITNAME = "ps_unitname";
public PersistJPAContainer(Class<T> entityClass) {
super(entityClass);
EntityManager em = JPAContainerFactory.createEntityManagerForPersistenceUnit(PERSISTENCE_UNITNAME);
setEntityProvider(new CachingMutableLocalEntityProvider<T>(entityClass, em));
}
}
public class AcademiaonlineUI extends UI {
private final PersistJPAContainer<Empresa> datasource = new PersistJPAContainer<Empresa>(Empresa.class);
And works !

Related

Getting access to registred EntityManager in a Runnable

I have a working JSF application with JPA. The JTA-DataSource is wildfly-managed.
Now I have to run some database operations periodically. As mentioned here ( SO: How to run a background task in a servlet based web application? ) I created the two classes:
#WebListener
public class Scheduler implements ServletContextListener {
private ScheduledExecutorService scheduler;
#SuppressWarnings("deprecation")
#Override
public void contextInitialized(ServletContextEvent event) {
Calendar c = new GregorianCalendar();
Date d = c.getTime();
int stm = 60 - d.getSeconds();
int mth = 60 - d.getMinutes();
scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new TestRunner(), stm, 60, TimeUnit.SECONDS);
}
#Override
public void contextDestroyed(ServletContextEvent event) {
scheduler.shutdownNow();
}
}
public class TestRunner implements Runnable {
private EntityManager em;
public TestRunner() {
}
#Override
public void run() {
this.Test();
}
public void Test() {
System.out.println("Test executed...");
if (this.em != null) {
System.out.println(em.find(Ship.class, 2).getName());
System.out.println(em.find(Commodity.class, 1).getName());
} else {
System.out.println("EntityManager is null");
}
}
}
The best whould be to access the registered Persistence Unit.
I tried to get the EM via #PersistenceContext(unitName = "PU"), tried to register the Persistence in the web.xml to get it via JNDI, but had no luck.
Where is my mistake?
Found a solution for me: define a second persistence content.
First, my persistence unit:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
version="2.1">
<persistence-unit name="PU" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>java:jboss/datasources/mysqldb</jta-data-source>
<class>model.Commodity</class>
<class>...</class>
<properties>
<!-- <property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform"/> -->
<!-- <property name="hibernate.hbm2ddl.auto" value="update" /> -->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<!-- <property name="hibernate.show_sql" value="true" /> -->
<property name="hibernate.enable_lazy_load_no_trans" value="true" />
</properties>
</persistence-unit>
<persistence-unit name="RLPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>java:jboss/datasources/mysqldb</jta-data-source>
<class>model.Commodity</class>
<class>...</class>
<properties>
<!-- <property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform"/> -->
<!-- <property name="hibernate.hbm2ddl.auto" value="update" /> -->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<!-- <property name="hibernate.show_sql" value="true" /> -->
<property name="hibernate.enable_lazy_load_no_trans" value="true" />
</properties>
</persistence-unit>
</persistence>
In JSF I use the EntityManager within the CDI-Beans via
#PersistenceContext(unitName = "PU", type = PersistenceContextType.EXTENDED)
private EntityManager em;
Within the CronJob/Scheduler/Runnable I create the EntityManager via
public TestRunner() {
this.em = Persistence.createEntityManagerFactory("RLPU").createEntityManager();
}
So can I use the Persistence Context both in a container managed class and in unmanaged classes.

Provider org.hibernate.envers.event.EnversIntegrator not a subtype error in CDI+JPA2.1+Restful

I am trying to call JPA from a rest web service. but it throws me
org.hibernate.integrator.spi.Integrator: Provider org.hibernate.envers.event.EnversIntegrator not a subtype at org.apache.cxf.service.invoker.AbstractInvoker.createFault(AbstractInvoker.java:170) at
org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:136) at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:204) at
org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:101) at
org.apache.openejb.server.cxf.rs.AutoJAXRSInvoker.invoke(AutoJAXRSInvoker.java:68) at org.apache.cxf.interceptor.ServiceInvokerInterceptor
I have used maven 4, JPA 2.1, CDI.
My code:
JPA part:
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("defaultMainUnit", null);
EntityManager entityManager = entityManagerFactory.createEntityManager();
Persistence.generateSchema("defaultMainUnit", null);
Query master Query = entityManager
.createNamedQuery("master.findAll");
List<Master > masterList = masterQuery.getResultList();
for(Master master : masterList){
System.out.println("Master id: "+master .getMaster TrackingId());
}
entityManager.clear();
entityManager.close();
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="defaultMainUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>core.Master</class>
<class>core.Child</class>
<properties>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver" />
<property name="hibernate.connection.url" value="jdbc:hsqldb:mem:defaultDB" />
<property name="hibernate.connection.username" value="sa" />
<property name="hibernate.connection.password" value="" />
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="hibernate.connection.release_mode" value="after_statement"/>
<!-- insert data using sql file -->
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
<property name="javax.persistence.schema-generation.create-source" value="metadata"/>
<property name="javax.persistence.schema-generation.drop-source" value="metadata"/>
<property name="javax.persistence.sql-load-script-source" value="mcb-test-import.sql"/>
</properties>
</persistence-unit>
Restservice:
package restcdi.rest;
#Path("/")
public class GreetREST {
#Inject
private EnglishGreet greet;
#GET
#Path("/greet")
#Produces(MediaType.TEXT_PLAIN)
public String greet() {
return greet.greet();
}
#GET
#Path("/master")
#Produces(MediaType.APPLICATION_JSON)
public List master() throws FileNotFoundException, IOException{
CheckJPAProperties check = new CheckJPAProperties();
List masterList = check.runMe();
return masterList;
}
}
in the above code, runMe() returns all the masters in database using JPA code above. when i run the JPA code without a rest service in main it runs fine and returns everything. I am not sure what I am missing. I tried including the hibernate-envers dependency in pom.xml but it still throws the same error.
please help.
ps: just in case this is needed i am including my applicationConfig
package restcdi.rest;
import java.util.Set;
import javax.ws.rs.core.Application;
#javax.ws.rs.ApplicationPath("rest")
public class ApplicationConfig extends Application {
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new java.util.HashSet<>();
resources.add(GreetREST.class);
return resources;
}
}

Transaction is not active using OpenJPA

i have a frustrating problem with my servlet. This is very basic, i'm supposed to add a blog entry to my database table which has 3 columns (id, tittel(title), main(mainbody)). I can load from my database and display in my jsp file. However i can't persist the data to the database and i cant figure out why.
I use postgres as a database.
This is my "saveBlog"-method:
public void lagreBlogg(Blogg b){
EntityManager em = Persistence.createEntityManagerFactory("kimsBlogg").createEntityManager();
EntityTransaction transaction = em.getTransaction();
try {
transaction.begin();
em.persist(b);
transaction.commit();
} catch (Exception e) {
transaction.rollback();
} finally {
em.close();
}
}
}
This is my entity class:
#Entity
#Table(schema = "blogg", name = "blogg")
public class Blogg {
#Id
#GeneratedValue
private int id;
private String tittel;
private String main;
public Blogg() {
}
public Blogg(String tittel, String main){
this.tittel= tittel;
this.main = main;
}
public String getTittel() {
return tittel;
}
public void setTittel(String tittel) {
this.tittel = tittel;
}
public String getMain() {
return main;
}
public void setMain(String main) {
this.main = main;
}
}
My persistence.xml
<?xml version="1.0" encoding="UTF-8" ?>
<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"
version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="kimsBlogg">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl
</provider>
<class>no.kim.model.Blogg</class>
<properties>
<property name="javax.persistence.jdbc.logging.level" value="INFO" />
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/postgres" />
<property name="javax.persistence.jdbc.user" value="postgres" />
<property name="javax.persistence.jdbc.password" value="krheggen" />
<property name="openjpa.RuntimeUnenhancedClasses" value="supported" />
</properties>
</persistence-unit>
This is the error i get:
HTTP Status 500 - Can only perform operation while a transaction is active.
type Exception report
message Can only perform operation while a transaction is active.
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.apache.openjpa.persistence.InvalidStateException: Can only perform operation while a transaction is active.
org.apache.openjpa.kernel.BrokerImpl.assertTransactionOperation(BrokerImpl.java:4732)
org.apache.openjpa.kernel.BrokerImpl.rollback(BrokerImpl.java:1543)
org.apache.openjpa.kernel.DelegatingBroker.rollback(DelegatingBroker.java:940)
org.apache.openjpa.persistence.EntityManagerImpl.rollback(EntityManagerImpl.java:598)
no.kim.helpers.BloggDAO.lagreBlogg(BloggDAO.java:37)
no.kim.Controller.BloggServlet.doPost(BloggServlet.java:33)
javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
StackTrace
Caused by: org.apache.openjpa.persistence.PersistenceException: ERROR: relation "blogg.openjpa_sequence_table" does not exist
Position: 28 {prepstmnt 166406485 SELECT SEQUENCE_VALUE FROM blogg.OPENJPA_SEQUENCE_TABLE WHERE ID = ? FOR UPDATE} [code=0, state=42P01]
at org.apache.openjpa.jdbc.sql.DBDictionary.narrow(DBDictionary.java:5001)
at org.apache.openjpa.jdbc.sql.DBDictionary.newStoreException(DBDictionary.java:4961)
at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:133)
at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:107)
at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:59)
at org.apache.openjpa.jdbc.kernel.AbstractJDBCSeq.next(AbstractJDBCSeq.java:63)
at org.apache.openjpa.util.ImplHelper.generateValue(ImplHelper.java:159)
at org.apache.openjpa.util.ImplHelper.generateFieldValue(ImplHelper.java:143)
at org.apache.openjpa.jdbc.kernel.JDBCStoreManager.assignField(JDBCStoreManager.java:774)
at org.apache.openjpa.util.ApplicationIds.assign(ApplicationIds.java:492)
at org.apache.openjpa.util.ApplicationIds.assign(ApplicationIds.java:468)
at org.apache.openjpa.jdbc.kernel.JDBCStoreManager.assignObjectId(JDBCStoreManager.java:758)
at org.apache.openjpa.kernel.DelegatingStoreManager.assignObjectId(DelegatingStoreManager.java:135)
at org.apache.openjpa.kernel.StateManagerImpl.assignObjectId(StateManagerImpl.java:595)
at org.apache.openjpa.kernel.StateManagerImpl.preFlush(StateManagerImpl.java:3051)
at org.apache.openjpa.kernel.PNewState.beforeFlush(PNewState.java:44)
at org.apache.openjpa.kernel.StateManagerImpl.beforeFlush(StateManagerImpl.java:1072)
at org.apache.openjpa.kernel.BrokerImpl.flush(BrokerImpl.java:2143)
at org.apache.openjpa.kernel.BrokerImpl.flushSafe(BrokerImpl.java:2103)
at org.apache.openjpa.kernel.BrokerImpl.beforeCompletion(BrokerImpl.java:2021)
at org.apache.openjpa.kernel.LocalManagedRuntime.commit(LocalManagedRuntime.java:81)
at org.apache.openjpa.kernel.BrokerImpl.commit(BrokerImpl.java:1526)
at org.apache.openjpa.kernel.DelegatingBroker.commit(DelegatingBroker.java:932)
at org.apache.openjpa.persistence.EntityManagerImpl.commit(EntityManagerImpl.java:569)
relation "blogg.openjpa_sequence_table" does not exist
This seems to be straightforward, just create a sequence for the table blogg, more information here.
The problem is your " transaction.rollback();" in the catch method. if commit fails with an exception the connection is not longer active.

JPA/HSQLDB Persistence class not found error

I'm pretty new to JPA and HSQLDB, and I'm havin a weird error when I'm trying to create my EntityManagerFactory. Its a Web Dynamic project in Eclipse (with Tomcat 6.0 as web server) and I imported all the libraries in the the WEB-INF/lib. I'm trying to create the Entity manager Factory in a servlet but in just gives me a class not found exception on the line
emf = Persistence.createEntityManagerFactory("manager1");
Here is the code I used in my servlet:
package view;
import java.io.IOException;
import javax.persistence.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.ThemeLivre;
public class AjouterTheme extends HttpServlet {
//private static final long serialVersionUID = 1L;
#PersistenceUnit(unitName ="DB")
private EntityManagerFactory emf;
public AjouterTheme() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
emf = Persistence.createEntityManagerFactory("DB");
EntityManager em = emf.createEntityManager();
String nomTheme = request.getParameter("nomtheme");
String descTheme = request.getParameter("desctheme");
EntityTransaction tx = em.getTransaction();
tx.begin();
ThemeLivre thml = new ThemeLivre(nomTheme, descTheme);
em.persist(thml);
tx.commit();
}
}
Here is my persistence.xml
<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="DB" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/DefaultDS</jta-data-source>
<class>model.ThemeLivre</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.connection.url" value="jdbc:hsqldb:hsql://localhost/"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
Please tell me what I did wrong, or if there is something I can do.
Thank you
In your servlet code you used
#PersistenceUnit(unitName ="DB")
private EntityManagerFactory emf;
but you declare
<persistence-unit name="manager1" transaction-type="RESOURCE_LOCAL">
change either the one or the other persistence unit name.
Following your input above
Try to add the hibernate persistence provider lib. You add only the specification (API). The implementation itself (hibernate) is needed, to create an Entity Manager.

"org.apache.openjpa.persistence.PersistenceException: null" error

I've been trying to make a simple class in Java run with JPA to no avail. Help?
The title is the error I'm getting.
I've been trying to make a simple class in Java run with JPA to no avail. Help?
The title is the error I'm getting.
My persistence.xml:
<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="geronimo" transaction-type="RESOURCE_LOCAL">
<provider>
org.apache.openjpa.persistence.PersistenceProviderImpl
</provider>
<class>label.entities.Discography</class>
<properties>
<property name="openjpa.ConnectionURL" value="jdbc:sqlite:C:\\sqlitedb\\repo.db" />
<property name="openjpa.ConnectionDriverName" value="org.sqlite.JDBC" />
<property name="openjpa.ConnectionUserName" value="" />
<property name="openjpa.ConnectionPassword" value="" />
<property name="openjpa.Log" value="SQL=TRACE" />
</properties>
</persistence-unit>
My JPA class:
package label.implementations;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import label.entities.Discography;
public class Disconfigurator {
public static void main(String[] args) {
String persistenceUnit = "geronimo";
EntityManagerFactory eFactory = Persistence.createEntityManagerFactory(persistenceUnit);
EntityManager eManager = eFactory.createEntityManager();
EntityTransaction eTransaction = eManager.getTransaction();
eTransaction.begin();
Discography discography = new Discography();
discography.setArtist("Kings Of Leon");
discography.setSong("Radioactive");
eManager.persist(discography);
eTransaction.commit();
eManager.close();
eFactory.close();
}
}
My Entity class:
package label.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
#Entity(name="discography")
public class Discography {
#Column(name="artist",length=1000,nullable=true)
String artist;
#Column(name="song",length=1000,nullable=true)
String song;
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public String getSong() {
return song;
}
public void setSong(String song) {
this.song = song;
}
}
The error trace:
31 geronimo INFO [main] openjpa.Runtime - Starting OpenJPA 1.2.1
Exception in thread "main" <openjpa-1.2.1-r752877:753278 nonfatal general error> org.apache.openjpa.persistence.PersistenceException: null
at org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBrokerFactory.java:196)
at org.apache.openjpa.kernel.DelegatingBrokerFactory.newBroker(DelegatingBrokerFactory.java:142)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:192)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:145)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:56)
at label.implementations.Disconfigurator.main(Disconfigurator.java:16)
Caused by: java.lang.NullPointerException
at org.sqlite.JDBC.connect(JDBC.java:63)
at org.apache.openjpa.jdbc.schema.SimpleDriverDataSource.getConnection(SimpleDriverDataSource.java:81)
at org.apache.openjpa.jdbc.schema.SimpleDriverDataSource.getConnection(SimpleDriverDataSource.java:60)
at org.apache.openjpa.lib.jdbc.DelegatingDataSource.getConnection(DelegatingDataSource.java:106)
at org.apache.openjpa.lib.jdbc.DecoratingDataSource.getConnection(DecoratingDataSource.java:87)
at org.apache.openjpa.jdbc.sql.DBDictionaryFactory.newDBDictionary(DBDictionaryFactory.java:91)
at org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl.getDBDictionaryInstance(JDBCConfigurationImpl.java:562)
at org.apache.openjpa.jdbc.meta.MappingRepository.endConfiguration(MappingRepository.java:1265)
at org.apache.openjpa.lib.conf.Configurations.configureInstance(Configurations.java:505)
at org.apache.openjpa.lib.conf.Configurations.configureInstance(Configurations.java:430)
at org.apache.openjpa.lib.conf.PluginValue.instantiate(PluginValue.java:103)
at org.apache.openjpa.conf.MetaDataRepositoryValue.instantiate(MetaDataRepositoryValue.java:68)
at org.apache.openjpa.lib.conf.ObjectValue.instantiate(ObjectValue.java:83)
at org.apache.openjpa.conf.OpenJPAConfigurationImpl.newMetaDataRepositoryInstance(OpenJPAConfigurationImpl.java:863)
at org.apache.openjpa.conf.OpenJPAConfigurationImpl.getMetaDataRepositoryInstance(OpenJPAConfigurationImpl.java:854)
at org.apache.openjpa.kernel.AbstractBrokerFactory.makeReadOnly(AbstractBrokerFactory.java:638)
at org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBrokerFactory.java:183)
... 5 more
You're trying to persist the Transaction and not your entity object.
This is what your code SHOULD look like --
EntityManagerFactory eFactory = Persistence.createEntityManagerFactory("geronimo");
EntityManager eManager = eFactory.createEntityManager();
EntityTransaction eTransaction = eManager.getTransaction();
//eManager.persist(eTransaction); <--- DO NOT DO THIS
eTransaction.begin();
Discography discography = new Discography();
discography.setArtist("Kings Of Leon");
discography.setSong("Radioactive");
eManager.persist(discography); // DO THIS INSTEAD. PERSIST THE ENTITY
eTransaction.commit();
eManager.close();
eFactory.close();

Categories