20 abril 2009

persistence unit

Packaging

EJB3 JPA is standardizing POJO persistence. Thus, entities aren't limited to EJB modules; they can be packaged in a Web module, ejb-jar module, library module in the EAR level, or a standard jar file. You can also use entities in Java SE. You must package a descriptor (persistence.xml), like the following, in the archive that contain entities:



oracle.toplink.essentials.PersistenceProvider
jdbc/OracleDS
...

This descriptor identifies the persistence provider, persistent units, and the data source used by a persistent unit. As the name suggests, a persistent unit is a collection of entities that are managed together. If you have a single persistent unit defined in a specific module, you don't have to identify the entity classes in the persistence.xml; it will be dynamically discovered by the persistence provider.

persist an entity (Serializable) on application-managed entity manager

from Standardizing Java Persistence with the EJB3 Java Persistence API

If you persist an entity, any state changes to associated entities will be persisted as well if CascadeType for the relationship is set to PERSIST or ALL. Unless you're using an extended persistent context, the entities will become detached after the end of the transaction. The merge operation lets you merge a detached entity instance with the persistent context; the state of a detached entity will be synchronized with the database. This helps you get rid of the Data Transfer Object (DTO) anti-pattern prevalent in EJB 2.x because entities, being POJOs, can be transferred between tiers. The only requirement is that the entity class must implement the java.io.Serializable interface.

Extending the Hibernate Validation Framework for Complex Rules

Extending the Hibernate Validation Framework for Complex Rules


go

The Hibernate Validation Framework leverages annotations to define data validation rules on entity beans. Out of the box it comes with many useful annotations for defining simple validation rules such as, NotNull, Min, Max, etc... However, for complex rules that involve multiple properties you will have to write your own validators. This posting shows two approaches to make this easier by using expression language and custom code fragments.

Simple Validations


Here is an example of a simple validation. The annotation on the amount property is scoped just to that property. Thus only simple rules can be defined.

@Entity
public class Loan {
@NotNull(message="The Amount must be provided.")
private Double amount;
...
}

Complex Validation


Here is an example of a complex validation. The annotation on the class is scoped to the whole class. Thus complex rules can be defined that involve any property in the class.

@Entity
@StartDateBeforeEndDate(message="The start date must be before the end date.")
public class Loan {
private Date startDate;
private Date endDate;
...
}

These features pretty much cover all the various validation requirements. However, defining complex validation rules requires writing both a custom annotation and a custom validator for each rule, which can become very cumbersome. Here are two ways around this issue.

Expression Language Validator


By using expression language we can write a generic validator that can be reused for various rules. The generic Expression annotation is used to define the rule.


@Entity
@Expression(value="value.startDate <>", message="The start date must be before the end date.")
public class Loan {
private Date startDate;
private Date endDate;
...
}

The ExpressionValidator class uses the commons-jexl library to evaluate the expression. The value variable in the expression equals the instance of the object being validated. In this case value is a loan.

public class ExpressionValidator implements Validator {
private String expression;
public void initialize(Expression expression) {
this.expression = expression.value();
}

public boolean isValid(Object value) {
org.apache.commons.jexl.Expression e = ExpressionFactory.createExpression(expression);
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("value", value);
return (Boolean) e.evaluate(jc);
}
}

Custom Assertion Validator


There are times when you will just have to write custom validation code. But instead of writing a custom annotation and validator class it would be nice to encapsulate the rules in the same class for which the rules apply. This generic Assertion annotation and IAssertion interface do the trick.

@Entity
@Assertion(value=Loan.StartDateBeforeEndDateAssertion.class, message="The start date must be before the end date.")
public class Loan {
private Date startDate;
private Date endDate;
...
public static class StartDateBeforeEndDateAssertion implements IAssertion
{
public boolean isValid(Object value) {
Loan loan = (Loan) value;
return
loan.getStartDate().before(loan.getEndDate());
}
}
}

The AssertionValidator class will create an instance of the IAssertion and execute it against the object being validated.

public class AssertionValidator implements Validator {
private IAssertion assertion;
public void initialize(Assertion assertion) {
this.assertion = (IAssertion) assertion.value().newInstance();
}

public boolean isValid(Object value) {
return assertion.isValid(value);
}
}

