If you're looking for a good place to start learning how to create a Java Bean, look no further. This article explains how to create an entity bean. It is taken from chapter 4 of the book Enterprise JavaBeans 3.0 Fifth Edition, written by Richard Monson-Haefel and Bill Burke (O'Reilly, 2006; ISBN: 059600978X).
Developing Your First Beans - Creating a new Cabin entity (Page 5 of 5 )
In this example, you finally see how Cabin entities are created. Java's new() operator is used to allocate an instance of the Cabin bean class. Nothing magical is happening. The client initializes the properties locally on the Cabin bean instance. The id, name, deckLevel, shipId, and bedCount of the Cabin entity are set:
The Cabin entity does not get inserted into the database when you allocate it on the client. The instance must be passed to the TravelAgentEJB where it will be created in the database when the EntityManager.persist() method is called.
Figure4-3 shows how the relational database table we created should look after this code has been executed. It should contain one record.
Figure 4-3. CABIN table with one cabin record
The client locates Cabin entity beans by passing the primary key to the TravelAgentRemote’s find Cabin() method. As you saw before, this session bean interacts with the EntityManager service to find the bean in the database. The TravelAgent passes back an instance of a Cabin with that primary key. This is possible because we defined the Cabin bean class to implement the java.io.Serializable interface, which allowed the Cabin bean instance to be marshaled across the wire back to the client.
We can now interrogate the Cabin bean instance locally to get the Cabin entity's name, deckLevel, shipId, and bedCount:
We are ready to create and run the Client application. Compile the Client application and deploy the Cabin entity into the container system. Then run the Client application. The output should look something like this:
Master Suite 1 1 3
Congratulations! You just created and used your first stateless session bean and entity bean. Of course, the Client application doesn't do much, but this is a good first step to learning how to implement EJBs and entities.
DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.