Is it possible to use EclipseLink (with persistence.xml) with Embedded Derby - java

So here is what i am trying to achieve:
A Java App with JPA implementation usinf Embedded Derby. Once this is working , i am then planning to have Spark (with Jetty Server) and Angular js.
These are the tools/frameworks i am using
Eclipse IDE (Luna)
Maven Build system
JPA Implementation (EclipseLink)
Embedded Derby for database
Spark with Embedded Jetty server.
Angular JS
I have the persistence.xml defined with the Derby Embedded Driver and the db properties.
In the Main class i am using the EntityManger to get the EM. I also create new Instance of the EmbeddedDerby to start the Engine.
But when i run the App, it says "No Persistence provider Persistence for Entity Manager"named testSparkJettyDerby"
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://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="testSparkJettyDerby" transaction-type="RESOURCE_LOCAL">
<class>model.MyUser</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:derby:sample;create=true"/>
<property name="javax.persistence.jdbc.user" value="user"/>
<property name="javax.persistence.jdbc.password" value="xxxx"/>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver"/>
</properties>
</persistence-unit>
Code snippet in my Main Class
createConnection();
// TODO Auto-generated method stub
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factory.createEntityManager();
private static void createConnection()
{
try
{
Class.forName("org.eclipse.persistence.jpa.PersistenceProvider");
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
//Get a connection
conn = DriverManager.getConnection(dbURL);
if(conn != null) {
System.out.println("Connected...");
}
}
catch (Exception except)
{
except.printStackTrace();
}
}
My derby jar files are in the classpath.
I am not sure if this is possible, but i could not find any tutorial or answers who have done something like this.
Any help is appreciated.
Thanks in advance..

Make sure that your persistence.xml file is in classes(or whatever your build dir is)/META-INF.

Related

JPA on MFP Java adapter

I've created a Java adapter in MFP 7.0. The adapter is running on the local development server (Liberty). Since I couldn't find any references in the documentation, is there a possibility to use JPA within the Java adapter to access DB data?
Where do I need to put the persistence.xml?
Is there any configuration I have to do on the Liberty profile server.xml?
Where do I need to put the DB driver's library jar (EclipseLink)?
Attached you'll find the code from the Java adapter:
#GET
public String performJPAQuery(){
String result = null;
Person marco = new Person();
marco.setId(1);
marco.setName("Marco");
// connection details should be loaded from persistence.xml
EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpa-test");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(marco);
tx.commit();
// Querying the contents of the database using JPQL query
Query q = em.createQuery("SELECT p FROM Person p");
#SuppressWarnings("unchecked")
List<Person> results = q.getResultList();
logger.info("List of persons\n----------------");
for (Person p : results) {
logger.info(p.getName() + " (id=" + p.getId() + ")");
}
// Closing connection
em.close();
emf.close();
return result;
}
This is how my persistence.xml looks like:
<?xml version="1.0"
encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">
<persistence-unit name="jpa-test" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.sample.Person</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.sqlite.JDBC" />
<property name="javax.persistence.jdbc.url" value="jdbc:sqlite:sample.db" />
<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
<property name="eclipselink.ddl-generation.output-mode" value="database" />
</properties>
</persistence-unit>
</persistence>
That is definitely possible. The location of the persistence.xml file should be as described here. Besides that, you will have to either:
use the connection using JNDI (in which case you do not need the javax.persistence.jdbc.url parameter).
along to the javax.persistence.jdbc.url parameter put the user credentials to your DB in persistence.xml (if you go for this option google for it, as it depends on the JPA/EclipseLink vesion, but probably this is a good start).
Instantiate manually EVERYTHING, in which case you do not need the persistence.xml file. This option is much more complicated, but also more flexible. I did it with Hibernate once, thus cannot help you with EclipseLink.

Hibernate: app doesn't close after crash

My app just creates an EntityManager and after that I throw a RuntimeException on purpose. If I place the RuntimeException line before I create the entity manager, the exception is correctly caught by main and the app closes (as expected). But if any exception occurs after that, the exception is caught (I can see the stacktrace) but the app keeps running and I have to kill it. In Netbeans, the thread's state is "zombie".
libs used
Hibernate 4.3.1 Final: all jars from jpa folder and required folder (link)
Database connector: jtds 1.3.1 (link)
My test class
package test;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] args) {
// throw an exception here, app closes as expected
EntityManagerFactory factory = Persistence.createEntityManagerFactory("pu");
EntityManager em = factory.createEntityManager();
// throw an exception here, it runs forever
throw new RuntimeException();
}
}
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">
<persistence-unit name="pu" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect"/>
<property name="javax.persistence.jdbc.driver" value="net.sourceforge.jtds.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="user"/>
<property name="javax.persistence.jdbc.password" value="password"/>
<property name="javax.persistence.jdbc.url" value="jdbc:jtds:sqlserver://server:1433/database"/>
</properties>
</persistence-unit>
</persistence>
Any EntityManagerFactory could get hold of critical resources which need proper cleanup; in your example it's probably a thread managing the connection.
You must make sure the factory is closed: normally frameworks take care of proper shutdown, but if you manage the resources yourself you have to enclose the next blocks in a finally block.
EntityManagerFactory factory = Persistence.createEntityManagerFactory("pu");
try {
// rest of your application here
}
finally {
factory.close();
}
Are you trying to close your application on purpose? I'm not sure I follow what you're attempting to do here.
If all you want to do is stop the application, you can call,
System.exit(0)
which signifies that the execution of the program was successful, or pass in other numbers to signify a failure.

Vaadin JPAContainer doesn't work

I created a web app application like my work thesis. This application used the entire stack java EE 6: JPA2, EJB, JSF, RichFaces....
Now i'm trying to change the UI of my application from RichFaces to Vaadin. The first problems began with use of JPA container. i can't get a instance of entitymanager.
this is my persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">
<persistence-unit name="primary">
<jta-data-source>java:jboss/VaadinDS</jta-data-source>
<class>org.mypackage.entity.Utente</class>
<class>org.mypackage.entity.Indirizzo</class>
<class>org.mypackage.entity.Paese</class>
<properties>
<!-- Properties for Hibernate -->
<property name="hibernate.hbm2ddl.auto" value="create" />
<property name="hibernate.show_sql" value="false" />
</properties>
</persistence-unit>
</persistence>
this is my singelton class where i want to get the i instance of entitymanager
public class Utility {
private static EntityManager entityManager;
public Utility() {
// TODO Auto-generated constructor stub
}
public static EntityManager getInstance(){
if(entityManager == null)
entityManager = JPAContainerFactory.createEntityManagerForPersistenceUnit("primary");
return entityManager;
}
}
but doesn't work , i showed always the followed error:
[com.vaadin.server.DefaultErrorHandler] (http-localhost-127.0.0.1-8080-1) : java.lang.NullPointerException
where i wrong?
Your persistence.xml file needs to have a dialect property
Also, you need 2 other things that the book of vaadin explain if you are using hibernate with the jpacontainer: The use of one entity manager per reqeust pattern and the use of hibernate lazy loading delegate on your entity provider. If you need more help, I'll keep updating this answer.

An application using EJB 3.0 and Hibernate persistence provider gives an UnknownServiceException

I am trying to create a web app using JSF and EJB 3.0.
I am using plain JSF, Glassfish Server, Hibernate as my persistance provider. My database is apache derby.
Here my Stateless Session bean as follows:
#Stateless
#TransactionManagement(TransactionManagementType.CONTAINER)
public class StudentServiceBean implements StudentService{
#PersistenceContext(unitName="forPractise")
private EntityManager entityMgr;
#Resource
private SessionContext sessionContext;
#Override
public List<StudentVO> fetchStudentListOrderByStudentId(boolean flag){
List<StudentEntity> studentList = null;
TypedQuery<StudentEntity> studentQuery = null;
List<StudentVO> studentVOList = null;
String queryDesc = "select s from StudentEntity s order by s.studentId desc";
String query = "select s from StudentEntity s order by s.studentId";
try{
if(!flag){
studentQuery = entityMgr.createQuery(query,StudentEntity.class);
}else{
studentQuery = entityMgr.createQuery(queryDesc,StudentEntity.class);
}
studentList = studentQuery.getResultList();
studentVOList = new ArrayList<StudentVO>();
for(StudentEntity studentE : studentList){
studentVOList.add(new StudentVO(String.valueOf(studentE.getStudentId()),studentE.getStudentName(),studentE.getContactNumber()));
}
}catch(Exception e){
System.out.println(" EXCEPTION IN "+this.getClass().getName()+" in method fetchStudentListOrderByStudentId "+e);
}
return studentVOList;
}
And this is 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_2_0.xsd"
version="2.0">
<persistence-unit name="forPractise" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/app</jta-data-source>
<class>com.entity.StudentEntity</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.SunONETransactionManagerLookup" />
</properties>
</persistence-unit>
</persistence>
What happens is on load of the JSP page, the getter method of StudentList is called -
inside the getter method I have written logic that if studentList is empty then call the studentService.fetchStudentListOrderByStudentId(true);.
But when I do this I get an exception:
EXCEPTION IN com.bb.StudentServiceBean in method
fetchStudentListOrderByStudentId
org.hibernate.service.UnknownServiceException: Unknown service
requested
[org.hibernate.service.jdbc.connections.spi.ConnectionProvider]
Can you please tell me what I am missing, or where I am going wrong?
Thanks.
You indicate that you are using Hibernate 4.x, but the class you mentioned afaik is only valid for JPA 1.0 and Hibernate 3.x. Try removing the following line from your configuration:
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.SunONETransactionManagerLookup" />
Just in case it's of any interest, I got this error on Jetty when trying to start a Hibernate session:
Unknown service requested [org.hibernate.service.jdbc.connections.spi.ConnectionProvider]
The root cause was a previous Exception (a few seconds earlier in the logs) which caused the spring context (WebAppContext) to fail to initialize.
Once I fixed the spring context, the "Unknown service requested" fixed itself. So, if you're seeing this error it's worth checking for earlier errors before investigating too much..

Is there a non-commercial Hibernate query checker?

We are using Hibernate at my workplace on some project and I had to modify some queryes recently. I found it really cumbersome to modify a query, run an ant smart or ant refresh and see whether my query works. When I asked one of my colleagues he told me that it is the way we use it.
Do you have any idea how can I speed up this process? I'm looking for a tool which can connect to a database (we are using PGSQL) and run my Hibernate query there and show the results without touching ant.
For example I would be able to try this:
#Query(query = "SELECT DISTINCT l FROM Line l, IN(l.workplaces) w WHERE w.workshop.sid=:wsid", params = "wsid")
JBoss Tools for eclipse has a HQL editor that you can open from the hibernate perspective, you can test hql queries there.
We have a junit-Test for hibernate which uses the derby database as a in-memory databse. This will create the database in derby with all tables and you should be able to execute the query, to see if it is valid.
We have all queries in the orm.xml, so those queries are already checked when creating the EntityManager.
setup
private static EntityManagerFactory emf;
private static EntityManager em;
#BeforeClass
public static void before()
{
emf = Persistence.createEntityManagerFactory("persistenztest");
em = emf.createEntityManager();
}
test
#Test public void test()
{
Query q = em.createQuery(YOUR_QUERY_HERE);
List<?> list = q.getResultList();
}
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="persistenztest" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<mapping-file>orm.xml</mapping-file>
<properties>
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.connection.driver_class" value="org.apache.derby.jdbc.EmbeddedDriver" />
<property name="hibernate.connection.url" value="jdbc:derby:memory:sa;create=true;territory=de_DE;collation=TERRITORY_BASED:SECONDARY;"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.HashtableCacheProvider"/>
<property name="hibernate.cache.use_query_cache" value="false"/>
<property name="hibernate.cglib.use_reflection_optimizer" value="false" />
</properties>
</persistence-unit>
</persistence>

Categories

Resources