Persistence API (JPA) series (iii) development technology of Entity Bean-establish connection with database, jpabean
In EJB 2. in array x, EJB has three types of beans: Session Bean, Message-Driven Bean, and Entity Bean ).
With the launch of EJB 3, the Entity Bean in EJB2.x is gradually replaced by the JPA specification. JPA can be used not only in the EJB environment, but also in the Java SE and Java EE environments, compared with EJB 2. the Entity Bean in x, which is widely used.
But here we still name it as an entity Bean.
Similar to Session Bean and message-driven Bean, the new Entity Bean is also a simple Java object (POJO) with a annotator (@ Entity ), entity relationships and O/R ing are also defined by annotators and provide several different database operation specifications.
Once accessed by EntityManager, it becomes a persistent object and a part of the persistent context. Now we can use object like Hibernate, iBATIS, and MYBATIS.
This article describes in detail the development technology of entity beans.
1. Establish a connection with the database to demonstrate the development and calling process of the Entity Bean.
2. Entity Manager: The method for executing database updates.
3. lifecycle: listener and callback of the Entity Bean.
4. relational entity ing: Method for developing entities.
5. JPQL Query Language: queries database entities.
6. Native SQL query: Execute native SQL statements.
The relationship between them is implemented by operating the Entity Bean through the Entity Manager to update the database, JPQL query, and Native SQL query. Entity Manager is a tool and Entity Bean is data.
Next, we will first explain the calling process of the entity Bean, and then demonstrate 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. Develop the first entity Bean-Student. java.
4. Call the Development Session Bean -- StudentDAORemote. java and StudentDAO. java.
5. Package and deploy it on the JBoss server.
6. Test the development client-StudentDAOClient. java.
The final implementation is to establish a connection with the MySQL database through the Entity Bean and insert a record into the data table.
1. How object beans work entity beans are managed by EJB containers as persistence classes. To call this persistence class, follow these steps.
(1) configure the data source connection.
(2) Specify the data source in the configuration file persistence. xml.
(3) Develop the Entity Bean.
(4) Call the Entity Bean in Session Bean, Java SE, or Java EE.
Entity beans can be called not only by session beans, but also by any Java classes, JSP and Servlet. The purpose of the call is to perform database operations. It has the same meaning as Hibernate and iBATIS. It serves as the DAO layer of the system to access the database.
Next we will demonstrate the process of creating a connection to the database in the order from the bottom layer to the upper layer.
2. Configure the data source
Jndi-name: Specify the JNDI name.
Connection-url: database connection URL.
Driver: Database driver Class.
User-name: the username used to log on to the database.
Password: password used to log on to the database.
You only need to reference the data source by referencing the JNDI command KsMysqlDS. the reference method is very simple. You only need to specify the alias in persistence. xml.
3. Specify the data source-persistence. xmlThe data source configured above is loaded and managed by the JBoss server. to use these data sources, you also need to specify which data source to reference in our application. The reference method is simple, just add a configuration file persistence under the/project/META-INF directory of the application. xml, and specify the referenced data source JNDI name in the file. You can also set the relevant operation attributes of the data source.
Configuration File persistence. xml
It contains three configuration elements.
Persistence-unitElement: one or more persistence-unit elements define the persistent content name, data source name used, and Hibernate attributes. The name attribute is used to set the persistence name.
Jta-data-sourceElement: Specifies the data source name KsMysqlDS used by the Entity Bean. When specifying the data source name, the java:/prefix cannot be missing. Note that the data source name is case sensitive.
PropertiesElement: used to specify the attributes of Hibernate. If the value of hibernate. hbm2ddl. auto is set to update, the corresponding fields can be added to the data table when the object Bean adds an attribute.
(1) properties element attributes are different in the persistence products used by each Application Server. For example, JBoss uses Hibernate, WebLogic10 uses Kodo, and GlassFish/Sun Application Server/Oralce uses Toplink.
(2) When the JBoss server is started or shut down, publishing and uninstalling the Entity Bean will be triggered.
4. Develop the first entityThe Entity Bean actually corresponds to the tables in the database. It represents the tables in the database in the Java class, usually the most common POJO class. The EJB container can automatically create a data table in the database based on the object Bean. This requires that the object class correspond to the structure of the data table, including the table name, field name, field length, field type, primary key, and other information.
To develop a single table Entity Bean corresponding to the database table, we first design a student table student data structure, which contains seven fields, as shown in Table 6-1.
Student
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, that is, the variable type in the Entity Bean.
To develop an object Bean corresponding to the table, it is easy to create a POJO class and add seven variables with the same name as the table fields, you can also use some annotators to indicate the ing between the Entity Bean and the data table student.
Bean class Student. java. First, let's take a look at the complete entity class code, as shown below:
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; // Student ID private String name; // name private boolean sex; // gender private Short age; // age private Date birthday; // birth Date private String address; // address private String telephone // call @ Id @ GeneratedValue public Integer getStudentid () {return studentid;} public void setStudentid (Integer studentid) {this. studentid = studentid;} @ Column (name = "name", length = 50) 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 = 100) public String getAddress () {return address;} public void setAddress (String address) {this. address = address ;}@ Column (name = "telephone", length = 20) public String getTelephone () {return telephone;} public void setTelephone (String telephone) {this. telephone = telephone ;}}
The object Bean usually needs to implement the Serializable interface, so that an EJB client can create this object and send it to the server. Otherwise, the exception of java. io. InvalidClassException will be thrown.
This class is a Java POJO class, which contains 7 variables and adds the getter/setter function to each variable. To present the POJO class as an entity Bean, some annotators are added to correspond to the student data table. The annotations are as follows.
@ Entity annotation indicates that this is an Entity Bean, and each Entity Bean class maps to a table in the database.
@ Name attribute of Table comment specifies the name of the mapped data Table. The data Table mapped by the Student class is Student.
@ Column Comment defines all attributes mapped to a Column, such as whether the Column name is unique, whether it is allowed to be empty, and whether it is allowed to be updated. Its Attributes are described as follows.
Name: name of the mapped column. For example, to map the name Column of the Student table, you can add @ Column (name = "name") to the getName () method of the name attribute. If the ing Column name is not specified, the container uses the property name as the default ing column name.
Unique: unique or not. Nullable: whether to allow null.
Length: specifies the maximum character length of a column.
Insertable: whether to allow insertion.
Updatable: whether updates are allowed.
ColumnDefinition: defines the DDL for this column when a table is created.
SecondaryTable: name of the slave table. If this column is not created on the primary table (it is created on the primary table by default), this attribute defines the name of the slave table where the column is located.
@ Lob annotation specifies the text field type with a large field.
@ Id annotation specifies the studentid attribute as the table's primary key.
@ GeneratedValue annotation defines the generation method of the ID field. The studentid value in this example is automatically generated by the MySQL database. It can be generated in the following ways.
TABLE: The container uses the underlying data TABLE to ensure uniqueness.
SEQUENCE: Use the SEQUENCE column of the database to ensure uniqueness.
IDENTITY: use the database's INDENTIT column to ensure uniqueness.
AUTO: The container selects an appropriate method to ensure uniqueness.
NONE: the container is not responsible for generating the primary key, which is completed by the calling program.
For example:
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) public Integer getId() { return this.id; }
In this way, the Entity Bean is developed. Besides adding some annotations to POJO, it is no different from the common POJO class.
5. Develop Session Bean for calling1. Develop a session Bean to call StudentDAORemote. java and StudentDAO. java.
Next we will develop a remote session Bean component. by calling the Entity Bean class Student. java, We can insert a record into the data table student.
First, create a new package com. ejb. create a remote session Bean component StudentDAO in the package according to the development method of the Session Bean. After the creation, a remote interface class StudentDAORemote will be generated. java and implementation class StudentDAO. java.
1) the Remote interface class StudentDAORemote. java is identified by the annotator @ Remote. The function insert () executes the insert student function. The remote interface class StudentDAORemote. java
<span style="font-family:SimSun;">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) implementation class StudentDAO. java
The remote interface StudentDAORemote. java is implemented and identified as a Stateless Session Bean through @ Stateless.
First, it contains an EntityManager type variable em. EntityManager is the Entity Manager, as its name suggests. It is the management container of the Entity Bean. Through this object, we can achieve various interactions with the database, including adding, deleting, modifying, and querying.
The entity variable em also uses annotation @ PersistenceContext to dynamically inject EntityManager objects, if persistence. if multiple persistence contents are configured in the xml file, you also need to specify the persistence name to inject the EntityManager object. You can specify the unitName attribute in the @ PersistenceContext annotation, for example:
@PersistenceContext(unitName="exam-entity") EntityManager em;
If there is only one persistent content configuration, you do not need to specify it explicitly.
Then, the insert () function in the implementation interface is developed. You only need to call the persist () function of em to persistently store the Student object to the database, that is, add a record to the database.
Implementation 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; } }
6. Package and deploy it on the JBOSS server, compress it into a jar package, and deploy it on the JBoss server. Then the JBoss server automatically loads the service. The JNDI service is formed for external access. The release process is as follows:
1. Load the persistence. xml file. 2. Create a database table student. view the MySQL database and you will see the newly created table student. 3. Publish the JNDI service StudentDAO/remote.
In this way, we can access the JNDI service StudentDAO/remote through the client.
7. Test the development client-StudentDAOClient. test the java Development client-StudentDAOClient. java we have developed the Entity Bean and Session Bean components and released them to the JBoss server. Next we will develop a Java client program to create an entity object on this client, call the Session Bean component to insert this object and insert a record into the data table.
Copy the object class Student. java and the interface class StudentDAORemote. java to the corresponding package of the test project EJBTestJava, and 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 props = new Properties (); props. setProperty ("java. na Ming. 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 ("Liu zhongbing"); stud Ent. 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. Create a Student object and call the insert () function to insert the object. After running the program, the following information is output in the console:
A student record has been inserted!
This indicates that the Java class of the client has correctly submitted the Student object to the remote session Bean component. After the first loading, the Entity Bean object has been cached by the Entity Manager of the Entity Manager. When the object is accessed again, the object is directly obtained from the cache.