In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will give you a detailed explanation on how to use EJB3.0. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.
What is EJB?
An enterprise JavaBean (EJB) is a reusable and portable J2EE component. EJB consists of multiple methods that encapsulate business logic. For example, an EJB can have business logic that includes a method to update data in a customer database. Multiple remote and local clients can call this method. In addition, EJB runs in a container that allows developers to focus only on business logic in bean without thinking about complex and error-prone things like transaction support, security, and remote object access. EJB is developed in the form of POJO or plain old Java objects, and developers can use metadata annotations to define how the container manages these Bean.
EJB Typ
There are three main types of EJB: session Bean, entity Bean and message-driven Bean. The session Bean performs a clear decoupling task, such as checking customer account history. Entity Bean is a complex business entity that represents business objects that exist in the database. Message-driven Bean is used to receive asynchronous JMS messages. Let's understand these types in more detail.
Session Bean
A session Bean generally represents an action such as "processing an order" in a business process. Session Bean is classified as stateful or stateless based on whether excessive state is maintained or not. Stateless session Bean has no intermediate state. They do not keep track of the information passed by one method call to another. So each call to a stateless business method is independent of its previous call; for example, tax calculation or account transfer. When the method of calculating the tax amount is called, the tax value is calculated and returned to the called method, and there is no need to store the internal state of the caller for future invocation. Because they do not maintain state, these Bean are managed only by the container. When a client requests a stateless Bean instance, it can receive an instance from the free container-managed stateless session Bean instance set. Also because stateless session Bean can be shared, containers can maintain a smaller number of instances to serve a large number of clients. Simply add meta annotation @ Stateless to the Bean to specify that a Java Bean is deployed and managed as a stateless session Bean.
A stateful session Bean maintains a session state that spans multiple method calls; for example, an online shopping basket application. When a customer starts shopping online, the customer's details are obtained from the database. The same information is also accessible to other methods that are called when the customer adds or removes items from the basket and so on. But because this state is not retained when the session ends, the system crashes, or the network fails, the stateful session Bean is temporary. When a client requests a stateful session Bean instance, the client gets a session instance, and the state of the Bean is only maintained for the client. Tell the container that a stateful session Bean instance should be removed when a method call ends by adding meta comment @ Remove to the method. Session Bean instance
Import javax.ejb.Stateless.*
/ * *
* A simple stateless session bean implementing the incrementValue () method of the * CalculateEJB interface.
, /
@ Stateless (name= "CalculateEJB")
Public class CalculateEJBBean
Implements CalculateEJB
{
Int value = 0
Public String incrementValue ()
{
Value++
Return "value incremented by 1"
}
}
Entity Bean
The entity Bean is an object that manages persistent data, potentially uses some related Java objects and can be identified by the primary key. Specify that a class is an entity Bean by including the @ Entity meta annotation. The entity Bean represents persistent data from the database, such as a record in a customer table, or an employee record in an employee table. Entity Bean can also be shared by multiple clients. For example, an employee entity can be used by multiple clients that calculate an employee's annual payroll or update the employee's address. Entity Bean object-specific variables can be persisted. All variables in the entity Bean that do not have a @ Transient meta annotation need to be considered for persistence. One of the main features of EJB3.0 is the ability to create an object / relational mapping entity Bean that contains annotations using metadata. For example, specify that the empId variable of the entity Bean maps to the EMPNO attribute in the employee table, annotating the name of the table with @ Table (name= "Employees") and the empId variable with @ Column (name= "EMPNO") as in the following example. In addition, a feature of EJB3.0 is that you can easily test the entity Bean at development time, and you can use Oracle Application Server Entity Test Harness to run an entity Bean outside the container.
Import javax.persistence.*
Import java.util.ArrayList
Import java.util.Collection
@ Entity
@ Table (name = "EMPLOYEES")
Public class Employee implements java.io.Serializable
{
Private int empId
Private String eName
Private double sal
@ Id
Column (name= "EMPNO", primaryKey=true)
Public int getEmpId ()
{
Return empId
}
Public void setEmpId (int empId)
{
This.empId = empId
}
Public String getEname ()
{
Return eName
}
Public void setEname (String eName)
{
This.eName = eName
}
Public double getSal ()
{
Return sal
}
Public void setSal (double sal)
{
This.sal = sal
}
Public String toString ()
{
StringBuffer buf = new StringBuffer ()
Buf.append ("Class:")
.append (this.getClass (). GetName ()) .append ("::") .append ("empId:") .append (getEmpId ()) .append ("ename:") .append (getEname ()) .append ("sal:") .append (getSal ())
Return buf.toString ()
}
}
Message driven Bean
Driving Bean (MDB) provides an easier way to implement asynchronous communication than to use Java message services (JMS) directly. Create a MDB to receive asynchronous JMS messages. The container handles most of the work required to load the processing for JMS queues and topics. It sends all messages to the relevant MDB. A MDB allows J2EE applications to send asynchronous messages that can be processed by the application. Implement the javax.jms.MessageListener interface and annotate the Bean with @ MessageDriven to specify that a Bean is a message-driven Bean.
Message-driven Bean instance
Import javax.ejb.MessageDriven
Import javax.ejb.ActivationConfigProperty
Import javax.ejb.Inject
Import javax.jms.*
Import java.util.*
Import javax.ejb.TimedObject
Import javax.ejb.Timer
Import javax.ejb.TimerService
@ MessageDriven (
ActivationConfig = {
ActivationConfigProperty (propertyName= "connectionFactoryJndiName", propertyValue= "jms/TopicConnectionFactory")
ActivationConfigProperty (propertyName= "destinationName", propertyValue= "jms/myTopic")
ActivationConfigProperty (propertyName= "destinationType", propertyValue= "javax.jms.Topic")
@ ActivationConfigProperty (propertyName= "messageSelector", propertyValue= "RECIPIENT = 'MDB'")
}
)
/ * *
* A simple Message-Driven Bean that listens to the configured JMS Queue or Topic and gets notified
Via an * invocation of it's onMessage () method when a message has been posted to the Queue or Topic. The bean
* prints the contents of the message.
, /
Public class MessageLogger implements MessageListener, TimedObject
{
@ Inject javax.ejb.MessageDrivenContext mc
Public void onMessage (Message message)
{
System.out.println ("onMessage () -" + message)
Try
{
String subject = message.getStringProperty ("subject")
String inmessage = message.getStringProperty ("message")
System.out.println ("Message received\ n\ tDate:" + new java.util.Date () + "\ n\ tSubject:" + subject + "\ n\ tMessage:" + inmessage + "\ n")
System.out.println ("Creating Timer a single event timer")
TimerService ts = mc.getTimerService ()
Timer timer = ts.createTimer (30000, subject)
System.out.println ("Timer created by MDB at:" + new Date (System.currentTimeMillis ()) + "with info:" + subject)
}
Catch (Throwable ex)
{
Ex.printStackTrace ()
}
}
Public void ejbTimeout (Timer timer)
{
System.out.println ("EJB 3.0: Timer with MDB")
System.out.println ("ejbTimeout () called at:" + new Date (System.currentTimeMillis ()
Return
}
}
Use EJB
The client is the application that accesses the Bean. Although it is not necessary to store it in the client layer, it can be used as a stand-alone application, JSP,Servlet, or another EJB. The client accesses the methods in the EJB through the remote or local interface of Bean, depending on whether the client and the Bean are running in the same or different JVM. These interfaces define the methods in Bean, which are actually implemented by the Bean class. When a client accesses a method in the Bean class, the container generates a proxy for Bean, called a remote object or a local object. The remote or local object receives the request, delegates it to the corresponding Bean instance, and returns the result to the client. Call a method in Bean, and the client finds Bean using a name defined in EJB that is not a description file. In the following example, the client uses the context object to find the Bean named "StateLessejb".
EJB client instance
Import javax.naming.Context; import javax.naming.InitialContext; / * * A simple bean client which calls methods on a stateless session bean. * / public class CalculateejbClient {public static void main (String [] args) {Context context = new InitialContext (); CalculateEJB myejb = (CalculateEJB) context.lookup ("java:comp/env/ejb/CalculateEJB"); myejb.incrementValue () }} this is the end of the article on "how to use EJB3.0". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.