1. Create a database-related table first. The following is an online document. Save a little bit of writing trouble :)
I.
JBoss has a default data source defaultds, which uses the built-in HSQLDB database of JBoss. You may use different
Databases, such as MySQL, MSSQLServer, and Oracle. For the data source configuration templates of various databases, you can go to the [JBoss installation project
Directory] \ docs \ examples \ JCA. The default name is database name +-Ds. xml.
No matter which database you use, you need to place the driver jar package in the [JBoss installation directory] \ Server \ All \ lib directory
Enable after Configuration
Run the JBoss server.
The database used in this tutorial is mysql-5.0.22 and ms SQL Server2000, using the driver jar package is as follows:
MySQL: mysql-connector-java-3.1.13-bin.jar
Ms SQL Server2000: msbase. jar, MSSQLServer. jar, msutil. Jar
The following describes the MySQL data source configuration, the data source configuration file name format must be xxx-ds.xml, such:
Mysql-ds.xml, mssqlserver-ds.xml, oracle-ds.xml.
After the data source file is configured, it must be placed in the [JBoss installation directory]/Server/config-name/deploy directory. In this tutorial, the configuration name is all,
Therefore, the path is the [JBoss installation directory]/Server/All/deploy directory.
The following defines a MySQL data source named defaultmysqlds. The Connection database is foshanshop, the database logon username is root, the password is 123456, and the database Driver Class is org. gjt. Mm. MySQL. Driver. You only need to modify the Database Name and logon username and password.
Directly.
Mysql-ds.xml
<? XML version = "1.0" encoding = "UTF-8"?>
<Datasources>
<Local-TX-datasource>
<JNDI-Name> defaultmysqlds </JNDI-Name>
<Connection-URL> JDBC: mysql: // localhost: 3306/foshanshop?
Useunicode = true & amp; characterencoding = GBK
</Connection-URL>
<Driver-class> org. gjt. Mm. MySQL. Driver </driver-class>
<User-Name> root </user-Name>
& Lt; password & gt; 123456 & lt;/password & gt;
<Exception-sorter-class-Name> org. JBoss. Resource. Adapter. JDBC. Vendor. mysqlexceptionsorter
</Exception-sorter-class-Name>
<Metadata>
<Type-mapping> mysql </type-mapping>
</Metadata>
</Local-TX-datasource>
</Datasources>
II.
1. Configure the data source and place it in the [JBoss installation directory]/Server/All/deploy directory. Place the database driver jar package in [JBoss
Installation Directory] \ Server \ All \ lib directory. After placing the directory, restart the JBoss server. If the data source already exists, you do not need to configure it.
2. Configure the persistence. xml file to specify the source data source and parameters used in the file.
3. compress the object class and persistence. xml file into jar and put persistence. xml in the META-INF directory of the JAR file.
Remember, in persistence. XML
<JTA-data-source> JAVA:/defaultmysqlds </JTA-data-source> cannot be written
<JTA-data-source> defaultmysqlds </JTA-data-source> otherwise, an error is returned when entity EJB is published.
III.
Introduce the database tables to be mapped before development
Person
Field Name field type attribute description
Personid (primary key) int (11) not null personnel ID
Personname varchar (32) not null name
Sex tinyint (1) not null gender
Age smallint (6) Not null age
Birthday datetime null Date of birth
Create an Entity Bean mapped to the person table
Package com. foshanshop. ejb3.bean;
Import java. Io. serializable;
Import java. util. date;
Import javax. Persistence. column;
Import javax. Persistence. entity;
Import javax. Persistence. generatedvalue;
Import javax. Persistence. ID;
Import javax. Persistence. Table;
Import javax. Persistence. Temporal;
Import javax. Persistence. temporaltype;
Import javax. Persistence. generationtype;
@ Suppresswarnings ("serial ")
@ Entity
@ Table (name = "person ")
Public class person implements serializable {
Private integer personid;
Private string name;
Private Boolean sex;
Private short age;
Private date birthday;
@ ID
@ Generatedvalue (Strategy = generationtype. Auto)
Public integer getpersonid (){
Return personid;
}
Public void setpersonid (integer personid ){
This. personid = personid;
}
@ Column (nullable = false, length = 32)
Public String getname (){
Return name;
}
Public void setname (string name ){
This. Name = Name;
}
@ Column (nullable = false)
Public Boolean getsex (){
Return sex;
}
Public void setsex (Boolean sex ){
This. Sex = sex;
}
@ Column (nullable = false)
Public short getage (){
Return age;
}
Public void setage (short age ){
This. Age = age;
}
@ Temporal (value = temporaltype. Date)
Public date getbirthday (){
Return birthday;
}
Public void setbirthday (date birthday ){
This. Birthday = birthday;
}
}
To use the above Entity Bean, we define a session bean as its user. The following is the service connection of the Session Bean.
This section defines two business methods: insertperson and getpersonnamebyid. insertperson is used to add a person,
Getpersonnamebyid Root
Obtain the person's name based on the personid.
Persondao. Java
Package com. foshanshop. ejb3;
Import java. util. date;
Public interface persondao {
Public Boolean insertperson (string name, Boolean sex, short age, date birthday );
Public String getpersonnamebyid (INT personid );
}
The following is the implementation of Session Bean.
Persondaobean. Java
Package com. foshanshop. ejb3.impl;
Import java. util. date;
Import java. util. List;
Import javax. EJB. Remote;
Import javax. EJB. stateless;
Import javax. Persistence. entitymanager;
Import javax. Persistence. persistencecontext;
Import javax. Persistence. query;
Import com. foshanshop. ejb3.persondao;
Import com. foshanshop. ejb3.bean. person;
@ Stateless
@ Remote (persondao. Class)
Public class persondaobean implements persondao {
@ Persistencecontext
Protected entitymanager em;
Public String getpersonnamebyid (INT personid ){
Person = em. Find (person. Class, integer. valueof (personid ));
Return person. getname ();
}
Public Boolean insertperson (string name, Boolean sex, short age, date birthday ){
Try {
Person = new person ();
Person. setname (name );
Person. setsex (sex );
Person. setage (short. valueof (AGE ));
Person. setbirthday (birthday );
Em. persist (person); // use persist to add data
} Catch (exception e ){
E. printstacktrace ();
Return false;
}
Return true;
}
Public Person getpersonbyid (INT personid ){
Return em. Find (person. Class, personid );
}
Public Boolean updateperson (person ){
Try {
Em. Merge (person); // update data with merge
} Catch (exception e ){
E. printstacktrace ();
Return false;
}
Return true;
}
Public list getpersonlist (){
Query query = em. createquery ("from person order by personid ASC ");
List list = query. getresultlist ();
Return list;
}
}
The above uses an object: entitymanager em, entitymanager is automatically managed and configured by the EJB container, not
Users required
Create it by yourself and use it as the operation Entity Bean. For more information, see entitymanager.
The above em. Find () method is used to query records whose primary key ID is personid. The EM. persist () method is used to insert a record into the database.
You may feel
It is strange that the entitymanager em value is not displayed in the class, but can be directly used later. This is because in the Entity Bean
Load
The container uses @ persistencecontext annotations to dynamically inject entitymanager objects.
If multiple persistence contents are configured in the persistence. xml file. You need to specify the persistence name to inject entitymanager
Object.
Specify the unitname attribute through the annotation of @ persistencecontext, for example:
@ Persistencecontext (unitname = "foshanshop ")
Entitymanager em;
If there is only one persistent content configuration, you do not need to specify it explicitly.
The following is the configuration of the persistence. xml file:
<Persistence>
<Persistence-unit name = "foshanshop">
<JTA-data-source> JAVA:/defaultmysqlds </JTA-data-source>
<Properties>
<Property name = "hibernate. hbm2ddl. Auto" value = "Create-drop"/>
</Properties>
</Persistence-unit>
</Persistence>
Compress him
JAR file and publish it to JBoss.
Check whether the data source used in the persistence. xml file is configured before publishing.
The following exception often occurs when the foshanshop table is not created in the database or the <Property
Name = "dialect"> org. hibernate. dialect. sqlserverdialect </property>
Objectname: persistence. Units: jar = entitybean. jar, unitname = foshanshop
State: Failed
Reason: javax. Persistence. persistenceexception: org. hibernate. hibernateexception:
Hibernate dialect must be explicitly set
I depend on:
JBoss. JCA: service = performancebinding, name = defaultmysqlds
Depends on me:
JBoss. J2EE: jar = entitybean. jar, name = persondaobean, service = ejb3
When the Entity Bean is published successfully
Then, we can check whether the person table is generated in the database,
The following is the JSP client code:
Entitybeantest. jsp
<% @ Page contenttype = "text/html; charset = GBK" %>
<% @ Page import = "com. foshanshop. ejb3.persondao,
Javax. Naming .*,
Java. util. properties,
Java. util. date,
Java. Text. simpledateformat "%>
<%
Properties props = new properties ();
Props. setproperty ("Java. Naming. Factory. Initial ",
"Org. jnp. Interfaces. namingcontextfactory ");
Props. setproperty ("Java. Naming. provider. url", "localhost: 1099 ");
Props. setproperty ("Java. Naming. Factory. url. pkgs", "org. JBoss. Naming ");
Initialcontext CTX = new initialcontext (props );
Try {
Persondao = (persondao) CTX. Lookup ("persondaobean/remote ");
Simpledateformat formatter = new simpledateformat ("yyyy-mm-dd ");
Persondao. insertperson ("decimal", true, (short) 22, formatter. parse ("1985-10-17"); // Add a person
Out. println (persondao. getpersonnamebyid (1); // The person whose personid is 1
} Catch (exception e ){
Out. println (E. getmessage ());
}
%>
The code above adds a person to the database, and then obtains the name of the person with a personid of 1.