Showing posts with label JPA. Show all posts
Showing posts with label JPA. Show all posts

Saturday, March 19, 2011

Tricky thing in EclipseLink/TopLink

Recently, I got problem when I used a DB adapter in SOA suite to insert a record into DB with a sequence. I always got the follow exception.
Exception Description: The sequence named [AVS_REQUEST_SEQ] is setup incorrectly. Its increment does not match its pre-allocation size.


Searched by google and found somebody wrote the follow.
Use 100 as a start value will resolve the problem: by default the start value is 1, when Eclipselink attempts to use the first allocated sequence value it's negative 1 - 100 + 1, that causes the exception.
(Reference: http://dev.eclipse.org/mhonarc/lists/eclipselink-users/msg03461.html)

The above setting solved the issue, but I got a sequence number is 52 instead of 1. I keep to search and found another answer.
You must change the DBAdapter properties in WebLogic deployments console, make the preallocationSize same as the one used for the sequence.
<config-property name="sequencePreallocationSize" value="1"/>


I checked my connection setting in DBAdapter, the value is really 50 and that is why I got a sequence from 52 (101-50+1).

The follow step is the way to change the preI've found it. It is in the dbAdapter connection pool's configuration of sequencePreallocationSize.


In the Weblogic's console:
1) Deployments->dbAdapter
2) Configuration's Tab
3) Click on
4) Click on your ConnectionPoolFactory
5) Properties' Tab
6) Change 'sequencePreallocationSize' property's value to 1. Press ENTER to actually change it.
7) Click Save button.
8) Go to Deployments
9) Check dbAdapter and click Update
10) Click Finish

This is really a tricky thing.

Friday, March 11, 2011

Hibernate Cache

Hibernate is a well-know persistence framework in the  Java world, it comes with a wonderful API to ease application communication with the database. Caching is a mechanism that stores data so that future requests for that data can be served faster. It’s a good point for performance when there are a lot of requests for the same stuff . 


Hibernate comes with 3 caching mechanisms to resolve this issue.
First Level Cache
A hibernate session is a unit of work that’s corresponding to a DB transaction. When doing operations on entities, these latters are not stored immediately in DB but wait until the session commits. The hibernate session is hence representing the first level cache and it’s enabled by default.
Second Level Cache
A hibernate SessionFactory aims to create sessions, initializes JDBC connections and pool them. The second level cache lives in the SessionFactory level so all session can share it. This is why it’s called a process scoped cache.
The second level cache is not enabled by default. One has to configure the cache strategy for hibernate entities and the cache provider that will be a third party caching API like EHCache.
Query Cache
This is related to second level cache and is used for caching queries with parameters. It has to be configured like the second level cache.
To know if the application is hitting the cache, you can configure it in the session factory configuration file and begin your unit tests to get an idea of performance.

Friday, January 15, 2010

Who is the best JPA Provider in WebLogic?

http://www.theserverside.com/news/thread.tss?thread_id=44219

Posted by: Gavin King on February 10, 2007 in response to Message #227266
And by the way - I'm a bit out of date, but the actual measurements I did a year or so ago of simple CRUD performance of Hibernate vs. Kodo gave a mixed bag of results. They are slightly faster on creation/destruction of the persistence context and on inserts, we are a bit faster on queries. For mass operations on many objects, they are faster if you use standard APIs, we are quicker if you use StatelessSession. Etc.

Nowhere did I find anything that was a big enough difference that you would prefer one product over the other on the basis of performance alone.

Which confirmed to me that the BEA marketing line of the time that "Kodo is faster than Hibernate" is just the usual marketing BS, which was my initial reaction.

Friday, December 11, 2009

Java Persistence API Pro