Hopefully the expression appoach will satisfy all your needs and you wont need this custom code approach. For example, you could add an isStartDateBeforeEndDate() method to your entity and call it in a simple expression as show below. But the custom code approach is here just in case.

@Entity
@Expression(value="value.startDateBeforeEndDate", message="The start date must be before the end date.")
public class Loan {
...
public boolean isStartDateBeforeEndDate() {
return startDate.before(endDate);
}
}

Multiple Rules


There is still another piece to this puzzle. We need to be able to apply multiple expressions or assertions. To do this we need a container annotation.

@Entity
@Expressions ({
@Expression(value="value.startDate <>", message="..."),
@Expression(value="...", message="...")
})
public class Loan {
private Date startDate;
private Date endDate;
...
}

Note that this capability relies on a requested Hibernate enhancement. You can vote for this enhancement here: JIRA Issue ANN-513. Or you can apply the patch yourself.

Resources



An Agile Development Environment

An Agile Development Environment



All agile methodologies preach delivering working software early and continuously. To achieve this an automated development environment is beneficial. It is also important to get a new project up and running quickly. To this end here is a suggested development environment made up of open source tools along with instructions for getting up and running.

Server Machine

  • Use your perfered operationing system: Linux, Windows, etc. These instructions will be some what specific to Windows.
  • Two gigs of RAM, a dual processor, and a fast harddrive are the minimum recommendations.
  • Install Java 5 or higher: http://java.sun.com/javase/downloads/index_jdk5.jsp

Source Control Management



The first thing you will need on your development server is version control. SVN is the tool of choice!
Next you want to install Apache HTTP Server to access SVN remotely.
LoadModule dav_svn_module modules/mod_dav_svn.so
    • map the location

DAV svn
SVNPath c:/svnrepos


On the client machines you will need Subclipse and TortoiseSVN.

Continuously Integration Build System


Now we need to install Maven and create your own corporate maven repository.
  • Download Maven
  • Unzip to a desired location
  • Add the bin directory to your system path
  • Add the following to your httpd.conf file
Alias /maven2/ c:/WINDOWS/system32/config/systemprofile/.m2/repository/
Alias /maven2 c:/WINDOWS/system32/config/systemprofile/.m2/repository

Options Indexes
AllowOverride All
Order allow,deny
Allow from all


Next we need to install and configure Continuum to automate your builds.
  • Download Continuum
  • Unzip to a desired location
  • Add the following to your httpd.conf file
ProxyPass /continuum http://localhost:8091/continuum/
ProxyPassReverse /continuum http://localhost:8091/continuum/

Alias /working-directory/ c:/continuum/working-directory/
Alias /working-directory c:/continuum/working-directory/

Options Indexes
AllowOverride All
Order allow,deny
Allow from all


Note that you will need to add the and sections to all of your pom.xml files.

Database


For running junit tests the Hypersonic in memory database is excellent. It can be downloaded automatically by maven. To demo your applications to your customers MySQL is a great choice.
  • Download and run
    • mysql-essential-4.1.21-win32.msi
    • mysql-gui-tools-5.0-r3-win32.msi
  • Download and place in your app servers lib directory
    • mysql-connector-java-3.1.13.zip


Application Server


To get up and running fast with JBoss AS + Portal you can start with the Taylor Tracker Bundle. It is preconfigured with various JBoss components. Just unzip it to the desired location. You will want at least two servers configured: QA and PM. The QA server will be used for running all your automated test cases and for demonstration to your customer. The PM server will run various project management and collaboration software like Taylor Tracker, JBoss Wiki, and JBoss Forum, etc.

Client Tools


On the client side us Eclipse. More information is available on the Taylor Installation page.


That is pretty much it! It is also a good idea to ghost this configuration so that you can stamp out new servers as needed. And don't forget to setup a backup schedule for the SVN repository and the MySQL database.

19 abril 2009

Taylor - Model Management

Model Management



In any real world application you will need to manage the size of your models so that multiple people can work on the project at the same time. This is often referred to as Team support.

Contents

[hide]

SCM

The obvious solution is to use a Source Control Management (SCM) system such as CVS or Subversion. Taylor model files are just XMI files, so they are ready for scm. And Eclipse provides the scm infrastructure needed for checkin, checkout, diff, merge, etc...

