Methods for deploying Java EJB components on the server side

  • 2020-04-01 04:26:48
  • OfStack

What is EJB?
EJB is a Java enterprise Bean, a JavaEE server-side enterprise component model, whose design goal and core application is to deploy distributed applications. Without further ado, see how EJB3 is deployed on the machine.
 
Deployment environment:
Operating system: Windows 8.1
EJB container: Jboss 7.1
DB: MySQL 5.6.10
IDE: MyEclipse 10
The JDK: 1.6
 
1. Create database and table
Because you need to communicate with the database during this process, you need to create the database tables first.
Create database:


create database student; //Create a database student

Create a table:


create table student( //Create the table student with the same name as the database
`id` integer(11) not null, 
`name` varchar2(20) default null,
primary key (`id`)
)ENGINE=InnoDB DEFAULT CHARSET=latin1

Insert a piece of data:

insert into student values(1,'easynoder');
commit;
Assign access to the local root user (do not do this in production).

grant all privileges on *.* to root@localhost indentified by "1234"
 
Through the above steps, the required database tables are set up. All data can be accessed by the root user.
 
2. Write entity beans, user action interfaces, and session beans
 
Create an EJB project called the MyEJBProject. The project meta-info directory contains a file persistence. XML file. This file is used to configure the data source for later configuration.
Next, create the entity Bean

@Entity //Indicates that this is an entity Bean
@Table (name = "student" ) //Create a map with the database table student
public class StudentEntity implements Serializable {
  private static final long serialVersionUID = 4002145187978562529L;

  @Id //Indicates the id of the entity
  @GeneratedValue(strategy = GenerationType. AUTO ) //Id generation strategy
  @Column(name = "id" )//This corresponds to the student table id field
  private int id ; 

  @Column(name = "name" ) //This corresponds to the student table name field
  private String name;

  public int getId() {
    return id ;
  }

  public String getName() {
    return name ;
  }

  public void setId(int id) {
    this .id = id;
  }

  public void setName(String name) {
    this .name = name;
  }

}

Establish operation interface:


 public interface BaseOperation {
 
   public List<?> findAll();
 }

The interface has only one method to get all the students
 
Creating session beans


@Stateless //This is a stateless Bean
@Remote (BaseOperation. class) //Specify the remote interface for the Bean
public class StudentDaoBean implements BaseOperation {
   
   //EntityManager is automatically configured and managed by the EJB container, corresponding to the value of the unitName attribute
persistence.xml  In the < persistence-unit name = "MyEJBProject" transaction-type = "JTA" ></ persistence-unit > name The configuration of the 
  @PersistenceContext(unitName = "MyEJBProject" )
  private EntityManager em;

  @SuppressWarnings( "unchecked" )
  public List<?> findAll() {
    System. out .println(" Query to ..." );
    List<StudentEntity> list = em.createQuery( " from StudentEntity ").getResultList();
    if (list != null) {
      Iterator<StudentEntity> it = list.iterator();
      while (it.hasNext()) {
        StudentEntity student = it.next();
        System. out .println(" students id:" + student.getId());
        System. out .println(" Student name: " + student.getName());
      }
    }
    System. out .println(" The query is completed ...." );
    return list;
  }

}

3. Data source configuration
It is important to note that the configurations in jboss6 and jboss7 are different.
Both jboss6 and previous versions added **-ds.xml to the deploy directory, where ** denotes any database name, in the case of mysql, the mysql-ds.xml file. In jboss7, it's different.
Switch the directory to Jboss installation directory, namely %JBOSS_HOME%, enter the modules/com directory, set up the folder mysqldatabase, enter, set up the mysql folder, enter, set up the main folder.
In the main directory, set up a module. XML file. The contents of the configuration file are:


<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="com.mysqldatabase.mysql">
   <resources>
     <resource-root path="mysql-connector-java-5.**-bin.jar"/>
   </resources>
   <dependencies>
     <module name="javax.api"/>
     <module name="javax.transaction.api"/>
     <module name="javax.servlet.api" optional="true"/>
   </dependencies>
