Intro
This article is base of JSF call EJB comp Demo , it maybe more deeper than that article, than one is just use SLSB, and here we will use all things except MB of EJB1.2, Now i will show you an whole EJB2.1+JSF+CMP case.
Background knowledge
In EJB, EntityBean should not be called directly, it should use in SessionBean,and for cilent when using SB, it should been use by which home interface, and call create() to create an SB handler, then you can use this handler do which provide, in other words, this EJB comp provide to you.
And to EntityBean, it should used in SessionBean, attention, which not need to create, becuse in you deploy, it register to App server's JDNI. So you just have get this resource, in other words, you just need get which home hander.
When mention JDNI, make a not at here, in contianer it should use like it
==============
COMP_NAME="java:comp/env/ejb/UserSessionLocal";
==============
while outside should use
================
JNDI_NAME="UserSessionLocal";
================
Another question is we should remember all the time, if we want to add an method to comp, which should register in all interface file, it same between SB and EB, not forget this, if not, you will find in client side, you couldnot get your useful-method definded in comp.
Ok, follow me, let's have a look this typical case.
Main Code and XML
EntityBean
UserBean.java
package ejbBeans;
/**
* Local home interface for UserData.
*/
public interface UserLocalHome
extends javax.ejb.EJBLocalHome
{
public static final String COMP_NAME= "java:comp/env/ejb/UserLocal";
public static final String JNDI_NAME= "UserLocal";
public UserLocal create(java.lang.Integer id,java.lang.String name )
throws javax.ejb.CreateException;
public UserLocal findByName(java.lang.String name)
throws javax.ejb.FinderException;
@SuppressWarnings( "unchecked")
public java.util.Collection findAll()
throws javax.ejb.FinderException;
public UserLocal findByPrimaryKey(java.lang.Integer pk)
throws javax.ejb.FinderException;
}
UserLocalHome.java
package ejbBeans;
/**
* Local home interface for UserData.
*/
public interface UserLocalHome
extends javax.ejb.EJBLocalHome
{
public static final String COMP_NAME= "java:comp/env/ejb/UserLocal";
public static final String JNDI_NAME= "UserLocal";
public UserLocal create(java.lang.Integer id,java.lang.String name )
throws javax.ejb.CreateException;
public UserLocal findByName(java.lang.String name)
throws javax.ejb.FinderException;
@SuppressWarnings( "unchecked")
public java.util.Collection findAll()
throws javax.ejb.FinderException;
public UserLocal findByPrimaryKey(java.lang.Integer pk)
throws javax.ejb.FinderException;
}
SessionBean
LocalUserSessionBean.java
package ejbBeans;
import java.util.Collection;
import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.FinderException;
import javax.ejb.RemoveException;
import base.BaseSessionBean;
public class LocalUserSessionBean extends BaseSessionBean{
/**
*
*/
private static final long serialVersionUID = 5028163905841527500L;
/**
* The local home interface of user entity bean.
*/
private UserLocalHome userdatahome= null;
/**
* Default create for SessionBean.
*
* @throws CreateException if bean instance can't be created
* @see org.ejbca.core.model.log.Admin
*/
public void ejbCreate() throws CreateException {
userdatahome=(UserLocalHome)getLocator().getLocalHome(UserLocalHome.COMP_NAME);
}
@SuppressWarnings( "unchecked")
public Collection getAllUser(){
Collection usercollection= null;
try {
usercollection=userdatahome.findAll();
} catch (FinderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return usercollection;
}
/**
* Returns a user data source id, given it's user data source name
*
* @return the id or 0 if the user data source cannot be found.
* @ejb.transaction type="Supports"
* @ejb.interface-method view-type="both"
*/
public int getUserInfoId(String name) {
int returnval = 0;
if (userdatahome!= null || !userdatahome.equals( null)) {
System.out.println( "userdatahome is not null");
}
try {
//add
/*UserLocal userdata=userdatahome.create(3,"testuser3");
System.out.println("userdata create"+userdata.getAddress());
*/
//read
System.out.println( "Test1: findByName");
System.out.println( "name:"+name);
Integer id = (userdatahome.findByName(name)).getId();
returnval = id.intValue();
System.out.println( "get id:"+id);
//read again
System.out.println( "Test2: findByPrimaryKey");
UserLocal user=userdatahome.findByPrimaryKey(returnval);
System.out.println( "get address of id=:"+returnval+ ","+user.getAddress());
//delete way1
UserLocal userdemo=userdatahome.findByPrimaryKey(returnval);
userdemo.remove();
System.out.println( "delete user by id:"+returnval+ "which name"+name);
//delete way2 - not pass test
// UserVO userobj=new UserVO(name);
// userdatahome.remove(userobj);
// System.out.println("delete userobj by name:"+name);
} catch (FinderException e) {
e.printStackTrace();
}
// catch (CreateException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
catch (EJBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RemoveException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return returnval;
} // getUserDataSourceId
/**
* Just a test ejb comp call method
* @param str
* @return
*/
public String setString(java.lang.String str ){
return "Do some job and return your enter str as:"+str;
}
}
IUserSessionHome.java
/**
*
*/
package ejbBeans;
/**
* Home interface for UserAdminSession.
*/
public interface IUserSessionHome
extends javax.ejb.EJBHome
{
public static final String COMP_NAME= "java:comp/env/ejb/UserSession";
public static final String JNDI_NAME= "UserSession";
public IUserSessionRemote create()
throws javax.ejb.CreateException,java.rmi.RemoteException;
}
XML
ejb-jar.xml
<? xml version ="1.0" encoding ="UTF-8" ?>
< ejb-jar id ="ejb-jar_1" xmlns ="http://java.sun.com/xml/ns/j2ee" xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation ="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/ejb-jar_2_1.xsd" version ="2.1" >
< description ><![CDATA[MyEJB generated by eclipse wtp xdoclet extension.]]> </ description >
< display-name >MyEJB </ display-name >
< enterprise-beans >
<!-- Session Beans -->
< session id ="Session_UserAdminSession" >
< description ><![CDATA[Administrates users in the database using User Entity Bean.]]> </ description >
< ejb-name >UserSession </ ejb-name >
< home >ejbBeans.IUserSessionHome </ home >
< remote >ejbBeans.IUserSessionRemote </ remote >
< local-home >ejbBeans.IUserSessionLocalHome </ local-home >
< local >ejbBeans.IUserSessionLocal </ local >
< ejb-class >ejbBeans.UserSessionSession </ ejb-class >
< session-type >Stateless </ session-type >
< transaction-type >Container </ transaction-type >
< env-entry >
< env-entry-name >DataSource </ env-entry-name >
< env-entry-type >java.lang.String </ env-entry-type >
< env-entry-value ><![CDATA[java:/TestDS]]> </ env-entry-value >
</ env-entry >
< env-entry >
< description ><![CDATA[Defines the JNDI name of the mail service used]]> </ description >
< env-entry-name >MailJNDIName </ env-entry-name >
< env-entry-type >java.lang.String </ env-entry-type >
< env-entry-value ><![CDATA[java:/EjbcaMail]]> </ env-entry-value >
</ env-entry >
< ejb-local-ref id ="EJBLocalRef_94" >
< ejb-ref-name >ejb/UserLocal </ ejb-ref-name >
< ejb-ref-type >Entity </ ejb-ref-type >
< local-home >ejbBeans.UserLocalHome </ local-home >
< local >ejbBeans.UserLocal </ local >
< ejb-link >User </ ejb-link >
</ ejb-local-ref >
</ session >
<!--
To add session beans that you have deployment descriptor info for, add
a file to your XDoclet merge directory called session-beans.xml that contains
the <session></session> markup for those beans.
-->
<!-- Entity Beans -->
< entity id ="ContainerManagedEntity_User" >
< description ><![CDATA[This enterprise bean entity represents a user]]> </ description >
< display-name >UserEB </ display-name >
< ejb-name >User </ ejb-name >
< local-home >ejbBeans.UserLocalHome </ local-home >
< local >ejbBeans.UserLocal </ local >
< ejb-class >ejbBeans.UserBean </ ejb-class >
< persistence-type >Container </ persistence-type >
< prim-key-class >java.lang.Integer </ prim-key-class >
< reentrant >false </ reentrant >
< cmp-version >2.x </ cmp-version >
< abstract-schema-name >UserBean </ abstract-schema-name >
< cmp-field id ="CMPAttribute_180" >
< description ><![CDATA[]]> </ description >
< field-name >id </ field-name >
</ cmp-field >
< cmp-field id ="CMPAttribute_181" >
< description ><![CDATA[]]> </ description >
< field-name >name </ field-name >
</ cmp-field >
< cmp-field id ="CMPAttribute_182" >
< description ><![CDATA[]]> </ description >
< field-name >password </ field-name >
</ cmp-field >
< cmp-field id ="CMPAttribute_183" >
< description ><![CDATA[]]> </ description >
< field-name >phone </ field-name >
</ cmp-field >
< cmp-field id ="CMPAttribute_184" >
< description ><![CDATA[]]> </ description >
< field-name >address </ field-name >
</ cmp-field >
< primkey-field >id </ primkey-field >
< query >
< description ><![CDATA[findByName]]> </ description >
< query-method >
< method-name >findByName </ method-name >
< method-params >
< method-param >java.lang.String </ method-param >
</ method-params >
</ query-method >
< ejb-ql ><![CDATA[SELECT OBJECT(a) from UserBean a WHERE a.name=?1]]> </ ejb-ql >
</ query >
< query >
< description ><![CDATA[findAll]]> </ description >
< query-method >
< method-name >findAll </ method-name >
< method-params >
</ method-params >
</ query-method >
< ejb-ql ><![CDATA[SELECT OBJECT(a) from UserBean a]]> </ ejb-ql >
</ query >
<!-- Write a file named ejb-finders-UserBean.xml if you want to define extra finders. -->
</ entity >
</ enterprise-beans >
<!-- assembly-descriptor -->
< assembly-descriptor >
<!-- container-transaction -->
< container-transaction id ="MethodTransaction_273" >
< method id ="MethodElement_297" >
< ejb-name >UserSession </ ejb-name >
< method-name >* </ method-name >
</ method >
< trans-attribute >Required </ trans-attribute >
</ container-transaction >
< container-transaction id ="MethodTransaction_305" >
< method id ="MethodElement_329" >
< ejb-name >UserSession </ ejb-name >
< method-intf >Local </ method-intf >
< method-name >setString </ method-name >
< method-params >
< method-param >java.lang.String </ method-param >
</ method-params >
</ method >
< trans-attribute >Supports </ trans-attribute >
</ container-transaction >
< container-transaction id ="MethodTransaction_316" >
< method id ="MethodElement_340" >
< ejb-name >User </ ejb-name >
< method-name >* </ method-name >
</ method >
< trans-attribute >Required </ trans-attribute >
</ container-transaction >
</ assembly-descriptor >
</ ejb-jar >
Jboss.xml
<? xml version ="1.0" encoding ="UTF-8" ?>
<!DOCTYPE jboss PUBLIC "-//JBoss//DTD JBOSS 3.2//EN" "http://www.jboss.org/j2ee/dtd/jboss_3_2.dtd">
< jboss >
< unauthenticated-principal >nobody </ unauthenticated-principal >
< enterprise-beans >
<!--
To add beans that you have deployment descriptor info for, add
a file to your XDoclet merge directory called jboss-beans.xml that contains
the <session></session>, <entity></entity> and <message-driven></message-driven>
markup for those beans.
-->
< entity >
< ejb-name >User </ ejb-name >
< local-jndi-name >UserLocal </ local-jndi-name >
< method-attributes >
</ method-attributes >
</ entity >
< session >
< ejb-name >UserSession </ ejb-name >
< jndi-name >UserSession </ jndi-name >
< local-jndi-name >UserSessionLocal </ local-jndi-name >
< method-attributes >
</ method-attributes >
</ session >
</ enterprise-beans >
</ jboss >
jbosscmp-jdbc.xml
<? xml version ="1.0" encoding ="UTF-8" ?>
<!DOCTYPE jbosscmp-jdbc PUBLIC "-//JBoss//DTD JBOSSCMP-JDBC 3.2//EN" "http://www.jboss.org/j2ee/dtd/jbosscmp-jdbc_3_2.dtd">
< jbosscmp-jdbc >
< defaults >
< datasource >java:/TestDS </ datasource >
< datasource-mapping >mySQL </ datasource-mapping >
</ defaults >
< enterprise-beans >
<!--
To add beans that you have deployment descriptor info for, add a file
to your XDoclet merge directory called jbosscmp-jdbc-beans.xml that
contains the <entity></entity> markup for those beans.
-->
<!-- jboss 5.0.1 features -->
<!-- optimistic locking does not express the exclusions needed -->
< entity >
< ejb-name >User </ ejb-name >
< table-name >user </ table-name >
< cmp-field >
< field-name >name </ field-name >
</ cmp-field >
< cmp-field >
< field-name >password </ field-name >
</ cmp-field >
< cmp-field >
< field-name >id </ field-name >
< column-name >id </ column-name >
</ cmp-field >
< cmp-field >
< field-name >phone </ field-name >
</ cmp-field >
< cmp-field >
< field-name >address </ field-name >
</ cmp-field >
</ entity >
</ enterprise-beans >
<!--
To add jboss relationships for beans not managed by XDoclet, add a
file to your XDoclet merge directory called
jbosscmp-jdbc-relationships.xml that contains the
<ejb-relation></ejb-relation> markups for those beans.
-->
<!--
<relationships>
<ejb-relation>
<ejb-relation-name>AdminGroupDataToAccessRules</ejb-relation-name>
<ejb-relationship-role>
<ejb-relationship-role-name>AdminGroupData</ejb-relationship-role-name>
<key-fields>
<key-field>
<field-name>primKey</field-name>
<column-name>AdminGroupData_accessRules</column-name>
</key-field>
</key-fields>
</ejb-relationship-role>
<ejb-relationship-role>
<ejb-relationship-role-name>AccessRulesData</ejb-relationship-role-name>
<key-fields />
</ejb-relationship-role>
</ejb-relation>
</relationships>
-->
</ jbosscmp-jdbc >
JSF
Main MBean
LoginMBean.java
public class LoginMBean {
private static IUserSessionHome usersessionhome = null;
private IUserSessionRemote usersession = null;
private List userlist = new ArrayList();
/**
* get session bean handler
*/
public void initialize() {
InitialContext ctx;
try {
ctx = new InitialContext();
usersessionhome = (IUserSessionHome) PortableRemoteObject.narrow(
ctx.lookup(IUserSessionHome.JNDI_NAME),
IUserSessionHome. class);
usersession = usersessionhome.create();
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (CreateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public int getIdByUserName() throws NamingException{
InitialContext ctx;
int id=0;
try {
ctx = new InitialContext();
usersessionhome = (IUserSessionHome) PortableRemoteObject.narrow(
ctx.lookup(IUserSessionHome.JNDI_NAME),
IUserSessionHome. class);
usersession = usersessionhome.create();
id=usersession.getUserInfoId( "daniel");
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (CreateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return id;
}
}
Index.jsp
< %@ taglib uri ="http://java.sun.com/jsf/core" prefix ="f" % >
< %@ taglib uri ="http://java.sun.com/jsf/html" prefix ="h" % >
< %@page contentType ="text/html; charset=utf-8" % >
< !doctype html public "-//w3c//dtd html 4.0 transitional//en" >
< html >
< head >
< title > DataTable </title>
</head>
< body >
< f:view >
< h:outputText value ="#{loginMean.idByUserName}" />
</f:view>
</body>
</html>
Source Code for DownLoad
More Contact me by danni-505#hotmail.com