But, scm is not enough.

Architecture

We are really talking about an architecture problem. Not the architecture of the tool, but the architecture of your project. Is it one big jumble or is it decomposed into reasonable systems and subsystems and components and so forth.


Tool Support

Taylor leverages all of the features provided by EMF and GMF.

There are 2 basic options:

  • Use multiple models and link them together
    • See Resource Linking and Diagram Shortcuts
  • Divide one model into separate files by package
    • See Controlling Packages

You will probably use some combination of both.

Resource Linking

  • Right click anywhere in the Navigator and select Load Resource...
  • Browse the workspace for a model
  • Then you should be able to access the elements in the linked model from various property editors

Diagram Shortcuts

  • Right click in a diagram and select Create Shortcut...
  • Browse to an element you want to display in the diagram

Controlling Packages

  • Right click any package in the Navigator and select Control...
  • Select Browse Workspace and select a folder to create the new file
  • Name the file similar to the package name and give it a .uml extension
  • Then right click on the navigator and select Save to create the new file
  • A little green icon decoration will show that the package is controlled

Taylor

Classpath

Now lets setup the classpath before browsing the code.

Open the Eclipse preferences and add a M2_REPO classpath variable that points to your Maven repository [${user.home}/.m2/repository]

  • Or use maven: mvn -Declipse.workspace= eclipse:add-maven-repo


Open a command window, navigate to your master project directory, and run 'mvn install' and then 'mvn eclipse:eclipse' to generate the .project and .classpath files for all of the projects.

NOTE: If this is the first time you are running this it will take a while to download all the necessary jars. You may have to repeat it several times. It will also fail when it reaches the web project, but that is OK, we will come back to that later.

  • If you want to use WTP with the web project then use mvn eclipse:eclipse -Dwtpversion=1.5 in the web and pdf project directories
  • JSF Support


Now, go back to Eclipse and switch to the Java perspective. Then select all the projects and press F5 to refresh.

Now browse the code to see what was generated. The high-lights are discussed below.



Enumerations

Also give creating an Enumeration a try. And add some Literals. Then create a status property on the entity bean with a type of Status.

Now lets run some helper utilities to make some bulk changes to the model. Right-click on the net.taylor.tutorial.entity package and select Utilities > JPA and then run:

  • Add Temporal Stereotypes and
  • Add Enumeration Stereotypes

JSF Support

This will probably be fixed in a future version of the eclipse plugin.

Add the following to .settings/org.eclipse.wst.common.project.facet.core.xml

  

Types to Java and JSF Mapping

NOTE: Change the type of the description property to types.Text so that a Text Area will be generated in the facelet.

String String JSF Input Text
Text String Text Area - TinyMCE Editor
Date Date Seam Date Picker
Boolean Boolean JSF Check Box
Integer Long RichFaces Spinner
Decimal Double JSF Decimal
Currency BigDecimal JSF Currency
Percentage Double JSF Percentage
Byte[] byte[] Seam File Upload
Image String JSF Image
Link String JSF Link
Enumeration your Enum JSF SelectOne
Many to One Association your Class JSF SelectOne
Double Double deprecated - use Decimal, Currency, or Percentage
Long Long deprecated - use Integer



JPA Utilities

  • Cleanup Associations
    • For each association, default the mappedBy and cascade properties
  • Add Embedded Stereotypes
  • Add Temporal Stereotypes
    • For each property of type Date, Time, or Timestamp add the stereotype and set the value accordingly.
  • Add Enumeration Stereotypes
    • For each property with an Enumeration type add the stereotype and set the value to STRING
  • Add Index Stereotype to ManyToOne Properties
  • Add Join Table Stereotypes
  • Switch Inheritance Types
  • Switch Id Generators
  • Add Table Stereotypes
  • Add Column Stereotypes
  • Add Attribute Override Stereotypes


Unit Tests

From Taylor

Three types of JUnit tests are generated: Service, Seam, and JasperReports.


Seam

A Seam junit test is generated in the Ejb3 project for each entity. These tests verify that the Finder and Editor SFSBs and the Facelets expressions (EL) are working properly.

  • You might need to tweak the default values for properties.
  • Association tests are also not generated.

Possible Compilation Errors

After generating the code and setting up the classpath you may notice that some of the code might have compile errors. This could happen for several reasons:

  1. Something might be missing from the model. Fix the model and regenerate.
  2. Various TreeNode and EditorBean methods assume there is a property called 'name' that is used for display. Change these to the property you would like to display.
    1. For example, in the tutorial the Ticket entity has a 'title' property instead of a 'name' property.
  3. You added an Interceptor from a third party that needs to be added to the Maven pom.xml dependencies section. Or you added an Interceptor that you need to implement.
  4. The session bean operations need to be implemented because they did not match one of the default implementations: save, get, delete, query.
  5. You defined a operation named query that does not match the default signature. See below.

This is the default signature for operations named query. You will want to define more specialized query operations for the service, but using this signature is a good way to get a prototype up and running quickly. So, either change the model or implement the query as you see fit. Another good option is to use the NamedQuery stereotype to define your queries. It is a good practice to name these the same as the operation that will use them.

 
public List query(SomeEntity example, Long first, Long max, String orderBy) {
}





Facelets Customization


The generated facelets are meant to be customized. Generating an
Entity bean is very straight forward because there are well defined
rules and only so many variations. On the other hand, the user
interface is the place where different applications can differentiate
themselves.

To this end, the generated facelets are meant to give you a jump start. The following sections outline possible modifications.


Editor


For the most part the UI can be customized by making changes to the EditorBeans.


  • Implement isEditable()
  • Change the various isRendered methods
  • Implement isRendered(String name) and isDisabled(String name) to control individual fields
  • Modify Many2One and Many2Many association methods to change
    what fields are displayed and add filters. See TODO tags placed in the
    code.
  • Change createInstance() to initialize properties.
  • Add additional actions like submit() and schedule(). Examples have been generated.

Finder


  • getSearchFields()
  • Add Chart methods

Menus


The default-object.xml file defines how pages will be displayed in
JBoss Portal. You will probably want to add and remove pages from this
file. Alternatively, you can do this online in JBoss Portal.

You can also create additional *-object.xml files.


UI Facelets


This is were you might make the most changes, such as rearranging fields, changing input types, and adding buttons.

The Facelets use the standard Portlet CSS Styles, so you can accomplish a lot by changing the Portal Theme.

Facelets templates and tags are leveraged also. When the
Web project is built for the first time the Taylor-Tags library will be
expanded into your project. You can then change the following files to
make global changes across your application:


  • webapp/web-inf/jsf/templates
  • webapp/web-inf/jsf/tags
  • webapp/web-inf/pdf/templates
  • webapp/web-inf/pdf/tags

Report Facelets


The generated Seam PDF files are just Facelets so the same things apply as for the UI facelets.



Seam Tests

Taylor Commons contains a port of the Seam TestNG libraries to JUnit. Seam junit tests are generated for each Entity in the model to test the generated CRUD Editor and FInder classes. You will need to tweak the default values for some fields like dates and enumerations.


Version Control

Check in the model, diagrams, and generated code and descriptors into your version control system. I typically generate the code, then tweak it enough to compile, and then check it in. Then I do any major modifications and check that in before iterating again through the model and regenerating.


Package and Deploy


Setup

  • Copy the necessary configuration files generated in your Ear project's jboss\deploy directory to the server\all\deploy directory.
    • For example, to setup a datasource copy tutorial-hsqldb-ds.xml
  • Setup the JBOSS_HOME system property to point to your JBoss installation
    • SET JBOSS_HOME=C:\jboss-4.2.0.GA

Build

  • Change directories to your master project run mvn clean install to clean, compile, test, package, and install all the sub-projects: jpa, ejb, web, pdf, app, doc, etc.

Deploy

  • The App project's pom.xml has the logic to copy the Ear file to your JBoss server.
  • Alternatively, you can still use the jboss-maven-plugin
    • Run mvn clean install jboss:harddeploy to deploy your Ear to JBoss.

Packaging

  • Run mvn site to generate the project website with javadoc, xref, and test reports.
  • Run mvn assembly:assembly to package everything into zip and tar files.


Other Useful Maven Plugins

The templates could be changed to generate some of these:

Reports

Packaging


Customize Code Templates


