Persistence API (JPA) series (iii) Development techniques for entity beans-recommended connection to the database

Source: Internet
Author: User
Tags jboss jboss server java se

In EJB 2.x, EJB has 3 types of beans, namely session bean, message-driven bean (Message-driven Bean), and entity bean.

with the introduction of EJB 3, Entity beans in EJB2.x are gradually replaced by the JPA specification, which can be used not only in EJB environments, but also in Java SE, Java EE environments , relative to entity beans in EJB 2.x , it has a wider range of uses.

But here we still call it the entity bean.


Similar to session beans and message-driven beans, the new entity Bean is also a simple Java object (POJO) with an annotated identifier (@Entity), and the entity relationship and O/R mappings are also defined by annotations and provide several different database operating specifications.

Once accessed by Entitymanager, it becomes a persistent object and becomes part of the persistence context. At this point we can use the entity object just like Hibernate, IBATIS, MyBatis.

This article will explain in detail the development technology of entity bean.

1. Establish a connection with the database, and demonstrate the development and invocation process of the entity bean.
2. Entity Manager: How to perform database updates.
3. Life cycle: Monitoring and callback of entity Bean.
4. Relational entity mapping: Methods for developing entities.
5, JPQL Query Language: Execute database entity query.
6. Native SQL query: executes native SQL statement.


The relationships between them, by manipulating entity beans through the Entity Manager, are implemented to update the database, JPQL queries, and native SQL queries. The Entity Manager is the tool, and the entity bean is the data.

The following first explains the call procedure for the entity bean, and then demonstrates the configuration and development process by developing the first entity bean, including the following:

1. Configure the data source.
2. Specify the data source.
3, the development of the first entity Bean--student.java.
4. The development session Bean is called--studentdaoremote.java and Studentdao.java.
5. Package and deploy to the JBoss server.
6, the development of the client to test--studentdaoclient.java.


Finally, a record is inserted into the data table through the establishment of the entity bean and the connection to the MySQL database.

first, how the entity bean worksThe entity Bean is managed as a persisted class by the EJB container, and the following steps must be taken to implement the call to the persisted class.
(1) Configure the data source connection.
(2) Specify the data source in the configuration file Persistence.xml.
(3) Developing entity beans.
(4) Call the entity Bean in the session bean, Java SE, or Java EE.

The entity Bean can be called not only by the session bean, but also by any Java class, JSP, and servlet, and is invoked to implement operations on the database. Its meaning is exactly the same as Hibernate and Ibatis, which is the DAO layer of the system, which realizes access to the database.
Here we demonstrate the process of creating a connection to a database, in order from the bottom to the top.

Second, configure the data sourceThe data source configuration template can be found in the \jboss-eap-6.2.0\jboss-eap-6.2\docs\examples\configs directory.
</pre>

It contains 3 configuration elements, as follows:

persistence-unit element : can have one or more, each persistence-unit element defines the persisted content name, the data source name used, and the Hibernate property. Where the Name property is used to set the persisted name.
jta-data-source element : Used to specify the data source name Ksmysqlds used by the entity bean, the java:/prefix cannot be missing when specifying the data source name, and note the case of the data source name.
Properties element : Used to specify the attributes of hibernate, and if the value of Hibernate.hbm2ddl.auto is set to update, the entity bean can add an attribute to the data table while adding the corresponding field.

(1) Properties element attributes are different in persistent products used by each application server, such as JBoss using HIBERNATE,WEBLOGIC10 Kodo,glassfish/sun application server/ Oralce use TopLink.
(2) When the JBoss server starts or shuts down, it causes the publication and uninstallation of the entity bean.
Iv. Development of the first entity The entity bean actually corresponds to the table in the database, which is the representation of the table in the database in the Java class, usually the most common Pojo class. The EJB container is able to automatically create data tables in the database based on the entity Bean, which needs to correspond to the structure of the data table, including table name, field name, field length, field type, primary key, and other information.
To develop a single-table entity bean corresponding to a database table, we first design a data structure for the Student table student, which consists of 7 fields, as shown in the table.

    The field type corresponds to the field type in the MySQL database, and the Java type is the field type in the corresponding Pojo class, which is the variable type in the entity bean.
To develop an entity bean corresponding to the table is simple, just create a new Pojo class, add 7 variables with the same name as the table field, and use some annotations to represent the corresponding mapping of the entity bean to the data table student.
Bean class Student.java. First, let's look at the code for this complete entity class, as follows:

