Java persistence API (JPA) 1st-simple example

Source: Internet
Author: User
Tags netbeans

Objective: To use the Java persistent API to display data in the database. The basic process includes: U load driver U create database and table U load driver U in netbeans create connection U create persistent unit and entity Class U create session beanu access persistent unit create servlet Client program, access the Session Bean and display the result 1. Place the JDBC driver in the following directory.Modify according to your installation directory. If the default installation is used, it should be placed in the following directory. C:/Sun/appserver/domains/domain1/lib/EXT 2. Add the database entity to the MySQL databaseCreate Database entity 3. Create a table userinfoCreate a table in the Entity database. The table structure is the same as that in chapter 25 of the book. Insert several test data records. Create Table userinfo (userid varchar (10) primary key not null, username varchar (10) Not null, userpass varchar (10) Not null, usertype char (1) not null) insert the following test data: insert into userinfo values ('user001', 'hangsan ', 'hangsan', '0'); insert into userinfo values ('user002', 'lisi ', 'lisi', '0'); insert into userinfo values ('admin001', 'mishu', 'mishu', '0 '); 4. Add a driver to netbeansRight-click drivers and choose new driver. Select the jar package of the JDBC driver. 5. Add a connectionRight-click databases and choose new connection from the shortcut menu. On the displayed page, select the added driver, modify the URL, and modify the URL: JDBC: mysql: // localhost: 3306/entity. Specifically, localhost indicates the host, 3306 indicates the port, and entity indicates the database. 6. Create an EJB ModuleSelect File à New Project, select enterprise in the middle, and then select the EJB module on the right. The project name is usersession. 7. Create a persistent UnitRight-click the project, select newà file/folder, select persistence in the middle, and select persistence unit on the right. On the displayed page, select Data source: New datasource. Enter a JNDI name entity2 in the pop-up interface, and then select the connection created in step 1. The generated file is as follows: <? 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-source> entity2 </JTA-data-source> <Properties> <property name = "toplink. DDL-generation "value =" Create-tables "/> </Properties> </persistence-unit> </persistence> 8. Create a persistent classRight-click the project, select new, and select entity class from database. In datasource, select the configured data source entity2. Then the table appears in the lower-left corner. Select Add in the middle and add it to the right. Select next and then complete. The generated file is as follows:/** userinfo. java ** created on May 21, 2007, ** to change this template, choose tools | template manager * and open the template in the editor. */package JPA; import Java. io. serializable; import javax. persistence. column; import javax. persistence. entity; import javax. persistence. ID; import javax. persistence. namedqueries; import javax. persistence. namedquery; import javax. persistence. table ;/*** Entity class userinfo ** @ author administrator */@ entity @ table (name = "userinfo") @ namedqueries ({@ namedquery (name = "userinfo. findbyuserid ", query =" select u from userinfo u where u. userid =: userid "), @ namedquery (name =" userinfo. findbyusername ", query =" select u from userinfo u where u. username =: username "), @ namedquery (name =" userinfo. findbyuserpass ", query =" select u from userin Fo u where u. userpass =: userpass "), @ namedquery (name =" userinfo. findbyusertype ", query =" select u from userinfo u where u. usertype =: usertype ")}) public class userinfo implements serializable {@ ID @ column (name =" userid ", nullable = false) Private string userid; @ column (name = "username", nullable = false) Private string username; @ column (name = "userpass", nullable = false) Private string us Erpass; @ column (name = "usertype", nullable = false) Private char usertype;/** creates a new instance of userinfo */Public userinfo () {}/*** creates a new instance of userinfo with the specified values. * @ Param userid the userid of the userinfo */Public userinfo (string userid) {This. userid = userid;}/*** creates a new instance of userinfo with the specified values. * @ Param userid the u Serid of the userinfo * @ Param username the username of the userinfo * @ Param userpass the userpass of the userinfo * @ Param usertype the usertype of the userinfo */Public userinfo (string userid, string username, string userpass, char usertype) {This. userid = userid; this. username = username; this. userpass = userpass; this. usertype = usertype;}/*** gets the userid of this userinfo. * @ return The USERID */Public String getuserid () {return this. userid;}/*** sets the userid of this userinfo to the specified value. * @ Param userid the new userid */Public void setuserid (string userid) {This. userid = userid;}/*** gets the username of this userinfo. * @ return the username */Public String GetUserName () {return this. username;}/*** sets the username of this userinfo to the specif IED value. * @ Param username the new username */Public void setusername (string username) {This. username = username;}/*** gets the userpass of this userinfo. * @ return the userpass */Public String getuserpass () {return this. userpass;}/*** sets the userpass of this userinfo to the specified value. * @ Param userpass the new userpass */Public void setuserpass (string userpass) {This. userpas S = userpass;}/*** gets the usertype of this userinfo. * @ return the usertype */Public char getusertype () {return this. usertype;}/*** sets the usertype of this userinfo to the specified value. * @ Param usertype the new usertype */Public void setusertype (char usertype) {This. usertype = usertype;}/*** returns a hash code value for the object. this implementation computes * a hash code v Alue Based on the ID fields in this object. * @ return a hash code value for this object. * // @ override public int hashcode () {int hash = 0; hash + = (this. userid! = NULL? This. userid. hashcode (): 0); Return hash;}/*** determines whether another object is equal to this userinfo. the result is * <code> true </code> if and only if the argument is not null and is a userinfo object that * has the same ID field values as this object. * @ Param object the reference object with which to compare * @ return <code> true </code> if this object is the same as the argument; * <code> False </code> otherwise. * // @ override public Boolean equals (Object object) {// todo: Warning-This method won't work in the case the ID fields are not set if (! (Object instanceof userinfo) {return false;} userinfo Other = (userinfo) object; If (this. userid! = Other. userid & (this. userid = NULL |! This. userid. equals (Other. userid) return false; return true;}/*** returns a string representation of the object. this implementation constructs * That representation based on the ID fields. * @ return a string representation of the object. * // @ override Public String tostring () {return "JPA. userinfo [userid = "+ userid +"] ";}} and then in persistence. the add class button is shown below the design interface of the XML file. Click this button and add the newly created object class to the persistent unit. 9. Write a session bean to access this objectAdd a session bean to the project. For the process of adding a session bean, refer to the compiling of the Session Bean. The bean name is usermanager and provides the remote interface. Add a Business Method to the Session Bean. The following is the modified file, and the red part is added. 9.1 interface filePackage JPA; import javax. EJB. remote; import Java. util. list;/*** this is the business interface for usermanager enterprise Bean. * // @ remotepublic interface usermanagerremote {public list <userinfo> findalluser ();} 9.2 Bean class/** Usermanagerbean. java ** created on May 21, 2007, ** to change this template, choose tools | template manager * and open the template in the editor. */package JPA; import javax. EJB. stateless; import javax. persistence. persistencecontext; import javax. persistence. entitymanager; import Java. util. list;/***** @ author administrator */@ statelesspublic class usermanagerbean implements JPA. usermanagerremote {@ persistencecontext entitymanager em;/** creates a new instance of usermanagerbean */Public usermanagerbean () {} public list <userinfo> findalluser () {return em. createquery ("select u from userinfo U "). getresultlist ();}} 10 , Write Servlet Client Access session BeanTo introduce the client program of the Session Bean, right-click the liberaries of the Web application and choose add project. on the following page, select the EJB module created earlier, select Add (in this case, you do not need to copy the interface file of the Session Bean ). Add a servlet named findalluserservlet to the project. The modified code is as follows (the red part is added):/** findalluserservlet. java ** created on May 21, 2007, */package JPA. web; import Java. io. *; import java.net. *; import javax. servlet. *; import javax. servlet. HTTP. *; import javax. EJB. EJB; import JPA. usermanagerremote; import JPA. userinfo; import Java. util. list; import Java. util. iterator;/***** @ author administrator * @ version */public class findalluserservlet 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 (); List <userinfo> List = user. findalluser (); iterator <userinfo> I = List. iterator (); While (I. hasnext () {userinfo tmpuser = I. next (); out. print (tmpuser. getuserid () + "-" + tmpuser. getUserName () + "<br>");} Out. close ();} // <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>} 11. Run the testDeploy the EJB module and the web module respectively. Access the servlet to obtain the user list. For more information, refer to my book Java ee 5 practical tutorial-Based on WebLogic and eclipse

 

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.