Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 4. Enterprise Java > Using the Java Persistence API with JRuby

4.12. Using the Java Persistence API with JRuby

4.12.1. Problem

You want to use the Java Persistence API (JPA) in your JRuby application.

4.12.2. Solution

Use the static JPA method Persistence.createEntityManagerFactory() to generate a factory for your persistence unit. A call to the factory’s createEntityManager() method generates a new EntityManager class, which is your primary tool for accessing the Persistence API. The EntityManager is analogous to Hibernate’s Session or Toplink’s ClientSession object and contains the methods to interact with the database and your model objects. The EntityManager object is not threadsafe and shouldn’t be used with multiple concurrent requests. It is designed to be used and discarded in a relatively short amount of time and not as a long-running software component. Example 4-27 shows a JRuby application that creates a few User objects and then queries the database to confirm that they were successfully added.

Example 4-27. Example JPA access from JRuby

include Java

import javax.persistence.Persistence
import cookbook.User

def with_trans(em)
 t = em.getTransaction();
 begin
   t.begin()
   yield
   t.commit
 ensure
   t.rollback if t.isActive
 end
end

emf = Persistence.createEntityManagerFactory("hello-world")
em = emf.createEntityManager

with_trans(em) do
      u = User.new("stephen","lee","slee","password","stephen@ora.com")
      u2 = User.new("stephen","smith","ssmith","password","ssmith@ora.com")
      em.persist(u)
      em.persist(u2)
end
query = em.createQuery("select u from User u where u.firstname = :firstname").
query.set_parameter("firstname", "stephen").
hu = query.get_result_list

hu.each do |u|
  puts "found #{u.firstname} #{u.lastname}"
end

em.close
emf.close

					  

4.12.3. Discussion

The example demonstrates the use of a block once again (see Section 4.10) to express a JPA transaction. This helper method also automatically rolls back the transaction if the commit should fail.

4.12.4. See Also