Templates can be overridden by placing a new version in the directory you specify under Window/Preferences/Taylor. This is useful for overriding the copy right Header template or for fixing template bugs. The templates are found in plug-ins such as net.taylor.mda.ejb3gen.

I typically do the following:

  1. Create a templates folder next to the model folder.
  2. Set the preferences to point to this folder.
  3. Create a Header.jetinc file in this folder.
  4. Check in the custom template so everyone else has access.
  5. As the project progresses we will put additional customized templates here as well. NOTE: The path has to match the path specified in the particular plugin.xml file so that the engine finds them.

Custom Plugins

Additional templates can be added by placing them in your own plugin and adding the following extension point to its plugin.xml.





Additional information can be found under Architecture.

A good JET Template Editor can be found at http://www.eclipse.org/emft/projects/jeteditor/

Anotaciones EJB3

Anotaciones en EJB 3.0

http://www.adictosaltrabajo.com/tutoriales/tutoriales.php?pagina=AnotacionesEJB3


API de Persistencia: EntityManager

Primero veremos algunas partes importantes de la API, como la interfaz EntityManager. Esta interfaz es en la que se apoya la API de persistencia y la que se encarga del mapeo entre una tabla relacional y su objeto Java. Funcionalmente es similar a la clase Session de Hibernate o a PersistenceManager de JDO. Proporciona mé;todos para manejar la persistencia de un Bean de Entidad, permite añadir, eliminar, actualizar y consultar así como manejar su ciclo de vida. Sus métodos má;s importantes son:

  • persist(Object entity) - almacena el objeto entity en la base de datos.

  • merge(T entity) - actualiza las modificaciones en la entidad devolviendo la lista resultante.

  • remove(Object entity) - elima la entidad.

  • find(Class entity, Object primaryKey) - busca la entidad a través de su clave primaria.

  • flush() - sincroniza las entidades con el contenido de la base de datos.

  • refresh(Object entity) - refresca el estado de la entidad con su contenido en la base de datos.

  • createQuery(String query) - Crea una query utilizando el lenguaje JPQL.

  • createNativeQuery() - Crea una query utilizando el lenguaje SQL.

  • isOpen() - Comprueba si está; abierto el EntityManager.

  • close() - Cierra el EntityManager.

Podemos obtener una referencia al EntityManager a través de la anotación @PersistenceContext. El contenedor de EJB nos proporciona el contexto de persistencia mediante inyección por lo que no tendremos que preocuparnos de su creación y destrucción.

@PersistenceContext
EntityManager entityManager;

Otra forma de obtener un EntityManager es a través de la factoría EntityManagerFactory con el nombre del contexto de persistencia configurado en el persistence.xml .


EntityManagerFactory emf = Persistence.createEntityManagerFactory("TestPersistence");
EntityManager em = emf.createEntityManager();

En el método createEntityManagerFactory de la clase Persistence se debe pasar el nombre del contexto definido en el persistence.xml .



Ciclo de vida de una Entidad

Engloba dos aspectos: la relación entre el objeto Entidad y su contexto a persistir y por otro lado la sincronización de su estado con la base de datos. Para realizar estas operaciones la Entidad puede encontrarse en cualquiera de estos cuatro estados:

  • new - Nueva instancia de la Entidad en memoria sin que aún le sea asignado su contexto persistente almacenado en la tabla de la base de datos.

  • managed - La Entidad dispone de contenido asociado con el de la tabla de la base de datos debido a que se utilizó el método persist(). Los cambios que se produzcan en la Entidad se podrá;n sincronizar con los de la base de datos llamando al método flush().

  • detached - La Entidad se ha quedado sin su contenido persistente. Es necesario utilizar el método merge() para actualizarla.

  • removed - Estado después de llamarse al método remove() y el contenido de la Entidad será; eliminado de la base de datos.


Anotaciones de un Bean de Entidad

@Entity: Indica que es un Bean de Entidad.

  • name - por defecto el nombre de la clase pero se puede especificar otra diferente.

Métodos del ciclo de vida de una Entidad

@EntityListeners: Se pueden definir clases oyentes (listeners) con métodos de ciclo de vida de una entidad. Para hacer referencia a un listener se debe incluir esta anotación seguido entre paréntesis de la clase: @Entity Listeners(MyListener.class)

