O'Reilly logo

Enterprise JavaBeans, Third Edition by Richard Monson-Haefel

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The ejbCreate( ) Method

ejbCreate() methods are called by the container when a client invokes the corresponding create() method on the bean’s home. With bean-managed persistence, the ejbCreate() methods are responsible for adding new entities to the database. This means that the BMP version of ejbCreate() will be much more complicated than the equivalent methods in container-managed entities; with container-managed beans, ejbCreate() doesn’t have to do much more than initialize a few fields. Another difference between bean-managed and container-managed persistence is that the EJB specification states that ejbCreate() methods in bean-managed persistence must return the primary key of the newly created entity. By contrast, in container-managed beans ejbCreate() is required to return null.

The following code contains the ejbCreate() method of the ShipBean. Its return type is the Ship EJB’s primary key, Integer. The method uses the JDBC API to insert a new record into the database based on the information passed as parameters:

public Integer ejbCreate(Integer id, String name, int capacity, double tonnage) throws CreateException { if ((id.intValue() < 1) || (name == null)) throw new CreateException("Invalid Parameters"); this.id = id; this.name = name; this.capacity = capacity; this.tonnage = tonnage; Connection con = null; PreparedStatement ps = null; try { con = this.getConnection(); ps = con.prepareStatement( "insert into Ship (id, name, capacity, tonnage) " + "values (?,?,?,?)"); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required