环境
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;
@Id
public 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{
@PersistenceContext
private 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 {
@PrePersist
public void prePersist(User user){
System.out.println("prePersist called!");
}
@PostPersist
public void postPersist(User user){
System.out.println("postPersist called!");
}
@PreRemove
public void preRemove(User user){
System.out.println("preRemove called!");
}
@PostRemove
public void postRemove(User user){
System.out.println("postRemove called!");
}
@PreUpdate
public void preUpdate(User user){
System.out.println("preUpdate called!");
}
@PostUpdate
public void postUpdate(User user){
System.out.println("postUpdate called!");
}
@PostLoad
public 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>
生命周期探讨
插入数据
调用prePersist和postPersist
更新数据
调用postLoad、preUpdate和postUpdate
删除数据
调用postLoad、preUpdate和postUpdate
得到所有数据
调用四次postLoad,因有四条数据
得到单条数据
调用一次postLoad