• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How does CMP Bean works

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
I am new to Enterprise Beans and trying to make some CMP bean for learning purpose.
I created a CMP bean say Contents which is mapped to a MS SQL server contents table.
Created another session bean say ContentSession to provide access to this CMP bean.
Now in a servlet i invoked this session bean to create a new record into Content table using create method it seems working fine as it is returning me the correct valus but when i went into table i could not find anything in the database table.

Now my question is that because CMP Entity bean i directly mapped to database table therefore it should save data into database while shutting down of the server but i restarted JBoss server hosting my enterprise application but could not find anything in database even after restarting.

While even after restarting of the Jboss server if i am querying the earlier values i inserted using create method i can search and retrieve all that values.

From above behaviour of my bean it seems that i am lacking somewhere to understand the actual behaviour of a CMP bean and its relationship with the database.

Is there anybdoy who can clear me this thing or can advice me some online resource where i can find more detail on this topic.

Regs,
Rahi
Now
 
Ranch Hand
Posts: 518
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Shutting down the EJB container will not cause it to persist your data.

Are you inside a transaction that is not being committed?

If you will post the relevant sections of code, someone may be able to spot the problem.
 
Rahi Kumar
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Here is the complete code for my bean and other nodes

1- CMP Bean created using Netbeans 5.0


import javax.ejb.*;


public abstract class ContentTypesBean implements EntityBean, ContentTypesLocalBusiness {
private EntityContext context;

// <editor-fold defaultstate="collapsed" desc="EJB infrastructure methods. Click on the + sign on the left to edit the code.">
// TODO Consider creating Transfer Object to encapsulate data
// TODO Review finder methods
/**
* @see javax.ejb.EntityBean#setEntityContext(javax.ejb.EntityContext)
*/
public void setEntityContext(EntityContext aContext) {
context = aContext;
}

/**
* @see javax.ejb.EntityBean#ejbActivate()
*/
public void ejbActivate() {

}

/**
* @see javax.ejb.EntityBean#ejbPassivate()
*/
public void ejbPassivate() {

}

/**
* @see javax.ejb.EntityBean#ejbRemove()
*/
public void ejbRemove() {

}

/**
* @see javax.ejb.EntityBean#unsetEntityContext()
*/
public void unsetEntityContext() {
context = null;
}

/**
* @see javax.ejb.EntityBean#ejbLoad()
*/
public void ejbLoad() {

}

/**
* @see javax.ejb.EntityBean#ejbStore()
*/
public void ejbStore() {

}
// </editor-fold>

public abstract String getName();
public abstract void setName(String name);

public abstract String getFileType();
public abstract void setFileType(String fileType);

public abstract String getDataType();
public abstract void setDataType(String dataType);

public abstract Integer getStatus();
public abstract void setStatus(Integer status);

public abstract java.lang.Integer getId();

public abstract void setId(java.lang.Integer id);


public Integer ejbCreate(Integer id, String name, String fileType, String dataType, Integer status) throws CreateException {
if (id == null) {
throw new CreateException("The field \"id\" must not be null");
}

// TODO add additional validation code, throw CreateException if data is not valid
setId(id);
setName(name);
setFileType(fileType);
setDataType(dataType);
setStatus(status);

return null;
}

public void ejbPostCreate(Integer id, String name, String fileType, String dataType, Integer status) {
// TODO populate relationships here if appropriate

}
}

2- Session Bean


import java.util.Iterator;
import javax.ejb.*;

public class ContentTypesSessionBean implements SessionBean, ContentTypesSessionRemoteBusiness, ContentTypesSessionLocalBusiness {
private SessionContext context;

// <editor-fold defaultstate="collapsed" desc="EJB infrastructure methods. Click the + sign on the left to edit the code.">
// TODO Add code to acquire and use other enterprise resources (DataSource, JMS, enterprise bean, Web services)
// TODO Add business methods or web service operations
/**
* @see javax.ejb.SessionBean#setSessionContext(javax.ejb.SessionContext)
*/
public void setSessionContext(SessionContext aContext) {
context = aContext;
}

/**
* @see javax.ejb.SessionBean#ejbActivate()
*/
public void ejbActivate() {

}

/**
* @see javax.ejb.SessionBean#ejbPassivate()
*/
public void ejbPassivate() {

}

/**
* @see javax.ejb.SessionBean#ejbRemove()
*/
public void ejbRemove() {

}
// </editor-fold>

/**
* See section 7.10.3 of the EJB 2.0 specification
* See section 7.11.3 of the EJB 2.1 specification
*/
public void ejbCreate() {
// TODO implement ejbCreate if necessary, acquire resources
// This method has access to the JNDI context so resource aquisition
// spanning all methods can be performed here such as home interfaces
// and data sources.
}



// Add business logic below. (Right-click in editor and choose
// "EJB Methods > Add Business Method" or "Web Service > Add Operation")

private rishi.ContentTypesLocalHome lookupContentTypesBean() {
try {
javax.naming.Context c = new javax.naming.InitialContext();
rishi.ContentTypesLocalHome rv = (rishi.ContentTypesLocalHome) c.lookup("java:comp/env/ejb/ContentTypesBean");
return rv;
}
catch(javax.naming.NamingException ne) {
java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE,"exception caught" ,ne);
throw new RuntimeException(ne);
}
}

public int createNewContentType(java.lang.Integer id, String name, String fileType, String dataType, java.lang.Integer status) throws rishi.MyWapException {
int newId=0;
try{
rishi.ContentTypesLocalHome contentType= lookupContentTypesBean();
contentType.create(id,name,fileType,dataType,status);
newId=1;
}catch(Exception ex){
newId=-1;
}
return newId;
}

public int findContentType(String paramVal, String paramName) throws rishi.MyWapException {
int contentType=0;
try{
java.util.Collection col;
if(paramName.equalsIgnoreCase("name"))
col=lookupContentTypesBean().findByName(paramVal);
else if(paramName.equalsIgnoreCase("fileType"))
col=lookupContentTypesBean().findByFileType(paramVal);
else if(paramName.equalsIgnoreCase("dataType"))
col=lookupContentTypesBean().findByDataType(paramVal);
else
col=lookupContentTypesBean().findByStatus(new Integer(Integer.parseInt(paramVal)));
if(col!=null && col.size()>0)
{
Iterator itr=col.iterator();
if(itr.hasNext())
contentType=((ContentTypesLocal)itr.next()).getId().intValue();
else
contentType=0;
}
else
contentType=0;
}catch(Exception ex){
contentType=-1;
}
return contentType;
}



}

3- Java servlet invoking session bean



import java.io.*;
import java.net.*;

import javax.servlet.*;
import javax.servlet.http.*;


