JBOSS7 Deploying EJB Connection MySQL

Source: Internet
Author: User
Tags jboss

This article records the addition of MySQL database to the original Smarthome project, configures the data source, adds the entity class and configuration file, adds the calling method, and successfully uses the client program connection webservice to remotely invoke the EJB connection database to obtain the data.

Development environment: Win7,jdk1.7,jboss As7.1.1final,mysql 5.6,myeclipse 10.

First, MySQL

Table, etc., omitted here. (Note that connections use remote users and cannot use localhost users)

Ii. Configuring the MySQL data source in JBOSS7

Configuring a database connection in JBoss requires two steps:

1. Installing the JDBC Driver

First go to the JBOSS installation directory, that is,%jboss_home%, enter modules/com/, create a new MySQL folder, enter, create the main folder. In the main directory, add the following two files:

Jboss_home/modules/com/mysql/main/mysql-connector-java-5.1.17-bin.jar
Jboss_home/modules/com/mysql/main/module.xml

Mysql-connector-java-5.1.17-bin.jar is a JDBC driver, download link:

http://dev.mysql.com/downloads/connector/j/

The ② module.xml file, which records the configuration of the add-on module, is shown in the code below. Where the module node name is the established folder path, resources represents the path of the MySQL drive.

<?XML version= "1.0" encoding= "UTF-8"?><Modulexmlns= "urn:jboss:module:1.0"name= "Com.mysql">     <Resources>          <Resource-rootPath= "Mysql-connector-java-5.1.37-bin.jar"/>     </Resources>     <Dependencies>          <Modulename= "Javax.api"/>          <Modulename= "Javax.transaction.api"/>          <Modulename= "Javax.servlet.api"Optional= "true"/>     </Dependencies></Module>

2. Adding a data source to the configuration

Modify the Standalone.xml file under the/jboss_home/standalone/configuration directory, locate the datasources subsystem, and modify the configuration as follows, where jndi-name represents the data source name:

<Subsystemxmlns= "urn:jboss:domain:datasources:1.0"><datasources>   <DataSourceenabled= "true"Jndi-name= "Java:/mysqlds"JTA= "true"Pool-name= "Mysqlds_pool"USE-CCM= "true"Use-java-context= "true">    <Connection-url>Jdbc:mysql://115.xxx.xxx.xxx:3306/smarthome1</Connection-url>    <Driver>Mysql</Driver>    <Pool/>    <Security>      <User-name>Admin</User-name>      <Password>123456</Password>    </Security>    <Statement/>    <Timeout>      <idle-timeout-minutes>0</idle-timeout-minutes>      <Query-timeout>600</Query-timeout>    </Timeout></DataSource>  <Drivers>    <DriverModule= "Com.mysql"name= "MySQL">      <Driver-class>Com.mysql.jdbc.Driver</Driver-class>      <Xa-datasource-class>Com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</Xa-datasource-class>    </Driver>                     </Drivers></datasources>
</Subsystem>

Locate the JPA subsystem, modify the configuration as follows, and note that the datasource is consistent with the Jndi name above:

<xmlns= "urn:jboss:domain:jpa:1.0">     <  Default-datasource = "Java:/mysqlds" /> </ Subsystem >

If the above configuration is successful, the boot will not error if JBOSS7 does not deploy any ejbs, view the jboss_home/modules/com/mysql/main/path, You will find that the Mysql-connector-java-5.1.17-bin.jar.index file was generated, indicating that the module was added successfully.

Third, write the Bean entity and its configuration file, add the calling method

Bean entity (be careful not to generate serial version IDs automatically, otherwise you will get an error):

 PackageSmarthome.po;Importjava.io.Serializable;ImportJavax.persistence.Column;Importjavax.persistence.Entity;ImportJavax.persistence.GeneratedValue;ImportJavax.persistence.GenerationType;Importjavax.persistence.Id;Importjavax.persistence.Table; @Entity//indicates that this is an entity bean@Table (name = "Data")//Mapping with database table data Public classDataImplementsserializable{@Id//indicates the ID of the entity@GeneratedValue (strategy = GenerationType. AUTO)//ID Generation Policy@Column (name = "id")//corresponding data table ID field    PrivateInteger ID;//Data Number@Column (Name= "UID")//corresponding data table uid field    PrivateString uid;//User ID@Column (Name= "Guest")//corresponds to the data table's field    PrivateString;//Room Name: Living room, bedroom@Column (Name= "type")//corresponding data table Type field    PrivateString type;//data type: Temperature temp, humidity HUMD, illumination light, alarm alarm@Column (Name= "value")//corresponding data table value field    PrivateString value;//Data Values//Setter and Getter methods omitted}

Add methods to call the database in the session interface and the Servicesession class:

@PersistenceContext (unitname = "Data" )    PrivateEntitymanager em; //get database data based on user ID and room ID@SuppressWarnings ("Unchecked")     Publicresultmap Getdatabyuidandroomid (String) {Resultmap Resultmap=NewResultmap (); String Status=NULL;//result Status: Success,fail,overtime,errorString Description =NULL;//result description, fail when describing failure reasonHashmap<string, object> resultdata=NewHashmap<string, object>(); System.out.println ("Query starts ..."); List<Data> list = Em.createquery ("From Data"). Getresultlist (); if(List! =NULL) {Status= "Success"; Iterator<Data> it =List.iterator ();  while(It.hasnext ()) {Data Data=It.next (); if(Data.getuid (). Equals (User.getid ()) &&data.getroom (). Equals (Guest)                    {Resultdata.put (Data.gettype (), Data.getvalue ()); System.out.println ("Data type:" +Data.gettype ()); System.out.println ("Data value:" +Data.getvalue ()); }                           }        }        Else{Status= "Fail"; Description= "No room information found for this user"; } System.out.println ("Query complete ...." );        Resultmap.setstatus (status);        Resultmap.setdescription (description);        Resultmap.setresultdata (Resultdata); returnResultmap; }

Add the Persistence.xml file to the project's Meta-inf directory, which will refer to the DataSource used to match the entity to the database with the following code: (and note that the file is added when the project is packaged as a jar)

<?XML version= "1.0" encoding= "UTF-8"?><Persistencexmlns= "Http://java.sun.com/xml/ns/persistence"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"version= "1.0">    <!--Name property defines the name of the persisted unit (name required, null value is also valid) -    <Persistence-unitname= "Data"Transaction-type= "JTA">        <provider>Org.hibernate.ejb.HibernatePersistence</provider>            <!--Jta-data-source used to specify the global Jndi name of the Jta data source used by the persistence provider (optional) -            <Jta-data-source>Java:/mysqlds</Jta-data-source>        <Properties>            < Propertyname= "Hibernate.dialect"value= "Org.hibernate.dialect.MySQLDialect" />        </Properties>    </Persistence-unit></Persistence> 

The client connection EJB method is unchanged, and the associated code that invokes the method returns the result is omitted here.

JBOSS7 Deploying EJB Connection MySQL

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.