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 (?,?,?,?)"); ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access