Entity Bean Class Student.java
Package Com.ejb.entitybean;  Import java.io.Serializable;  Import Java.util.Date;  Import Javax.persistence.Column;  Import javax.persistence.Entity;  Import Javax.persistence.GeneratedValue;  Import Javax.persistence.Id;   Import javax.persistence.Table;  @SuppressWarnings ("Serial") @Entity @Table (name = "Student") public class Student implements Serializable {private      Integer StudentID;        Study number private String name;            Name private Boolean sex;          Gender private short age;      Age private Date Birthday;     Date of birth private String address;          Address private String telephone//Phone @Id @GeneratedValue public Integer Getstudentid () {      return studentid;      } public void Setstudentid (Integer studentid) {this.studentid = StudentID;      } @Column (name = "Name", length =) public String getName () {return name; } public void SetName (String name) {This. name = name;      } @Column (nullable = False) public Boolean getsex () {return sex;      public void Setsex (Boolean sex) {this.sex = sex;      } @Column (nullable = false) public short getage () {return age;      public void Setage (short age) {this.age = age;      Public Date Getbirthday () {return birthday;      } public void Setbirthday (Date birthday) {this.birthday = birthday;      } @Column (name = "Address", length = +) public String getaddress () {return address;      The public void setaddress (String address) {this.address = address;      } @Column (name = "Telephone", length =) public String Gettelephone () {return telephone;      } public void Settelephone (String telephone) {this.telephone = telephone;  }  }

an entity bean usually needs to implement the serializable interface so that an EJB client can create the object and deliver the object to the server, otherwise the java.io.InvalidClassException exception will be thrown.
The class is a Java Pojo class that contains 7 variables and adds a getter/setter function for each variable. In order to represent the Pojo class as an entity bean, some annotations have been added to correspond to the data table student, which are as follows.
@Entity Note indicates that this is an entity bean, and each entity Bean class maps a table in the database.
The Name property of the @Table note specifies the mapped data table names, and the data table for the Student class map is student.
@Column Note defines all the properties that are mapped to a column, such as whether the column name is unique, whether it is allowed to be empty, whether updates are allowed, and so on, its properties are described below.
Name: The column name of the map. If you map the name column of the student table, you can add @column (name = "name") above the GetName () method of the Name property, and if you do not specify a mapping column name, the container will use the property name as the default mapping column name.
Unique: is unique.
Nullable: null is allowed.
Length: For the character column, the length property specifies the maximum number of characters for the column.
Insertable: whether to allow insertion.
Updatable: Whether to allow updates.
ColumnDefinition: Defines the DDL that creates this column when the table is built.
Secondarytable: From the table name. If this column is not built on the primary table (which is built by default on the main table), this property defines the name of the table from which the column resides.
@Lob Note Specifies that a field is a large text field type.
@Id Note Specifies that the StudentID property is the primary key for the table.
@GeneratedValue Note defines how the identity field is generated, and the value of StudentID in this example is automatically generated by the MySQL database, which can be generated in several ways.
Table: container Specifies that the underlying data table is unique.
SEQUENCE: Use the SEQUENCE column of the database to guarantee uniqueness.
IDENTITY: Use the indentit column of the database to guarantee uniqueness.
AUTO: The container chooses a suitable way to guarantee the uniqueness.
NONE: The container is not responsible for generating the primary key, which is done by the calling program.

For example:
@Id @GeneratedValue (strategy = generationtype.identity) public  Integer getId () {      return this.id;  }
This is the end of the development of the entity Bean, which, in addition to adding some annotations on the Pojo, is no different from the ordinary Pojo class.
v. Developing a session bean for invocation1. The development session Bean is called--studentdaoremote.java and Studentdao.java.
Let's develop a remote session bean component by calling the entity Bean Class Student.java to insert a record into the data table student.
Create a new package Com.ejb.dao in the project Entitybeantest, and then create a new remote session bean component in the package based on the session bean development method Studentdao, which will result in a remote interface class Studentdaoremote.java and implementation Class Studentdao.java.

1) Remote interface class Studentdaoremote.javaidentified by the @remote of the annotation character. function Insert ()perform the Insert student functionremote Interface class Studentdaoremote.java
<span style= "Font-weight:normal;" >package Com.ejb.dao;   Import java.util.List;  Import Javax.ejb.Remote;  Import com.ejb.entitybean.Student;   @Remote public interface Studentdaoremote {public      boolean insert (Student Student);  </span>
2) Implement class Studentdao.java
The remote interface Studentdaoremote.java is implemented and is identified as a stateless session bean by @stateless.
First it contains a variable of type Entitymanager Em,entitymanager is the entity manager, as the name implies, it is the management container of the entity bean. Through this object, we can achieve various interactions with the database, including adding, deleting, changing, checking and so on.
The entity variable em also realizes the dynamic injection of Entitymanager object by annotation @persistencecontext, If several different persisted content is configured in the Persistence.xml file, you also need to specify the persisted name injection Entitymanager object, which can be specified by @persistencecontext the Unitname property of the annotation, for example:
@PersistenceContext (unitname= "exam-entity")  
If there is only one persisted content configuration, no explicit designation is required.
Then develop this class to implement the function insert () in the interface, only need to call the EM persist () function, you can persist the student object into the database, that is, a new record in the database.
Implementing Class Studentdao.java
Package Com.ejb.dao;   Import java.util.List;  Import javax.ejb.Stateless;  Import Javax.persistence.EntityManager;  Import Javax.persistence.PersistenceContext;  Import Javax.persistence.Query;  Import com.ejb.entitybean.Student;   @Stateless public class Studentdao implements Studentdaoremote {      @PersistenceContext     protected Entitymanager em;       public boolean insert (Student Student) {          try {              em.persist (Student);          } catch (Exception e) {              E.printstacktrace ();              return false;          }          return true;      }  }