@ExcludeSuperclassListeners: Indica que ningún listener de la superclase será; invocado por la entidad ni por ninguna de sus subclases.

@ExcludeDefaultListeners: Indica que ningún listener por defecto será; invocado por esta clase ni por ninguna de sus subclases.

@PrePersist: El método se llamará; justo antes de la persistencia del objeto. Podría ser necesario para asignarle la clave primaria a la entidad a persistir en base de datos.

@PostPersist: El método se llamará; después de la persistencia del objeto.

@PreRemove: El método se llamará; antes de que la entidad sea eliminada.

@PostRemove: El método se llamará; después de eliminar la entidad de la base de datos.

@PreUpdate: El método se llamará; antes de que una entidad sea actualizada en base de datos.

@PostUpdate: El método se llamará; después de que la entidad sea actualizada.

@PostLoad: El método se llamará; después de que los campos de la entidad sean cargados con los valores de su entidad correspondiente de la base de datos. Se suele utilizar para inicializar valores no persistidos.

@FlushMode: Modo en que se ejecuta la transacción: FlushModeType.AUTO (por defecto) y FlushModeType.COMMIT.

@NamedQuery: Especifica el nombre del objeto query utilizado junto a EntityManager.

  • name - nombre del objeto query.

  • query - especifica la query a la base de datos mediante lenguaje Java Persistence Query Language (JPQL)

@NamedQueries: Especifica varias queries como la anterior.

@NamedNativeQuery: Especifica el nombre de una query SQL normal.

  • name - nombre del objeto query.

  • query - especifica la query a la base de datos.

  • resultClass - clase del objeto resultado de la ejecución de la query.

  • resultSetMapping - nombre del SQLResultSetMapping definido (se explica má;s abajo).

@NamedNaviteQueries: Especifica varias queries SQL.

@SQLResultSetMapping: Permite recoger el resultado de una query SQL.

  • name - nombre del objeto asignado al mapeo.

  • EntityResult[] entities() - entidades especificadas para el mapeo de los datos.

  • ColumnResult[] columns() - columnas de la tabla para el mapeo de los datos.

@NamedNativeQuery(name="nativeResult", query="SELECT NOMBRE,APELLIDOS FROM USUARIOS WHERE USUARIO_ID= 123", resultSetMapping = "usuarioNamedMapping")

@SqlResultSetMapping(name="usuarioNamedMapping",
entities = {

@EntityResult(entityClass = com.autentia.entidades.Usuario.class,
fields = {

@ColumnResult(name="usuarioId", column="USUARIO_ID"),

@ColumnResult(name="nombre", column="NOMBRE"),
@ColumnResult(name="apellidos", column="APELLIDOS")})})

@PersistenceContext: Objeto de la clase EntityManager que nos proporciona todo lo que necesitamos para manejar la persistencia.

  • name - nombre del objeto utilizado para la persistencia en caso de ser diferente al de la clase donde se incluye la anotación.

  • unitName - identifica la unidad de la persistencia usada en el bean en caso de que hubiera má;s de una.

  • type - tipo de persistencia, TRANSACTION (por defecto) | EXTENDED.

@PersistenceContexts: Define varios contextos de persistencia.

@PersistenceUnit: Indica la dependencia de una EntityManagerFactory definida en el archivo persistence.xml.

  • name - nombre del objeto utilizado para la persistencia en caso de ser diferente al de la clase donde se incluye la anotación.

  • unitName - identifica la unidad de la persistencia usada en el bean en caso de que hubiera má;s de una.


@Lob: Se utiliza junto con la anotación @Basic para indicar que un campo se debe persistir como un campo de texto largo si la base de datos soporta este tipo.



14 abril 2009

@Transactional

seam_reference-2.1.1.GA.pdf line 525 (search for '@Transactional')

