Java ee5 series-Java persistence API 1.0 (ejb3 entity bean)

Source: Internet
Author: User
Java ee5, as the specification of the next-generation Java Enterprise Development Platform, has attracted the attention of the entire Java Development Community since its design. It has aroused numerous debates and raised numerous expectations. Java ee5, nearly six years after its birth as a J2EE platform, focuses on several hot topics in Java Development: development efficiency, operation efficiency, and enterprise application integration. The goal is to make J2EE development simple and simple. Let's take a look at what j2ee5 specifications are. Can they bring real benefits to developers/enterprises?

The Java ee5 specification is a so-called umbrella specification. It is a series of sub-specifications, including:

EJB 3.0 (JSR 220)
Java persistence API 1.0 (JSR 220)
JSP 2.1 (JSR 245)
JSF 1.2 (JSR 252)
JAX-WS 2.0 (JSR 224)
Stax 1.0 (JSR 173)
Jaxb 2.0 (JSR 222)
Web Services annotations 1.0 (JSR 181)
Common annotations 1.0 (JSR 250)
SAAJ 1.3 Maintenance
JTA 1.1 Maintenance
Javamail 1.4 & JAF 1.1 Maintenance
Jstl 1.2 Maintenance
Java ee mgmt Maintenance
Jacc Maintenance
Servlet Maintenance
Java EE deployment Maintenance
Wsee Maintenance

Java persistence API 1.0 (ejb3 entity bean) in Java ee5, Entity Bean, as the persistent component in the EJB specification, will gradually become a historical term, entity beans, which are the most prevalent in the J2EE 4 specification, were pushed back in Java ee5 and replaced by Java-developed general persistence specification Java persistence API 1.0, actually, the Entity Bean specification is completely redefined (for many occasions, we still use ejb3 persistence for historical reasons ). As a Java component responsible for link data persistence, JPA has become a separate specification, instead of Enterprise Java Bean (EJB is more about stateless/stateful Session Bean and message driven bean ).

Java persistence AP (JPA) is a collection of Java Persistence Technologies. It draws on excellent technologies and frameworks such as hiberante, JDO, and toplink, the pojo-based o/R Mapping technology developed over the past few years has been standardized to become a Java persistent API that is used in J2EE and j2se environments. It is worth noting that the Java persistence API is not dedicated to the J2EE environment, but a General API in Java. This means that we can use JPA wherever we need to access relational databases, and even desktop applications developed by swing. JPA does not need to run in a J2EE container, but can be used in any JVM environment. This makes it easy to combine JPA as a persistent component freely with various containers/frameworks (ejb3 containers, spring, etc.

How does JPA simplify the development of Entity Bean in ejb2? Let's look at a simple comparison:

  Ejb2.0 Ejb3.0 (JPA)
Business Interface
public inerface HelloWold extends EJBLocalObject{    Public String getResult();}
No interface needs to be defined
Ing configuration file Compile ejb3 deployment descriptor Optional
EJB implementation
public class HelloWorldEntityBean          implements HelloWold, EntityBean{    private int id;    private String result;    private EntityContext txt;       public HelloWorldEntityBean(){}    public void setEntityContext( EntityContext text ){         txt = text;    }       public String getResult(){         Return result;     }            public int getId(){        return id;     }        public void setResult( String result ){         this.result = result;    }        public String cretaeByName( String name ) throws EJBException{        .....    }    }
@Entity@Table(name=”hellotable”)public class HelloWoldEntity{       @Id    private int id; p    private String result;         public HelloWoldEntity(){}         public String getResult(){         return result;    }        public int getId(){        return id;    }          public void setResult( String result ){         this.result = result;    }}

In JPA, the Entity Bean Of ejb3 is a simple Java Bean, that is, pojo (plain old Java object ). Unlike the entitybean in ejb2, which must be closely related to the container (entitycontext must exist in ejb2), The entitybean in ejb3 has nothing to do with the container. In fact, in JPA, entitybean is no longer called entitybean, but entity, it is different from the existing EJB of Session Bean/message driven bean.

To simplify the O/R Mapping configuration, JPA uses the most important new feature annotaion of jdk1.5 to directly label the configuration in Java code. The o/R Mapping configuration marked with annotation can greatly reduce the O/R mapping workload configured with XML in the past, and improve efficiency and maintainability.

The following is a simple one-to-one association using annotation and xml configuration comparison.

  Java persistence API (ejb3 persistence) Hiberante
Configuration File Optional Yes
One-to-one Configuration Optional
<one-to-one            name="address"            class="com.foo.Address"            cascade="All"            lazy="false"/>
Java code
public class Order{     @OneToOne(cascade=CascadeType.ALL,fetch=FetchType.LAZYL)    Address address;    ......}
public class Order{        Address address;    ......   }

Annotation has the following advantages:

  • This reduces the number of configuration files, especially in systems with a large number of entities. Maintaining a large number of O/R Mapping xml configuration files is a lot of work.
  • This reduces the content to be marked for configuration. Since annotation is compiled and parsed by Java compiler, a lot of explicitly declared content in xml configuration is no longer needed (such as the variable name, type, object type in the set ).
  • The compilation check of annotation can avoid configuration syntax errors in XML files and promptly detect and correct the errors in IDE.
  • There is no need to switch between the xml configuration file and Java code, and there is little thought Skip, which improves the development efficiency.
  • Annotation is compiled into Java bytecode, omitting the XML parsing process, greatly improving the application startup speed and memory usage (especially when there are many entity instances ).

JPA is much simplified at startup, so that we can easily use JPA in the container (container) and j2se environments. JPA has a basic factory class entitymanagerfactory. You can call the createentitymanager () method of the factory class to obtain the entitymanager. All operations on entities, including persistence, query, and deletion, are defined on entitymanager.

public interface EntityManager {    public void persist(Object entity);    public 
  T merge(T entity);    public void remove(Object entity);    public 
  T find(Class
  entityClass, Object primaryKey);    public 
  T getReference(Class
  entityClass, Object primaryKey);    public void flush();    public void setFlushMode(FlushModeType flushMode);    public FlushModeType getFlushMode();    public void lock(Object entity, LockModeType lockMode);    public void refresh(Object entity);    public void clear();    public boolean contains(Object entity);    public Query createQuery(String ejbqlString);    public Query createNamedQuery(String name);    public Query createNativeQuery(String sqlString);    public Query createNativeQuery(String sqlString, Class result-    Class);    public Query createNativeQuery(String sqlString, String result-    SetMapping);    public void close();    public boolean isOpen();    public EntityTransaction getTransaction();}

Then how can we get entitymanagerfactory? Whether in J2EE or j2se, you must use a persistence. xml configuration file to configure entitymangaerfactory. The following is a simple example of persistence. xml.

<entity-manager>    <name>myEntityManager>/name>    <provider>com.redsoft.ejb3.PersistenceProviderImpl>/provider>    <class>com.redsoft.samples.HelloEntityBean>/class>    <properties>        <property name="ConnectionDriverName" value="com.mysql.jdbc.Driver"/>        <property name="ConnectionURL" value="jdbc:mysql://localhost/EJB3Test"/>        <property name="ConnectionUserName" value="ejb3"/>        <property name="ConnectionPassword" value="ejb3"/>   >/properties></entity-manager>

Name-specifies the name of the current entitymangaerfactory. We can define multiple entitymanagerfactory in a persistence. xml file.

Provider-specifies the implementation class that provides entitymanagerfactory. This implementation class is provided by different persistence product developers. In this example, the entitymanagerfactory implementation class of ejb3 persistence implementation in China redworks is used. If we need to replace the product with another manufacturer, we need to replace the specific implementation class.

Class-list all entity classes to be managed by JPA. To ensure versatility and portability in j2se/J2EE, JPA requires that all entity classes managed by JPA be listed here.

Properties-attributes defined by the persistence vendor.

If you use a JTA transaction, you can also use <JTA-data-source> mydatasource </JTA-data-source> to define the connection pool.

In the J2EE container environment and j2se environment, entitymangaerfactory is initialized by reading this configuration file. In the J2EE container environment, the ejb3 container is responsible for reading persistence. XML, initializing entitymanagerfactory, and helping entitymanagerfactory to jdni. In this way, we can access JNDI to obtain entitymanagerfactory and entitymanager. Because ejb3 containers support the IOC mode, we can also use IOC to inject entitymangerfactory directly to the required Java class using JPA persistence. Using IOC injection to obtain entitymanagerfactory or entitymanager is more convenient, reasonable, and recommended.

In the j2se environment, we can obtain entitymanagerfactory through the standard javax. Persistence. Persistence class. Javax. Persistence. Persistence searches for and reads persistence. xml in the META-INF/of the current classpath or jar package and initializes entitymanagerfactory.

The following is a simple example of how to obtain entitymanagerfactory and entitymanager in j2se environment, and use entitymanager to persistently helloworldentitybean.

public class HelloWorld {    public static void main( final String[] args ){        /*         * Obtain an EJB3 entity manager         */        final EntityManagerFactory emf = Persistence.createEntityManagerFactory();        final EntityManager entityManager = emf.createEntityManager();        // Construct a HelloEntityBean        final HelloEntityBean hello = new HelloEntityBean( 1, "foo" );        EntityTransaction trans = entityManager.getTransaction();        trans.begin();        entityManager.persist( hello );        trans.commit();        System.out.println( "Successfully persist hello: " + hello );        // Look up the HelloEntityBean by primarky key        final HelloEntityBean anotherHello = entityManager.find( HelloEntityBean.class, new Integer( hello.getId() ) );        System.out.println( "Found hello: " + anotherHello );        // close the EntityManager        entityManager.close();        emf.close();    }}

In fact, we can initialize entitymanagerfactory either in j2se or J2EE through javax. Persistence. Persistence.

In the preceding helloworld example, we need to explicitly call javax. Persistence. Persistence. createentitymanagerfactory, and start and close the transaction explicitly. In today's era when IOC is widely used to host containers, such encoding lags behind.

As a part of J2EE, JPA can naturally use ejb3's IOC container to host transaction and injection resources. Likewise, it can use the open source IOC container spring to host transaction and injection resources. Redworks also provides an open source spring Dao extension http://sourceforge.net/projects/ejb3daosupport to support the combination of JPA and spring.

The following is an example of how to host transactions in spring and inject entitymanager into Dao:

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "file://spring-beans.dtd"><beans><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"><property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property><property name="url"><value>jdbc:mysql://localhost/EJB3Test</value></property><property name="username"><value>ejb3</value></property><property name="password"><value>ejb3</value></property></bean><bean id="entityManagerFactory"class="org.springframework.orm.ejb3.LocalEntityManagerFactoryBean"><property name="persistenceInfo"><ref local="persistenceInfo"/></property></bean><bean id="persistenceInfo" class="com.redsoft.ejb3.PersistenceInfoImpl"><property name="nonJtaDataSource"><ref local="dataSource"/></property><property name="entityManagerName"><value>myEntityManager</value></property><property name="persistenceProviderClassName"><value>com.redsoft.ejb3.PersistenceProviderImpl</value></property><property name="entityClassNames"><list><value>com.redsoft.ejb3.spring.Child</value><value>com.redsoft.ejb3.spring.Father</value></list></property><property name="properties"><props><prop key="javax.jdo.PersistenceManagerFactoryClass">com.redsoft.jdo.PersistenceManagerFactoryImpl</prop></props></property></bean><bean id="transactionManager" class="org.springframework.orm.ejb3.EJB3TransactionManager"singleton="true"><property name="entityManagerFactory"><ref local="entityManagerFactory" /></property></bean><bean id="dao"class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"singleton="true"><property name="transactionManager"><ref local="transactionManager" /></property><property name="target"><bean class="com.redsoft.ejb3.spring.DAOImpl"><property name="entityManagerFactory"><ref local="entityManagerFactory" /></property></bean></property><property name="transactionAttributes"><props><prop key="save*">PROPAGATION_REQUIRED</prop><prop key="remove*">PROPAGATION_REQUIRED</prop><prop key="del*">PROPAGATION_REQUIRED</prop><prop key="update*">PROPAGATION_REQUIRED</prop><prop key="get*">PROPAGATION_REQUIRED,readOnly</prop><prop key="find*">PROPAGATION_REQUIRED,readOnly</prop><prop key="query*">PROPAGATION_REQUIRED,readOnly</prop></props></property></bean></beans>

The example in this article can be downloaded from the redworks home page http://www.redsoftfactory.com/chinese/index.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.