</module>

In particular, the value of the module node property name is the path to the folder we just created. Resources represents the mysql-driven path. This means that you need to put the mysql driver in the main directory. The main directory contains two files, module. XML and the database driver file.
 
After completing the previous step, switch to the %JBOSS_HOME%\standalone configuration directory,
Open standalone.xml, search for the datasources, and configure it as follows


<datasources>
        <datasource jndi-name="java:jboss/KouMySQLDS" pool-name="MySQLDS" enabled="true" use-java-context="true">
          <connection-url>jdbc:mysql://localhost:3306/student</connection-url>
          <driver>mysql</driver>
          <security>
            <user-name>root</user-name>
            <password>1234</password>
          </security>
        </datasource>
        <drivers>
          <driver name="mysql" module="com.mysqldatabase.mysql">
            <driver-class>com.mysql.jdbc.Driver</driver-class>
            <xa-datasource-class>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</xa-datasource-class>
          </driver>
        </drivers>
      </datasources>

Jndi-name represents the jndi name of the data source, and connection-url represents the url string of the connection. By default, port 3306 is used, and the student library is used. The user name and password are configured in the first step. The path to which the module is configured is that of the module that was just configured.
 
The relevant configuration of jboss has been completed, then switch to the newly created project, where there is a persistence.xml configuration file, which is configured as follows, where jta-data-source is the jndi-name configured above.
 


< jta-data-source> java:jboss/KouMySQLDS </jta-data-source >
      < properties>
        < property name= "hibernate.hbm2ddl.auto" value ="validate" />
        < property name= "hibernate.jdbc.fetch_size" value ="15" />
        < property name= "hibernate.jdbc.batch_size" value ="10" />
        < property name= "hibernate.show_sql" value ="true" />
        < property name= "hibernate.format_sql" value ="true" ></ property>
      </ properties>

At this point, the server code and data source configuration are complete. The next thing you need to do is how to deploy the code and how to invoke the EJB service on the client side.
 
Deploy EJB services.
Type all the code you wrote in the project into a jar called ejbservice.jar. At the same time, only the entity beans and interfaces are packaged into a jar, named ebjinterface.jar, which will be used for client calls in the future.
Will ejbservice. Jar in the JBOSS_HOME % % \ standalone \ deployments directory. When jboss starts, the directory is automatically scanned. Then deploy the jar.
 
Ok, let's configure jboss under MyEclipse, launch jboss in MyEclipse, and observe the output of the console.
If the Deployed "ejbservice.jar" log appears, the ejb deployment is successful.
 
5. How is the client called?
There are two prerequisites for client-side invocation:
Introduce the jboss-ejb-client.properties configuration, jboss-client.jar and ejbinterface.jar. Jboss-client.jar is located in the jboss bin/client directory. Ejbinterface.jar is the interface jar that we just created for the client to use.
The configuration of jboss-ejb-client.properties is as follows:


endpoint.name= client-endpoint
remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED= false
remote.connections= default
remote.connection.default.host= localhost
remote.connection.default.port= 4447
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS= false
remote.connection.default.username= yourUsername
remote.connection.default.password= yourPassword

 
With these two conditions, you can safely create a test class ejbtest.java, write the client method.


public static void main(String[] args) {

    Properties props = new Properties();
    props.setProperty(Context. URL_PKG_PREFIXES,"org.jboss.ejb.client.naming" );
    try {
      Context context = new InitialContext(props);
      //Here need to pay attention to the string written: ejbservice said ejb package name, StudentDaoBean said our actual call session Bean, org. Easynoder. Ejb2. Dao. BaseOperation said the corresponding interface
      BaseOperation op = (BaseOperation) context
          .lookup("ejb:/ejbservice//StudentDaoBean!org.easynoder.ejb2.dao.BaseOperation" );
      op.findAll();
    } catch (NamingException e) {
      e.printStackTrace();
    }
  }

Run this code, you can successfully query the database data.
 
At this point, the EJB is deployed successfully.


Related articles: