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();
Related
I'm implementing mult-tenancy per schema in my application and I'm having trouble switching the schema.
I'll put the flow step by step:
1 - I make the request to the API, passing X-TENANT-ID in the header
package br.com.braxxy.brxm.server.multtenant.hibernate;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import lombok.extern.slf4j.Slf4j;
#Slf4j
public class TenantInterceptor implements HandlerInterceptor {
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
log.info("TENANT: " + request.getHeader("X-TENANT-ID"));
Optional.ofNullable(request.getHeader("X-TENANT-ID")).map(String::toUpperCase)
.ifPresent(Tenant::setIdentificador);
return true;
}
}
2 - The resolveCurrentTenantIdentifier method of the CurrentTenantIdentifierResolver interface is overridden and returns the data I passed in the X-TENANT-ID.
package br.com.braxxy.brxm.server.multtenant.hibernate;
import org.hibernate.context.spi.CurrentTenantIdentifierResolver;
public class SchemaCurrentTenantIdentifierResolver implements CurrentTenantIdentifierResolver {
#Override
public String resolveCurrentTenantIdentifier() {
System.out.println("resolveCurrentTenantIdentifier : " + Tenant.getIdentificador());
return Tenant.getIdentificador();
}
#Override
public boolean validateExistingCurrentSessions() {
System.out.println("validateExistingCurrentSessions : " + Tenant.getIdentificador());
return false;
}
}
3 - This is the step I'm having trouble with. In theory, hibernate should call the getConnection method passing the tenant, but this method is not called when I make the request and consequently does not change the schema.
package br.com.braxxy.brxm.server.multtenant.hibernate;
import org.hibernate.HibernateException;
import org.hibernate.engine.config.spi.ConfigurationService;
import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider;
import org.hibernate.service.spi.ServiceRegistryAwareService;
import org.hibernate.service.spi.ServiceRegistryImplementor;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
public class SchemaMultiTenantConnectionProvider implements
MultiTenantConnectionProvider, ServiceRegistryAwareService {
/**
*
*/
private static final long serialVersionUID = 1L;
private ConnectionProvider connectionProvider = null;
#Override
public Connection getAnyConnection() throws SQLException {
return connectionProvider.getConnection();
}
#Override
public void releaseAnyConnection(Connection connection) throws SQLException {
connectionProvider.closeConnection(connection);
}
#Override
public Connection getConnection(String tenantIdentifier) throws SQLException {
Connection connection = getAnyConnection();
System.out.println("getConnection :" + tenantIdentifier);
try {
connection.createStatement().execute("SET SCHEMA '" + tenantIdentifier + "'");
} catch (SQLException e) {
throw new HibernateException("Could not change to schema " + tenantIdentifier + ".", e);
}
return connection;
}
#Override
public void releaseConnection(String tenantIdentifier, Connection connection) throws SQLException {
releaseAnyConnection(connection);
}
#Override
public boolean supportsAggressiveRelease() {
return false;
}
#Override
public boolean isUnwrappableAs(Class unwrapType) {
return false;
}
#Override
public <T> T unwrap(Class<T> unwrapType) {
return null;
}
#Override
public void injectServices(ServiceRegistryImplementor serviceRegistry) {
Map<String, String> settings = serviceRegistry
.getService(ConfigurationService.class)
.getSettings();
connectionProvider = new DriverManagerConnectionProviderImpl();
((DriverManagerConnectionProviderImpl) connectionProvider)
.injectServices(serviceRegistry);
((DriverManagerConnectionProviderImpl) connectionProvider)
.configure(settings);
}
}
I've tried to do it in several ways, but I always fall into the same problem. Does anyone know how to solve?
<?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_2.xsd"
version="2.2">
<persistence-unit name="brxTenant">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="javax.persistence.provider" value="org.hibernate.ejb.HibernatePersistence" />
<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="braxxy" />
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />
<property name="hibernate.archive.autodetection" value="class, hbm" />
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.multiTenancy" value="SCHEMA" />
<property name="hibernate.multi_tenant_connection_provider" value="br.com.braxxy.brxm.server.multtenant.hibernate.SchemaMultiTenantConnectionProvider"/>
<property name="hibernate.tenant_identifier_resolver" value="br.com.braxxy.brxm.server.multtenant.hibernate.SchemaCurrentTenantIdentifierResolver"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
</properties>
</persistence-unit>
</persistence>
After a hard day's work, I managed to solve my problem.
It had nothing to do with the Multitenancy implementation itself.
It was necessary for me to add #Transactional in the controller and it worked.
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.
getting this error in eclipselink JPA example. I am trying to set up a simple JPA class. It complains about the xml document not being well formed, but I don't see any problems. please let me know of any pointers. thanks!
Main class is:
package de.vogella.jpa.simple.main;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import de.vogella.jpa.simple.model.Todo;
public class Main {
private static final String PERSISTENCE_UNIT_NAME = "todos";
private static EntityManagerFactory factory;
public static void main(String[] args) {
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factory.createEntityManager();
// read the existing entries and write to console
Query q = em.createQuery("select t from Todo t");
List<Todo> todoList = q.getResultList();
for (Todo todo : todoList) {
System.out.println(todo);
}
System.out.println("Size: " + todoList.size());
// create new todo
em.getTransaction().begin();
Todo todo = new Todo();
todo.setSummary("This is a test");
todo.setDescription("This is a test");
em.persist(todo);
em.getTransaction().commit();
em.close();
}
}
here is 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="todos" transaction-type="RESOURCE_LOCAL">
<class>de.vogella.jpa.simple.model.Todo</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:derby:/home/vogella/databases/simpleDb;create=true" />
<property name="javax.persistence.jdbc.user" value="test" />
<property name="javax.persistence.jdbc.password" value="test" />
<!-- EclipseLink should create the database schema automatically -->
<property name="eclipselink.ddl-generation" value="create-tables" />
<property name="eclipselink.ddl-generation.output-mode"
value="database" />
</properties>
</persistence-unit>
</persistence>
The error is the following:
Exception in thread "main" Local Exception Stack:
Exception [EclipseLink-30009] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while trying to load persistence unit at url: file:/C:/paul/oneView/java/de.vogella.jpa.simple/build/eclipse/
Internal Exception: Exception [EclipseLink-30004] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while processing persistence.xml from URL: file:/C:/paul/oneView/java/de.vogella.jpa.simple/build/eclipse/
Internal Exception:
(1. The markup in the document preceding the root element must be well-formed.)
at org.eclipse.persistence.exceptions.PersistenceUnitLoadingException.exceptionLoadingFromUrl(PersistenceUnitLoadingException.java:100)
at org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor.processPersistenceArchive(PersistenceUnitProcessor.java:597)
at org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor.getPersistenceUnits(PersistenceUnitProcessor.java:481)
at org.eclipse.persistence.internal.jpa.deployment.JPAInitializer.findPersistenceUnitInfoInArchive(JPAInitializer.java:172)
at org.eclipse.persistence.internal.jpa.deployment.JPAInitializer.findPersistenceUnitInfoInArchives(JPAInitializer.java:154)
at org.eclipse.persistence.internal.jpa.deployment.JPAInitializer.findPersistenceUnitInfo(JPAInitializer.java:135)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactory(PersistenceProvider.java:177)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at de.vogella.jpa.simple.main.Main.main(Main.java:17)
I receive the following error in my standalone java application:
Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named DataSourcePostgres
Here's my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" 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://www.oracle.com/webfolder/technetwork/jsc/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="DataSourcePostgres">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>Denarnica</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.ProgressDialect"/>
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/>
<!--<property name="hibernate.show_sql" value="true"/>-->
<property name="hibernate.connection.username" value="*****"/>
<property name="hibernate.connection.password" value="*******"/>
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/postgres"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
and here's my Server.java:
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.List;
public class Server {
private static final String PERSISTENCE_UNIT_NAME = "DataSourcePostgres";
private static EntityManagerFactory factory;
public static void main(String[] args) {
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factory.createEntityManager();
// Read the existing entries and write to console
Query q = em.createQuery("select d from Data d");
List<Denarnica> dataList= q.getResultList();
System.out.println("Size: " + dataList.size());
}
}
I've been looking at some similar problems, but the solutions people suggested to them don't seem to help me. Any advice?
My problem was I didn't put the persistence.xml into a META-INF folder. After I fixed that everything worked.
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.