six, packaged and deployed to the JBoss serverinto a jar package and deploy to the JBoss server, the JBoss server will automatically load the service. The Jndi service is formed for external access. the publishing process is as follows:
1. Load the Persistence.xml file. 2, create the database table student, when you view the MySQL database will see the new table student. 3, publish Jndi service Studentdao/remote.
This allows us to access the Jndi service Studentdao/remote through the client.
Vii. developing the client for testing-studentdaoclient.java developing the client for testing--studentdaoclient.javaabove we developed the entity bean and Session bean component and published it to the JBoss server, let's develop a Java client program, create an entity object in the client, and then invoke the session bean component to insert the object and insert a record into the data table.
First add the entity class Student.java and the interface class Studentdaoremote.java copy to the corresponding package in the test project Ejbtestjava, and then create a new test class
Test class Studentdaoclient.java
Import java.text.ParseException;  Import Java.text.SimpleDateFormat;   Import java.util.Properties;  Import Javax.naming.InitialContext;   Import javax.naming.NamingException;  Import Com.ejb.dao.StudentDAORemote;   Import com.ejb.entitybean.Student; public class Studentdaoclient {public static void main (string[] args) throws namingexception {Properties P          Rops = new Properties ();          Props.setproperty ("Java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");          Props.setproperty ("Java.naming.provider.url", "localhost:1099");          Props.setproperty ("java.naming.factory.url.pkgs", "org.jboss.naming");              try {initialcontext ctx = new InitialContext (props);                            Studentdaoremote Studentdao = (studentdaoremote) ctx.lookup ("Studentdao/remote");              Student Student = new Student ();              Student.setname ("Liuzhong soldiers");              Student.setsex (TRUE); Student.setaGE ((short) 25);              SimpleDateFormat format = new SimpleDateFormat ("Yyyy-mm-dd");              Student.setbirthday (Format.parse ("1981-05-04"));              Student.settelephone ("12345678");                            Student.setaddress ("Beijing");              Studentdao.insert (student); System.out.println ("A student record has been inserted!                        ");          } catch (Namingexception e) {e.printstacktrace ();          } catch (ParseException e) {e.printstacktrace ();  }      }  }
This class obtains the remote session Bean instance Studentdao by accessing the remote Jndi service studentdao/remote. A student entity object is then created, and the insert () function is called into the object. After you run the program, the following information is printed in the console:
A student record has been inserted!
This indicates that the Java class of the client has correctly committed the student object to the remote session bean component. After the first load, the entity Bean object has been cached by the entity manager Entitymanager, and when accessed again, the entity object is taken directly from the cache.

Persistence API (JPA) series (iii) Development techniques for entity beans-recommended connection to the database

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.