Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
You want to use the Java Persistence API (JPA) in your JRuby application.
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.
Code View:
Scroll
/
Show All 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
|
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.