(From http://hobione.wordpress.com/jpapro/)




Java Persistence API Pro


Book Reference: Pro EJB 3: Java Persistence API (Pro)


Chapter 1


Why Persistence?

As all we know that understanding the relational data is key to successful enterprise development. Moving data back and forth between to database system and the object model of a Java application is a lot harder than it needs to be. Java developers either seem to spend a lot of time converting row and column data into objects, or they find themselves tied to proprietary frameworks that try to hide the database from the developer. The Java Persistence API is set to have a major impact on the way we handle persistence within Java. For the first time, developers have a standard way of bridging the gap between object-oriented domain models and relational database systems.


Java Object – Database Relational Mapping:

The main thought behind to convert JDBC result sets into something object-oriented as follows.

” The domain model has a class. The database has a table. They look pretty similar. It should be simple to convert from one to the other automatically” The science of bridging gap between the object model and the relational model is known as object-relational mapping, aka O-R mapping or ORM.


Inheritance (Life is a dirty beach without JPA):

A defining element of an object-oriented domain model is to opportunity to introduce generalized relationships between like classes. Inheritance is the natural way to express these relationship and allows for polymorphisms in the application. When a developer start to consider abstract superclasses or parent classes with no persistent form, inheritance rapidly becomes a complex issue in object-relational mapping. Not only is there a challenge with storage of the class data, but the complex table realtionship are difficult to query efficiently.


JPA saves our soul (SOS):

The Java Persistence API is a lightweight, POJO-based framework for Java persistence. Although object-relational mapping is a major component of the API, it also offers solutions to the architectural challenges of integrating persistence into scalable enterprise applications.


Overview: JPA = Simple + elegant + powerful + flexible

Natural to use and easy to learn.


POJO: It means there is nothing special about any object that is made persistent. Java Persistence API is entirely metadata driven and it can be done by adding annotations to the code or using externally defined XML.


Non-Intrusiveness: The persistence API exists as a separate layer from persistence objects. The application must be aware of the persistence API, the persistence objects themselves need not be aware.


Object Queries: Query Language that derived from EJB QL and modeled after SQL for its familiarity, but it is not tied to the database schema. Queries use a schema abstraction that is based on the state of an entity as opposed to the columns in which the entity is stored. It returns results that are in the form of entities that enable querying across the Java domain model instead of across database tables.


Mobile Entities:


Simple Configuration:


Integration and Testability:


Chapter 2


Entity Overview: The entity is not a new thing. In fact, entities have been around longer than many programming languages and certainly longer than Java. Peter Chen who first introduced entity-relational modeling (1976) described entities as things that have attributes and relationships.


Here is an example of an Entity class from a regular Java Class:


 

package examples.model;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Employee {
@Id
private int id;
private String name;
private long salary;

public Employee() {}
public Employee(int id) {
this.id = id;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public long getSalary() {
return salary;
}

public void setSalary(long salary) {
this.salary = salary;
}

public String toString() {
return "Employee id: " + getId() + " name: " + getName() + " salary: " + getSalary();
}
}

To turn Employee into an entity we first needed to annotate the class with @Entity. This is primarily just a marker annotation to indicate to the persistence engine that the class is an entity. The second annotation was needed to use as the unique identifying key in the table. All entities of type Employee will get stored in a table called EMPLOYEE.


Entity Manager: Until an entity manager is used to actually create, read or write an entity, the entity is nothing more than a regular (non-persistent) Java object. An entity manager is the show for the game. The set of managed entity instances within an entity instances withing an entity manager at any given time is called it’s persistence context. Only one Java instance with the same persistent identity may exist in a persistence context any any time. For example, if an Employee with a persistent identity (or id) of 158 exists in the persistence context, then no other object with its id set to 158 may exist within that same persistence context. All entity managers come from factories of type EntityManagerFactory. For Java SE application should use EntityTransaction instead of Entity Manager.


Obtaining an Entity Manger: The static createEntityMangerFactory() method creates EntityManagerFactory from persistence unit name “EmployeeServices”:


 

EntityManagerFactory emf = Persistence.createEntityManagerFactory("EmployeeService");

Now we have a factory, we can obtain an entity manager from it:


 
EntityManager em = emf.createEntityManager();

Persisting an Entity: Insert. It creates a new employee and persist it to the database table


 

public Employee createEmployee(int id, String name, long salary) {
Employee emp = new Employee(id);
emp.setName(name);
emp.setSalary(salary);
em.persist(emp);
return emp;
}

Finding an Entity: Read


 
public Employee findEmployee(int id) {
return em.find(Employee.class, id);
}

In this case where no employee exists for the id that is passed in, when the method will return null, since that is what find() will return.


Removing and Entity: Delete


 
public void removeEmployee(int id) {
Employee emp = findEmployee(id);
if (emp != null) {
em.remove(emp);
}
}

Updating an Entity: Update


 
public Employee raiseEmployeeSalary(int id, long raise) {
Employee emp = em.find(Employee.class, id);
if (emp != null) {
emp.setSalary(emp.getSalary() + raise);
}
return emp;
}

Queries: Instead of using Structured Query Language (SQL) to specify the query criteria, in persistence world, we query over entities and using a language called Java Persistence Query Language (JPQL).

A query is implemented in code as a Query object and it constructed using EntityManger as a factory.

As a first class object, this query can in turn be customized according to the needs of the application.

A query can be defined either statically or dynamically (more expensive to execute). Also there is kind of query called named query as well.


 
public Collection<Employee> findAllEmployees() {
Query query = em.createQuery("SELECT e FROM Employee e");
return ( Collection <Employee> ) query.getResultList();
}

To execute the query, simply invoke getResultList() on it and this returns a List. Note that a List <Employee> is not returned b/c no class is passed into the call, so no parameterization of the type is able to occur. The return type is indirect by the persistence provider as it processes the JPQL String. By doing this ( Collection<Employee> ) to make a neater return type.


Chapter 3


EJB definitions:


Chapter 4


Object-Relational Mapping


Lazy Fetching: The data to be fetched only when or if it is required is called lazy loading, deferred loading, lazy fetching, on-demand fetching, jun-in-time reading, indirection. Data may not be loaded when the object is initially read from the database but will be fetched only when it is referenced or accessed. The FetchType could be LAZY or EAGER. Lazy = until it is referenced. The default is to eagerly load all basic mappings.


 

package examples.model;

import static javax.persistence.FetchType.LAZY;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;

@Entity
public class Employee {
@Id
private int id;
private String name;
private long salary;

@Basic(fetch=LAZY)
@Lob @Column( name = "PIC" )
private byte[] picture;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
......

@Basic annotation is required. The comments field to be fetched lazily will allow an Employee instance returned from a query to have the comment field empty. It will be transparently read and filled in by the provider (Toplink/Hibernate) once the comments filed get accessed.


Two things to be aware of.

First and foremost: The directive to lazily fetch an attribute is meant only to be a hint to the persistence provider to help the application achieve better performance. The provider is not required to respect the request, since the behavior of the entity is not compromised if the provider goes ahead and loads the attribute.


Second: It may appear that this is a good idea for certain attributes but it is almost never a good idea to lazily fetch for simple types. The only time when lazy loading of a basic mapping should be considered are when either there are many columns in a table (for example, dozens or hundreds) or when the columns are large (for example, very large character strings or byte strings).


Large Object:


Sunday, October 18, 2009

Why did Hibernate update my database?

From http://blog.xebia.com/2009/04/06/why-did-hibernate-update-my-database/

Hibernate is a sophisticated ORM framework, that will manage the state of your persistent data for you. Handing over the important but difficult task of managing persistent state of your application to a framework has numerous advantages, but one of the disadvantages is that you sort of lose control over what happens where and when. One example of this is the dirty checking feature that Hibernate provides. By doing dirty checking, Hibernate determines what data needs to be updated in your database. In many cases, this feature is quite useful and will work without any issues, but sometimes you might find that Hibernate decides to update something that you did not expect. Finding out why his happened can be a rather difficult task.

I was asked to look into some issue with a StaleObjectState exception the other day. StaleObjectState exceptions are used by hibernate to signal an optimistic locking conflict: While some user (or process) tries to save a data item, the same data item has already been changed in the underlying database since it was last read. Now the problem was that the process that was throwing the exception was the only process that was supposed to change that data. From a functional point of view there could not have been any other user or process that changed the data in the meantime. So what was going on?

Digging around in the log for some time, we found that the data was updated by some other process that was supposed to only read that data. Somehow Hibernate decided that the data read by that process had become dirty and should be saved. So now he had to find out why Hibernate thought that data was dirty.

Hibernate can perform dirty checking in several places in an application:

1. When a transaction is being committed or a session is being flushed, obviously, because at that time changes made in the transaction or session should be persisted to the database
2. When a query is being executed. To prevent missing changes that still reside in memory, Hibernate will flush data that might be queried to the database just before executing the query. It tries to be picky about this and not flush everything all the time, but only the data that might be queried.
It is quite difficult to check all these places to find out where the data is being find dirty, especially when the process executes several queries.

To find out why Hibernate deems the data to be dirty, we have to dig into the Hibernate internals and start debugging the framework code. The Hibernate architecture is quite complex. There are a number of classes that are involved in dirty checking and updating entities:

The DefaultFlushEntityEventListener determines what fields are dirty. The internals of this class work on the list of properties of an entity and two lists of values: the values as loaded from the database and the values as currently known to the session. It delegates finding out the ''dirty-ness' of a field to the registered Interceptor and to the types of the properties.
The EntityUpdateAction is responsible for doing the update itself. An object of this type will be added to a ActionQueue to be executed when a session is flushed.
These classes show some of the patterns used in the internals of Hibernate: eventing and action queuing. These patterns make the architecture of the framework very clear, but they also make following what is going on sometimes very hard...

As previously explained, flushing happens quite often and setting a breakpoint in the DefaultFlushEntityEventListener is not usually a good idea, because it will get hit very often. An EntityUpdateAction, however, will only get created when an update will be issued to the underlying database. So to find out what the problem was, I set a breakpoint in the constructor and backtracked from there. It turned out Hibernate could not determine the dirty state of the object and therefor decided to update the entity just to be save.

As mentioned eralier, Hibernate uses the "loaded state" to determine whether an object is dirty. This is the state of the object (the values of its properties) when loaded form the database. Hibernate stores this information in its persistence context. When dirty checking, Hibernate compares these values to the current values. When the "loaded state" is not available, Hibernate effectively cannot do dirty checking and deems the object dirty. The only scenario, however, in which the loaded state is unavailable is when the object has been re-attached to the session and thus not loaded from the database. The process I was looking into, however did not work with detached data.

There is one other scenario in which Hibernate will lose the "loaded state" of the data: When the session is being cleared. This operation will discard all state in the persistence context completely. It is quite a dangerous operation to use in your application code and it should only be invoked if you are very sure of what you're doing. In our situation, the session was being flushed and cleared at some point, leading to the unwanted updates and eventually the StaleObjectStateExceptions. An unwanted situation indeed. After removing the clear, the updates where gone and the bug was fixed.

Using Hibernate can save a developer a lot of time, when things are running smoothly. When a problem is encountered, a lot of specialized Hibernate knowledge and a considerable amount of time is often needed to diagnose and solve it.

Friday, October 16, 2009

JPA and Hibernate Tutorial

A tutorial website of hibernate.
http://www.hibernate-training-guide.com/index.html


Hibernate 3 Annotations Tutorial
http://loianegroner.com/2010/06/hibernate-3-annotations-tutorial/

Two slides from Sun.
http://www.slideshare.net/caroljmcdonald/td09jpabestpractices2
http://developers.sun.com/learning/javaoneonline/2007/pdf/TS-4902.pdf?

http://java.sun.com/javaee/5/docs/tutorial/doc/bnbqw.html

Basic Java Persistence API Best Practices
http://www.oracle.com/technology/pub/articles/marx-jpa.html

An IBM Book
http://books.google.ca/books?id=ko5KTfIHjasC&printsec=frontcover&source=gbs_v2_summary_r&cad=0#v=onepage&q=&f=false

Generic Repository - Generic DB access?

Generic Repository (grepo) is an open source (ASLv2) framework for Java which allows you to access (database) repositories in a generic and consistent manner.

The main features of the framework are:
* generic support for Hibernate based DAOs
* generic support for Jpa based DAOs
* generic support for executing database stored-procedures and functions
* highly customizable

The "Generic Query" component allows to access databases using SQL queries. Currently the following ORM (Object Relational Mapping) tools/APIs are supported:

* Native Hibernate API
* Java Persistence API

The "Generic Procedure" component allows to access databases using PLSQL (that is calling stored procedures and/or functions) without requiring custom implementations - gprocedure is build on top of the Spring (JDBC) framework.


History
Daniel Guggi

The Generic Repository Framework (grepo) has its origins back in 2007. I started development after reading Per Mellqvist's article "Don't repeat the DAO". My employer BearingPoint INFONOVA GmbH develops and maintains various business applications for its customers (mainly telecom providers). The software is developed/extended by various development (scrum) teams. Even though we have a professional development environment (using professional/good tools and frameworks etc...) and development guidelines (detailed coding conventions etc...) it turned out that the data access layers in our software products got quite fragmented, inconsistent and bloated - mainly because of big development teams and large software products, the typicall daily project-stress and the always reoccoring (similar) boilerplate code for database access logic. So we started developing a framework which in turn was tuned and improved in order to achieve the following main goals for our software products:

* Ensure coding conventions and guidelines.
* Avoid boilerplate code for database access logic.
* Improve development time and code quality.

Finally we came up with a framework based on Spring and Hibernate. The framework is integrated in our software products for quite a while right now and is used for basically (at least about 90%) all new database related access objects. We are quite happy with the result and thus we decided to make it open source - and so the Generic Repository project was born.

Saturday, October 10, 2009

Configuring a JBoss + Spring + JPA (Hibernate) + JTA web application

(From http://www.swview.org/node/214)
Here's how one might go about deploying a Spring application in JBoss (4.something) that uses JPA with Hibernate as the provider for persistence and JTA for transaction demarcation.

1. Define the Spring configuration file in the web.xml file

<context-param>
        <description>Spring configuration file</description>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>



2. Define the Spring loader in the web.xml file

<listener>
        <description>Spring Loader</description>
        <listener-class>
         org.springframework.web.context.ContextLoaderListener
        </listener-class>
</listener>


3. Define the persistence unit reference in the web.xml file (which in fact has no effect until the Servlet container supports Servlet spec 2.5):

<persistence-unit-ref>
        <description>
            Persistence unit for the bank application.
        </description>
       
       <persistence-unit-ref-name>
              persistence/BankAppPU
       </persistence-unit-ref-name>
        <persistence-unit-name>BankAppPU</persistence-unit-name>       
</persistence-unit-ref>


* Note that this is what enables "" which has been commented out in the below given Spring configuration file.

* For the above to work well, your web.xml should start like this (note the version 2.5):

<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">


4. Here's the persistence.xml file. Make the changes to the as you have defined in your system (for example in a file like JBOSS_HOME/server/default/deploy/bank-ds.xml - See JBOSS_HOME/docs/examples/jca/ for templates).

<?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="BankAppPU" transaction-type="JTA">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <jta-data-source>java:BankAppDS</jta-data-source>
    <properties>
      <property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.JBossTransactionManagerLookup"/>
      <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
      <property name="jboss.entity.manager.factory.jndi.name" value="java:/BankAppPU"/>
      <property name="hibernate.hbm2ddl.auto" value="update"/>
    </properties>
  </persistence-unit>
</persistence>


5. Here's a sample Spring configuration file (applicationContext.xml):

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
       http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd">

    <!-- In a fully J5EE compatible environment, the following xml tag should work in accessing the EMF -->          
<!--
    <jee:jndi-lookup id="entityManagerFactory" jndi-name="java:/BankAppPU"/>
-->
  
    <!-- Hack for JBoss 4.something until full compliance is reached -->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
      <property name="persistenceUnitName" value="BankAppPU"/>
    </bean>

    <!-- Let's access the JTA transaction manager of the application server -->
    <bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager">
        <property name="transactionManagerName" value="java:/TransactionManager"/>
        <property name="userTransactionName" value="UserTransaction"/>
    </bean>
   
    <!-- Let's define a DAO that uses the EMF -->
    <bean id="accountHolderDAO" class="bankapp.dao.AccountHolderDAO">
        <property name="emf" ref="entityManagerFactory"/>
    </bean>
   
    <!-- This is a service object that we want to make transactional.
         You will have an interface implemented (AccountManager) in the class.
    -->
    <bean id="accountManager" class="bankapp.AccountManagerImpl">
        <property name="accountHolderDAO" ref="accountHolderDAO"/>
    </bean>
   
   
    <!-- The transactional advice (i.e. what 'happens'; see the <aop:advisor/> bean below) -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <!-- the transactional semantics... -->
        <tx:attributes>
            <!-- all methods starting with 'get' are read-only transactions -->
            <tx:method name="get*" read-only="true"/>
            <!-- other methods use the default transaction settings (see below) -->
            <tx:method name="*" read-only="false" />
        </tx:attributes>
    </tx:advice>
   
   
    <!-- ensure that the above transactional advice runs for execution
      of any operation defined by the AccountManager interface -->
    <aop:config>
        <aop:pointcut id="accountManagerOperation",
           expression="execution(* bankapp.AccountManager.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="accountManagerOperation"/>
    </aop:config>
</beans>


6. Here's the sample AccountManagerImpl:

public class AccountManagerImpl implements AccountManager {
   
    /** Creates a new instance of AccountManagerImpl */
    public AccountManagerImpl() {
    }


    private AccountHolderDAO accountHolderDAO;
   
    public AccountHolder createAccountHolder(AccountHolder accountHolder) throws BankException {
        return accountHolderDAO.create(accountHolder);
    }


    public AccountHolderDAO getAccountHolderDAO() {
        return accountHolderDAO;
    }


    public void setAccountHolderDAO(AccountHolderDAO accountHolderDAO) {
        this.accountHolderDAO = accountHolderDAO;
    } 
}




7. Here's the sample AccountHolderDAO:

public class AccountHolderDAO {
   
    /** Creates a new instance of AccountHolderDAO */
    public AccountHolderDAO() {
    }
   
    private EntityManagerFactory emf;


    public EntityManagerFactory getEmf() {
        return emf;
    }


    public void setEmf(EntityManagerFactory emf) {
        this.emf = emf;
    }
   
    public AccountHolder create(AccountHolder newAccountHolder) throws BankException {
        try {
           
            // JTA Transaction assumed to have been started by AccountManager (Spring tx advice)
            EntityManager em = emf.createEntityManager();
            //em.getTransaction().begin(); - Not required
            em.persist(newAccountHolder);
            //em.getTransaction().commit(); - Not required
            return newAccountHolder;
            // JTA Transaction will be completed by Spring tx advice
           
        } catch (Exception e) {
            throw new BankException("Account creation failed" + e.getMessage(), e);
        }
    } 
}




You will have some other code accessing the Spring bean "accountManager" and invoke the createAccountHolder() with the required parameters. Things should work well.

Java Persistence API

The Java Persistence API is a POJO persistence API for object/relational mapping. It contains a full object/relational mapping specification supporting the use of Java language metadata annotations and/or XML descriptors to define the mapping between Java objects and a relational database. Java Persistence API is usable both within Java SE environments as well as within Java EE.

It supports a rich, SQL-like query language (which is a significant extension upon EJB QL) for both static and dynamic queries. It also supports the use of pluggable persistence providers.

The Java Persistence API originated as part of the work of the JSR 220 Expert Group to simplify EJB CMP entity beans. It soon became clear to the expert group, however, that a simplification of EJB CMP was not enough, and that what was needed was a POJO persistence framework in line with other O/R mapping technologies available in the industry. The Java Persistence API draws upon the best ideas from persistence technologies such as Hibernate, TopLink, and JDO.