public class CreateMyObject extends HttpServlet {

/** 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();
// TODO output your page here
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet CreateMyObject</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet CreateMyObject at " + request.getContextPath () + "</h1>");
String id=request.getParameter("id");
String name=request.getParameter("name");
String dataType=request.getParameter("datatype");
String fileType=request.getParameter("filetype");
short status=1;
int retrId=0;
try{
rishi.ContentTypesSessionLocal sessObj=lookupContentTypesSessionBean();
sessObj.createNewContentType(new Integer(id),name,fileType,dataType,new Integer(status));
retrId=sessObj.findContentType(name,"name");
}catch(Exception ex){
retrId=-2;
}
out.println("<BR>id:"+id);
out.println("<BR>name:"+name);
out.println("<BR>dataType:"+dataType);
out.println("<BR>fileType:"+fileType);
out.println("<BR>status:"+status);
out.println("<BR>retrId:"+retrId);
out.println("</body>");
out.println("</html>");

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>

private rishi.ContentTypesSessionLocal lookupContentTypesSessionBean() {
try {
javax.naming.Context c = new javax.naming.InitialContext();
rishi.ContentTypesSessionLocalHome rv = (rishi.ContentTypesSessionLocalHome) c.lookup("java:comp/env/ejb/ContentTypesSessionBean");
return rv.create();
}
catch(javax.naming.NamingException ne) {
java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE,"exception caught" ,ne);
throw new RuntimeException(ne);
}
catch(javax.ejb.CreateException ce) {
java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE,"exception caught" ,ce);
throw new RuntimeException(ce);
}
}
}


Kindly advice if i am supposed to write code for writing data to database in CMP bean also and if it is then at which stage i shall do that.

Regs,
Rahi
 
Rahi Kumar
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here are the contents for my ejb-jar.xml file

<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar version="2.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">
<display-name>MyWap-EJBModule</display-name>
<enterprise-beans>
<session>
<display-name>ContentTypesSessionSB</display-name>
<ejb-name>ContentTypesSessionBean</ejb-name>
<home>rahi.ContentTypesSessionRemoteHome</home>
<remote>rahi.ContentTypesSessionRemote</remote>
<local-home>rahi.ContentTypesSessionLocalHome</local-home>
<local>rahi.ContentTypesSessionLocal</local>
<ejb-class>rahi.ContentTypesSessionBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
<ejb-local-ref>
<ejb-ref-name>ejb/ContentTypesBean</ejb-ref-name>
<ejb-ref-type>Entity</ejb-ref-type>
<local-home>rahi.ContentTypesLocalHome</local-home>
<local>rahi.ContentTypesLocal</local>
<ejb-link>ContentTypesBean</ejb-link>
</ejb-local-ref>
</session>
<entity>
<display-name>ContentTypesEB</display-name>
<ejb-name>ContentTypesBean</ejb-name>
<local-home>rahi.ContentTypesLocalHome</local-home>
<local>rahi.ContentTypesLocal</local>
<ejb-class>rahi.ContentTypesBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.Integer</prim-key-class>
<reentrant>false</reentrant>
<abstract-schema-name>ContentTypes</abstract-schema-name>
<cmp-field>
<field-name>name</field-name>
</cmp-field>
<cmp-field>
<field-name>fileType</field-name>
</cmp-field>
<cmp-field>
<field-name>dataType</field-name>
</cmp-field>
<cmp-field>
<field-name>status</field-name>
</cmp-field>
<cmp-field>
<description>Primary Key</description>
<field-name>id</field-name>
</cmp-field>
<primkey-field>id</primkey-field>
<query>
<description>auto generated method</description>
<query-method>
<method-name>findByName</method-name>
<method-params>
<method-param>java.lang.String</method-param>
</method-params>
</query-method>
<ejb-ql>SELECT OBJECT(c) FROM ContentTypes AS c WHERE c.name = ?1</ejb-ql>
</query>
<query>
<description>auto generated method</description>
<query-method>
<method-name>findByFileType</method-name>
<method-params>
<method-param>java.lang.String</method-param>
</method-params>
</query-method>
<ejb-ql>SELECT OBJECT(c) FROM ContentTypes AS c WHERE c.fileType = ?1</ejb-ql>
</query>
<query>
<description>auto generated method</description>
<query-method>
<method-name>findByDataType</method-name>
<method-params>
<method-param>java.lang.String</method-param>
</method-params>
</query-method>
<ejb-ql>SELECT OBJECT(c) FROM ContentTypes AS c WHERE c.dataType = ?1</ejb-ql>
</query>
<query>
<description>auto generated method</description>
<query-method>
<method-name>findByStatus</method-name>
<method-params>
<method-param>java.lang.Integer</method-param>
</method-params>
</query-method>
<ejb-ql>SELECT OBJECT(c) FROM ContentTypes AS c WHERE c.status = ?1</ejb-ql>
</query>
</entity>
</enterprise-beans>
<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>ContentTypesBean</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
<container-transaction>
<method>
<ejb-name>ContentTypesSessionBean</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>
 
Ranch Hand
Posts: 1847
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Have you taken care of your database transactions properly?
What you describe is typical of data being written in a transactional context without that context being committed afterwards.
The database will (to all other clients except the one holding the transaction) report the data as if the operations inside the transaction were never executed until such a time as the transaction is committed.

Killing the server will generally have the reverse effect from the one desired, as it will roll back open transactions.
 
Rahi Kumar
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
If we need to write code for database transaction management for a CMP bean then what is the difference between CMP bean and a BMP Beans in terms of database calls?

Regs,
 
Scott Johnson
Ranch Hand
Posts: 518
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
From a transaction point of view, BMP and CMP are the same. Both can participate in a container's transaction.

CMP does not eliminate the need to write code to commit or rollback transactions. That needs to happen regardless.
[ August 14, 2006: Message edited by: Scott Johnson ]
 
Rahi Kumar
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ok. But where shall we define these database transaction code for
Create/Update/delete calls.
I mean in which even handler?

Regs,
Rishi Tyagi
 
Ranch Hand
Posts: 8945
Firefox Browser Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

CMP does not eliminate the need to write code to commit or rollback transactions. That needs to happen regardless.


Why do I need to write the code to comitt. The container is supposed to take care of it because I would have defined the transaction attribute, right?
 
No matter how many women are assigned to the project, a pregnancy takes nine months. Much longer than this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic