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)
Related
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;
}
}
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 don't have Entity classes in my project. My requirement is When I am connecting to DataBase Based on schema I have to Get the all Tables names from that schema.
Here I have a Schema as "companydb" with 5 tables. Below is my code to retrieve total number of tables from particular schema.
Here may be Exception occur by "Query". Query is not well here so what type of query I have to use and how Can I get List of tables.
persiatance.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="reports" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/reports" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="root" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
</properties>
</persistence-unit>
</persistence>
GetTableList.java
#WebServlet("/GetTableList")
public class GetTableList extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
EntityManager entityManager = EntityManagerUtil.getEmf()
.createEntityManager();
try {
Query query = entityManager.createQuery("SELECT * FROM companydb.tables");
List list = query.getResultList();
System.out.println(list);
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
iterator.next();
}
out.print(list);
System.out.println("Data retrived successfully");
} catch (Exception e) {
e.printStackTrace();
} finally {
entityManager.close();
}
}
}
Exception is:
java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:
Exception Description: Syntax error parsing the query [SELECT * FROM companydb], line 1, column 7: unexpected token [*].
Internal Exception: NoViableAltException(93#[330:16: ( DISTINCT )?])
how can I over come.
Use Native query to get List of tables from your schema
Query query = entityManager.createNativeQuery("SHOW TABLES FROM companydb");
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.
I'm having program that creates JPA entries with the entity manager.
during the process I don't get any errors.
...
factory = Persistence.createEntityManagerFactory("perst");
EntityManager entityManager = factory.createEntityManager();
entityManager.getTransaction().begin();
entityManager.persist(object);
entityManager.getTransaction().commit();
...
entityManager.close();
I have created a program like follows to read the data but it doesn't return any data,
the query returns empty. What could be the reason ?
This is the program to read the data:
static List<String> classList = new ArrayList<String>();
private static EntityManagerFactory factory;
public static void main(String[] args) {
// TODO Auto-generated method stub
factory = Persistence.createEntityManagerFactory("perst");
EntityManager entityManager = factory.createEntityManager();
classList.add("LeaveRequest");
classList.add("person");
for (Object classOjc : classList) {
String className = classOjc.toString();
Query query = entityManager.createQuery("SELECT p FROM " + className + " p");
#SuppressWarnings("rawtypes")
List resultList = query.getResultList();
System.out.println(resultList.size());
for (Object result : resultList) {
System.out.println(result.toString());
}
}
}
the xml persist is:
<?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="perst" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>LeaveRequest</class>
<class>person</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="Sales" />
<property name="javax.persistence.jdbc.password" value="" />
<!-- EclipseLink should create the database schema automatically -->
<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
<property name="eclipselink.ddl-generation.output-mode"
value="database" />
<property name="eclipselink.logging.level" value="SEVERE" />
<property name="eclipselink.logging.exceptions" value="true" />
</properties>
</persistence-unit>
</persistence>
You configured eclipselink to drop and recreate the schema each time the app is started:
<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
So obviously, if you run a first application that persists some entries, and then a second application which tries to read what the first one has written, you won't find anything anymore, since eclipselink drops everything and recreates the schema every time.