Objectives:
- The following call process is used to add user information. On the JSP page, enter the user information and submit it to the servlet. The servlet calls the Session Bean and the session bean calls the entity class.
- Master the basic concepts of JPA.
Includes two parts:
The development process of adding features is as follows:
- Add a Business Method to the usersession Bean
- Adduser. jsp
- Write the adduserservlet. Java controller for Adding Functions
The content outlined in JPA includes:
- The difference between using JPA to interact with the database and using JDBC to interact with the database
- Java persistence
- Compile objects to be written in the object class
- How to access object classes
- Common JPA Interfaces
The following is an introduction. Note: This example is based on lecture 1.
Part 1: add features
Add a Business Method to the usersession BeanFirst, you need to add a method declaration in the business interface, and then implement this method in the bean class. In the service interface usermanagerremote. add the following method declaration to Java: Public void adduser (string userid, string username, string userpass, char usertype); In Bean class usermanagerbean. add the following method to Java: Public void adduser (string userid, string username, string userpass, char usertype) {userinfo user = new userinfo (userid, username, userpass, usertype); em. persist (User);} em is the entitymanager object injected into the Bean class in the last instance. The persist method is persistent, which is relative to the database insertion Operation. By using this method, the information in the object user is written to the database.
Adduser. jspAdd a JSP file to userweb to add user information. The Code is as follows: <% @ page contenttype = "text/html" %> <% @ page pageencoding = "UTF-8" %> <% -- The taglib directive below imports the jstl library. if you uncomment it, you must also add the jstl Library to the project. the add library... actionon libraries node in projects view can be used to add the jstl 1.1 library. -- %> <% -- <% @ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "C" %> -- %> <! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en" "http://www.w3.org/TR/html4/loose.dtd"> <HTML> Write the adduserservlet. Java controller for Adding FunctionsThe adduserservlet Controller provides the following functions: U obtains the information entered by the user U calls the business method U turns to the display information interface. The Code of adduserservlet is as follows (the red part is the code you need to add yourself ): /** adduserservlet. java ** created on May 23, 2007, */package JPA. web; import Java. io. *; import java.net. *; import javax. servlet. *; import javax. servlet. HTTP. *; import javax. EJB. EJB; import JPA. usermanagerremote;/***** @ author administrator * @ version */public class adduserservlet extends httpservlet {@ EJB usermanagerremote user; /** processes requests for both HTTP <code> Get </code> and <code> post </code> methods. * @ Param request Servlet Request * @ Param response servlet response */protected void processrequest (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {response. setcontenttype ("text/html; charset = UTF-8"); printwriter out = response. getwriter (); string userid = request. getparameter ("userid"); string username = request. getparameter ("username"); string userpass = request. getparameter ("userpass"); string usertype = request. getparameter ("usertype"); User. adduser (userid, username, userpass, usertype. charat (0); requestdispatcher RD = request. getrequestdispatcher ("findalluserservlet"); Rd. forward (request, response);} // <Editor-fold defaultstate = "Collapsed" DESC = "httpservlet methods. click on the + sign on the left to edit the code. ">/** handles the HTTP <code> Get </code> method. * @ Param request Servlet Request * @ Param response servlet response */protected void doget (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {processrequest (request, response );} /** handles the HTTP <code> post </code> method. * @ Param request Servlet Request * @ Param response servlet response */protected void dopost (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {processrequest (request, response );} /** returns a short description of the servlet. */Public String getservletinfo () {return "Short Description";} // </Editor-fold>}
TestRedeploy the EJB and web applications and access: http: // localhost: 8080/userweb/adduser. jsp. Enter a user information in this interface, and submit the information. after submitting the information, you can see the newly added user.
Part 2: JPA Overview
Comparison between JPA and JDBCPreviously, we used JDBC to interact with the database. The basic process was as follows: n loading the driver, n creating connections, N compiling SQL statements, n creating statement objects, and N executing SQL statements; n. The Query Process Using JPA is as follows: Em. createquery (...). Getsingleresult () or Em. createquery (...). The process for getresultlist () to add using JPA is as follows: In contrast to Em. persist (user), using JPA greatly reduces the workload of programmers. But the premise is that the persistence provider provides many implementations, and programmers need to write entity classes. The following describes the main problems to be solved by the persistence provider and how to compile the entity class.
Java persistenceTo put it simply, the main problem to be solved for Java persistence is the synchronization between objects in the content and entities in the database. The topics involved are as follows: n database information configuration, including the database location, name, user name, and password. In addition, the JDBC driver is required. N is used to load object data, from entity to object. N is used to update object data, from object to entity; N Data Query: load data from the database; n ing between the relationship between entities in the database and objects in the memory; n batch processing, including Batch addition, deletion, and modification; N security issues and N transaction issues.
How to compile entity classesAll object classes should have a persistent unit for management, which is declared in an XML document. The following code is the configuration file persistence. xml used in the previous instance: <? 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 = "userpu" transaction-type = "JTA"> <provider> oracle. toplink. essentials. EJB. cmp3.entitymanagerfactoryprovider </provider> <JTA-data-so Urce> entity2 </JTA-data-source> <Properties> <property name = "toplink. DDL-generation "value =" Create-tables "/> </Properties> </persistence-unit> </persistence> declares the database corresponding to the persistent unit, the name of the data source is usually used. In addition, you can declare the entity classes. The entity class is used to represent tables in the database. The compilation of the entity class mainly determines the following information: n which table the object corresponds to in the database, and N which field the attribute in the Entity class corresponds to in the table; n. Which attribute of the object class is the primary key. When writing an object class, the main knowledge points include: declare this class as an object class: @ entity declares which table the object class corresponds to: @ table (name = "userinfo ") declare which column of the object class corresponds to the table: @ column (name = "userid", nullable = false) Private string userid; @ column (name = "username ", nullable = false) Private string username; @ column (name = "userpass", nullable = false) Private string userpass; @ column (name = "usertype", nullable = false) private char usertype; declare the primary key of the object class: @ ID @ column (name = "userid", n Ullable = false) Private string userid; complete code can be found in section 1.
How to access object classesFrom the previous query of all users and adding users, we can see that operations on objects are mainly completed through the entitymanager interface. to query objects, you need to use the query interface.
Common JPA InterfacesCommon interfaces are as follows: entitymanager interface for Entity Management, including creating and querying, deleting entities, querying and adding entities. Query interface to complete various queries. Generally, entitymanager is created, mainly using the JPA query language, or standard SQL language. Entitymanagerfactory interface, used to create entitymanager. If entitymanager cannot be injected, you must use entitymanagerfactory to create it. Persistence interface, used to create an entitymanagerfactory object.
For more information, see Java ee 5 practical tutorial-Based on WebLogic and eclipse