30.5. Annotations for use with Seam JavaBean
components in a J2EE environment
Seam provides an annotation that lets you force a rollback of the JTA transaction for certain action
listener outcomes.
@Transactional
@Transactional
Specifies that a JavaBean component should have a similar transactional behavior to the
default behavior of a session bean component. ie. method invocations should take place in
a transaction, and if no transaction exists when the method is called, a transaction will be
started just for that method. This annotation may be applied at either class or method level.
Do not use this annotation on EJB 3.0 components, use @TransactionAttribute!
@ApplicationException
@ApplicationException
Synonym for javax.ejb.ApplicationException, for use in a pre Java EE 5 environment. Applied
to an exception to denote that it is an application exception and should be reported to the
client directly(i.e., unwrapped).
Do not use this annotation on EJB 3.0 components, use
@javax.ejb.ApplicationException instead.
• rollback — by default false, if true this exception should set the transaction to rollback
only

seam transaction

D:\Development\TOOLS_HOME\taylor\svn\components\branches\taylor-components-1.2.0\taylor-commons\src\test\java\net\taylor\conv\ConversionTest.java

protected void persist(EntityManager em) {
SampleEntity e = new SampleEntity();
e.setName("e1");
e.setType(Type.A);
em.persist(e);

e = new SampleEntity();
e.setName("e2");
// e.setType(Type.A);
em.persist(e);

e = new SampleEntity();
e.setName("e3");
// e.setType(Type.A);
em.persist(e);
}

seam transaction

D:\Development\TOOLS_HOME\taylor\svn\applications\branches\taylor-tracker-1.2.0\ejb\src\main\java\net\taylor\tracker\web\TransactionScript.java

public Object run() {
try {
EntityManagerFactory emf = (EntityManagerFactory) lookup(persistenceUnitJndiName);
EntityManager em = emf.createEntityManager();
UserTransaction t = (UserTransaction) lookup("UserTransaction");
try {
t.begin();
em.joinTransaction();
Object o = persist(em);// do the work
em.flush();
t.commit();
return o;
} catch (Exception e) {
t.rollback();
throw e;
} finally {
em.close();
}
} catch (Exception x) {
throw new RuntimeException(x);
}
}
D:\Development\TOOLS_HOME\taylor\svn\applications\branches\taylor-tracker-1.2.0\ejb\src\main\java\net\taylor\tracker\TrackerInit.java


protected void addGroup(String id, String name, String description) {
Group group = identityEntityManager.find(Group.class, id);
if (group == null) {
group = new Group();
group.setId(id);
group.setName(name);
group.setDescription(description);
identityEntityManager.persist(group);
}
}
D:\Development\TOOLS_HOME\taylor\svn\applications\branches\taylor-tracker-1.1.0\ejb\src\main\java\net\taylor\tracker\web\TransactionScript.java

try {
EntityManagerFactory emf = (EntityManagerFactory) lookup(persistenceUnitJndiName);
EntityManager em = emf.createEntityManager();
UserTransaction t = (UserTransaction) lookup("UserTransaction");
try {
t.begin();
em.joinTransaction();
Object o = persist(em);// do the work
em.flush();
t.commit();
return o;
} catch (Exception e) {
t.rollback();
throw e;
} finally {
em.close();
}

07 abril 2009

Definitivo ejemplo de @ApplicationException

En el ejemplo dvdstore, hay un @ApplicationException en CheckoutAction.
Está en el método submitOrder(), que tiene un @End.

Dependiendo de cierta condición lanza una InsufficientQuantityException o hace el persist:

em.persist(order);

dvdstore

el proyecto dvdstore ear de los project examples funciona en jboss 4.2, con el seam eap 2.0 de jbstudio y añadiendo a mano el ds.xml

06 abril 2009

maven2 embedded dependencies



org.jboss.embedded
hibernate-all
beta3
jar
compile


org.jboss.seam.embedded
jboss-embedded-all
beta3
jar
compile


org.jboss.seam.embedded
thirdparty-all
beta3
jar
compile

02 abril 2009

Bean-managed transactions (BMT)

Bean-managed transactions (BMT)—Developers should use bean-managed
transactions in order to have a finer-grained control over their transactional
system. For instance, with BMT beans, you can create more than one trans-
action per bean method (see recipe 5.9). A BMT bean is responsible for cre-
ating, propagating, committing, and rolling back its transactions. By not
relying on the container, the bean developer must face the sometimes
daunting task of coordinating a transactional system. EJB applications that
use BMT beans can be every bit as secure and reliable as CMT applications,
but there is a larger chance of developer-introduced transactional errors. In
most cases, the EJB container is sufficient for enterprise applications’ trans-
action management.