Weblog

All | Personal | Sun
« Previous day (Mar 29, 2006) | Main | Next day (Mar 30, 2006) »
20060330 Thursday March 30, 2006

Using TopLink persistence RI in Tomcat New EJB 3.0 persistence can be used in web module as well but all samples show this new feature in JavaEE5 projects. I assume that many users want to use this cool feature in web projects that have J2EE 1.4 version. I would like to show in this post how to use persistence in web project that is deployed in Tomcat. Of course, on the Tomcat we can't use container managed entity manager. Therefore, the application managed EM is used in this sample. You can use JTA entity managers or resource-local entity manager. Since the Tomcat doesn't support JTA we can use only resource-local entity manager. Let's create new web project with J2EE 1.4 specification and target server Tomcat in NetBeans 5.5. Don't forget that project should have defined 1.5 jdk as platform and we should change source level to 1.5. Of course, the Tomcat server must run on jdk 1.5 as well. Add JavaEE5 library and JDBC driver on project's classpath.Then, add persistence unit and choose application managed entity manager and generate entity classes from database or create them from scratch. In this post is presented using entity manager in servlet but similar approch might be used in JSF managed bean or in class too. The Entity manager might be used as follows:

    EntityManagerFactory emF = Persistence.createEntityManagerFactory("Advertisement");
        EntityManager  em = emF.createEntityManager();
        try{
            em.getTransaction().begin();
            List advertisements =
                 em.createQuery("SELECT a FROM Advertisement a").getResultList();
            for (Advertisement elem : advertisements) {
                out.println(elem.getDescription() +  ", " + elem.getId() + "
"); } em.getTransaction().commit(); }catch(Exception ex) { em.getTransaction().rollback(); }finally { em.close(); }
Build and run project. This works on Tomcat but I encountered security issues on Sun Application server 8.2. The workaround is that you should grant permissions for web module in server.policy. Add following lines in this file:
    permission java.lang.RuntimePermission  "createClassLoader";
    permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
  
Now, you can use Toplink persistence in existing web projects instead of Hibernate :-). Posted by pblaha ( Mar 30 2006, 03:28:46 PM CEST ) Permalink Comments [6]

Calendar

RSS Feeds

Search

Links

Navigation

Referers

Older blog entries