Saturday, April 28, 2012

Sample EntityManager usage in Java and Python WLST

In Eclipse, create a JDBC Connection
show view Data Source Explorer
new Connection Profile (enter parameters for your schema)

New JPA project
JPA Tools, Generate Entities from Tables

you should have a persistence.xml which contains

<?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="ToplinkTest" transaction-type="RESOURCE_LOCAL">
  <class>com.osb.reporting.WliQsReportAttribute</class>
  <class>com.osb.reporting.WliQsReportData</class>
  <properties>
   <property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@localhost:1521:xe"/>
   <property name="javax.persistence.jdbc.user" value="DEV_SOAINFRA"/>
   <property name="javax.persistence.jdbc.password" value="DEV_SOAINFRA"/>
   <property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
  </properties>
 </persistence-unit>
</persistence>



You can now code the client:

package com.osb.reporting.client;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import com.osb.reporting.WliQsReportAttribute;

public class ReportingClient {
 public static void main(String[] args) throws ClassNotFoundException {
  EntityManagerFactory emf = Persistence.createEntityManagerFactory("ToplinkTest");
  EntityManager em = emf.createEntityManager();
  WliQsReportAttribute result = em.find(WliQsReportAttribute.class, "uuid:0e6fb58fc7c49289:5378b92d:134416bc5f5:-7fbe");
  System.out.println(result.getMsgLabels());
  Query fa = em.createQuery("select a from WliQsReportAttribute a");
  List res = fa.getResultList();
  for (Object el : res) {
   System.out.println( ((WliQsReportAttribute)el).getMsgLabels());
  }
 }
}



you will need to add the JDBC driver to the classpath, like
C:\bea1035\wlserver_10.3\server\ext\jdbc\oracle\11g\ojdbc5_g.jar

In WLST, just add to the classpath the location from which you can access classes and META-INF (where persistence.xml is located).... like the build\classes directory.


package com.osb.reporting.client;

from javax.persistence import *
emf = Persistence.createEntityManagerFactory("CMBDModeling")
em = emf.createEntityManager()
q = em.createQuery("select envs from Nesoa2Env envs")
res = q.getResultList()
for i in res:
   print i.envname

so the message is: you can easily use JPA in WLST and get rid of all that horrible pain of reading property files, by accessing directly a DB

No comments: