读书人

EJB兑现简单CRUD操作和生命周期探讨

发布时间: 2012-12-27 10:17:10 作者: rapoo

EJB实现简单CRUD操作和生命周期探讨
环境

MyEclipse 8.6 + JBoss 6.0 + JDK 1.6.13 + EJB 3.0

问题

EJB实现简单CRUD操作和生命周期探讨

解决

1. 配置JBoss数据源

a) 数据源参考配置文件

jboss-6.0.0.Final/docs/examples/jca/**-ds.xml

b) 将配置文件放到站点根目录下

jboss-6.0.0.Final/server/default/deploy

c) 将connector加入站点

server/default/lib

d) 配置相关的参数

<jndi-name>MySqlDS</jndi-name>

<connection-url>jdbc:mysql://xxx:3306/xxx</connection-url>

<driver-class>com.mysql.jdbc.Driver</driver-class>

<user-name>xxx</user-name>

<password>xxx</password>

e) 启动JBoss

2. 创建数据库表

CREATE TABLE user(  id int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,  name varchar(255) DEFAULT NULL,  password varchar(255) DEFAULT NULL);


3. 编写实体Bean

User.java

package com.wgb.bean.entity;import java.io.Serializable;import javax.persistence.Entity;import javax.persistence.EntityListeners;import javax.persistence.Id;import com.wgb.bean.UserListener;/**  * @className: User.java * @classDescription:  * @function:  * @author: Wentasy * @createTime: 2012-12-4 下午08:00:32 * @modifyTime:  * @modifyReason:  * @since: JDK 1.6 */@Entity@EntityListeners(UserListener.class)public class User implements Serializable{private int id;private String name;private String password;@Idpublic int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}}


4. 创建对数据库进行操作的Session Bean

UserDao.java

package com.wgb.dao;import java.util.List;import com.wgb.bean.entity.User;/**  * @className: UserDao.java * @classDescription:  * @function:  * @author: Wentasy * @createTime: 2012-12-4 下午08:02:46 * @modifyTime:  * @modifyReason:  * @since: JDK 1.6 */public interface UserDao {public List<User> getAllUser();public void insert(String name, String password);public void update(User user);public void delete(int id);public User getUser(int id);}


UserDaoImpl.java

package com.wgb.dao.impl;import java.util.Iterator;import java.util.List;import javax.ejb.Remote;import javax.ejb.Stateless;import javax.persistence.EntityManager;import javax.persistence.PersistenceContext;import javax.persistence.Query;import com.wgb.bean.entity.User;import com.wgb.dao.UserDao;/**  * @className: UserDaoImpl.java * @classDescription:  * @function:  * @author: Wentasy * @createTime: 2012-12-4 下午08:03:25 * @modifyTime:  * @modifyReason:  * @since: JDK 1.6 */@Stateless@Remote ({UserDao.class})public class UserDaoImpl{@PersistenceContextprivate EntityManager em;@SuppressWarnings("unchecked")public List<User> getAllUser(){return em.createQuery("from User").getResultList();}public void insert(String name, String password){User user = new User();user.setName(name);user.setPassword(password);em.persist(user);}public void update(User user){em.merge(user);}public void delete(int id){em.remove(em.find(User.class, id));}public User getUser(int id){return em.find(User.class, id);}}


5. 编写对生命周期进行处理的Listener

UserListener.java

package com.wgb.bean;import javax.persistence.PostLoad;import javax.persistence.PostPersist;import javax.persistence.PostRemove;import javax.persistence.PostUpdate;import javax.persistence.PrePersist;import javax.persistence.PreRemove;import javax.persistence.PreUpdate;import com.wgb.bean.entity.User;/**  * @className: UserListener.java * @classDescription:  * @function:  * @author: Wentasy * @createTime: 2012-12-11 下午07:44:00 * @modifyTime:  * @modifyReason:  * @since: JDK 1.6 */public class UserListener {@PrePersistpublic void prePersist(User user){System.out.println("prePersist called!");}@PostPersistpublic void postPersist(User user){System.out.println("postPersist called!");}@PreRemovepublic void preRemove(User user){System.out.println("preRemove called!");}@PostRemovepublic void postRemove(User user){System.out.println("postRemove called!");}@PreUpdatepublic void preUpdate(User user){System.out.println("preUpdate called!");}@PostUpdatepublic void postUpdate(User user){System.out.println("postUpdate called!");}@PostLoadpublic void postLoad(User user){System.out.println("postLoad called!");}}


6. 编写显示页面

index.jsp

<%@ page language="java" import="java.util.*,javax.naming.*,com.wgb.bean.*,com.wgb.bean.entity.*,com.wgb.dao.*,com.wgb.dao.impl.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'index.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>    <body>        <%       try {       //Remote    //Properties props = 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");                  //InitialContext ctx = new InitialContext(props);              //HelloWorld helloworld = (HelloWorld) ctx.lookup("HelloWorldBean/remote");            //out.print(helloworld.sayHello("WGB"));                          //Local            InitialContext ctx = new InitialContext();              //HelloWorld helloworld = (HelloWorld) ctx.lookup("HelloWorldBean/local");            //out.print(helloworld.sayHello("Wentasy"));                        //MyTimer t = (MyTimer)ctx.lookup("MyTimerBean/local");            //t.start();                        UserDao userDao = (UserDao)ctx.lookup("UserDaoImpl/remote");                        //插入数据            //userDao.insert("123", "123");            //19:55:05,370 INFO  [STDOUT] prePersist called!            //19:55:05,496 INFO  [STDOUT] postPersist called!                        //更新数据            //User user = new User();            //user.setId(4);//user.setName("125");//user.setPassword("123");            //userDao.update(user);            //19:55:26,769 INFO  [STDOUT] postLoad called!            //19:55:26,770 INFO  [STDOUT] preUpdate called!            //19:55:26,775 INFO  [STDOUT] postUpdate called!                        //删除数据            //userDao.delete(6);            //19:56:37,074 INFO  [STDOUT] postLoad called!            //19:56:37,078 INFO  [STDOUT] preRemove called!            //19:56:37,083 INFO  [STDOUT] postRemove called!                        //得到所有数据            //for (User u : userDao.getAllUser()) {      //out.println(u.getId() + " : " + u.getName() +  "<br/>");      //}            //19:57:28,970 INFO  [STDOUT] postLoad called!            //19:57:28,970 INFO  [STDOUT] postLoad called!            //19:57:28,970 INFO  [STDOUT] postLoad called!            //19:57:28,971 INFO  [STDOUT] postLoad called!                        //得到单条数据            //User u = userDao.getUser(1);            //out.println(u.getId() + " : " + u.getName() + " : " + u.getPassword());            //19:58:09,524 INFO  [STDOUT] postLoad called!                        } catch (NamingException e) {                  e.printStackTrace();              }                 %>    </body></html>


生命周期探讨

EJB兑现简单CRUD操作和生命周期探讨

EJB兑现简单CRUD操作和生命周期探讨

插入数据

调用prePersist和postPersist

更新数据

调用postLoad、preUpdate和postUpdate

删除数据

调用postLoad、preUpdate和postUpdate

得到所有数据

调用四次postLoad,因有四条数据

得到单条数据

调用一次postLoad

1楼Wentasy2012-12-12 18:20
还有一步很关键,在src\META-INF目录下还应配置persistence.xml文件:n[code=html]n<?xml version="1.0" encoding="UTF-8"?>n<persistence xmlns="http://java.sun.com/xml/ns/persistence"n xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"n xsi:schemaLocation="http://java.sun.com/xml/ns/persistencen http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">nt<persistence-unit name="mysql" transaction-type="JTA">n tt<jta-data-source>java:/MySqlDS</jta-data-source>nt</persistence-unit>n</persistence>n[/code]

读书人网 >编程

热点推荐