EJB3.0实体Bean总结(EntityBean)

EJB3.0 实体Bean(EntityBean)
作者:waitbin 2007-07-25
1.从EJB3.0开始,持久化已经自成规范,被称为java Persistence API;
2 持久化配置文件persistence.xml;目录结构:工程->str->META-INF->persistence.xml
<?xml version="1.0"?>
<persistence xmlns="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">
    <persistence-unit name="jbossdb">
   <!-- weblogic config 
        <jta-data-source>foshanDS</jta-data-source>
        <class>com.foshanshop.ejb3.bean.Person</class>
        <properties>
            <property name="kodo.jdbc.SynchronizeMappings" value="buildSchema" />
        </properties>
-->
    <jta-data-source>java:/DefaultMySqlDS</jta-data-source>
    <properties>
      <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
    </properties>
  
    </persistence-unit>
</persistence>
************************************************************
3:jboss数据源配置:
(1)各种数据库配置模板可在jboss安装目录[Jboss]\docs\examples\jca 数据库名 -ds.xml下找到如( mysql-ds.xml)
mysql-ds.xml:
<?xmlversion="1.0"encoding="UTF-8"?>
   <datasources>
       <local-tx-datasource>
         <jndi-name>DefaultMySqlDS</jndi-name>
         <connection-url>jdbc:mysql://localhost:3306/foshanshop?useUnicode=true&characterEncoding=GBK
         </connection-url>
         <driver-class>org.gjt.mm.mysql.Driver</driver-class>
         <user-name>root</user-name>
         <password>123456</password>
        <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>
*************************************************************
oracle-ds.xml:
<?xmlversion="1.0"encoding="UTF-8"?>
  <datasources>
   <local-tx-datasource>
    <jndi-name>OracleDS</jndi-name>
    <connection-url>jdbc:oracle:thin:@nd:1521:FS</connection-url>
    <driver-class>oracle.jdbc.driver.OracleDriver</driver-class>
   <user-name>root</user-name>
   <password>123456</password>
   <SetBigStringTryClob>true</SetBigStringTryClob>
  <exception-sorter-class-name>
  org.jboss.resource.adapter.jdbc.vendor.OracleExceptionSorter</exception-sorter-class-name>
  <metadata>
  <type-mapping>Oracle9i</type-mapping>
  </metadata>
  </local-tx-datasource>
</datasources>
(2)不管何种数据库一定要把驱动包(.jar)放在jboss安装目录[jboss]\server\default\lib下
(3)放置后需要重启jboss服务
4:建立实体Person表的映射Bean
   package com.ejb.interfacesdao;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@SuppressWarnings("serial")
@Entity
@Table(name="Person")
public class Person implements java.io.Serializable{
    private int id;
    private String name;
    private String sex;
    private Date birthday;
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Temporal(value=TemporalType.DATE)
    public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Column(name="name",nullable=false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name="sex",nullable=false )
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
********************************************************
5:创建Session Bean的业务接口PersonDao:
   package com.ejb.interfaces;

import java.util.Date;
import java.util.List;

import com.ejb.interfacesdao.Person;

public interface PersonDao {
   public boolean insert(String name,String sex,Date birthday);
   public String getName(int id);
   public Person getPersonById(int id);
   public List getPersonList();
   public boolean update(Person person);
}
**********************************************************
6:创建Session Bean 业务接口的实现类:PersonDaoBean
   package com.ejb.interfacesdao;

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.ejb.interfaces.PersonDao;
@Stateless
@Remote(PersonDao.class)
public class PersonDaoBean implements PersonDao{
    @PersistenceContext
    protected EntityManager em;
public String getName(int id) {
Person person =em.find(Person.class, Integer.valueOf(id));
return person.getName();
}

public Person getPersonById(int id) {

return em.find(Person.class, id);
}

public List getPersonList() {
Query query =  em.createQuery("from Person ");
List list = query.getResultList();
return list;
}

public boolean insert(String name, String sex, Date birthday) {
Person person = new Person();
person.setName(name);
person.setBirthday(birthday);
person.setSex(sex);
em.persist(person);
return true;
}

public boolean update(Person person) {
em.merge(person);
return true;
}

}
*****************************************
7:创建Ant配置文件 build.xml,在整个EJB发布中起很重要的作用:
  <?xml version="1.0" encoding="UTF-8"?>
<project name="HelloWord" default="ejbjar" basedir="..">

<property environment="env" />
<property name="app.dir" value="${basedir}/HelloWord" />
<property name="src.dir" value="${app.dir}/src" />
<property name="jboss.home" value="${env.JBOSS_HOME}" />
<property name="jboss.server.config" value="default" />
<property name="build.dir" value="${app.dir}/build" />
<property name="build.classes.dir" value="${build.dir}/classes" />

<!-- Build classpath -->
<path id="build.classpath">
<fileset dir="D:\EEEE\jboss\HelloWord\lib">
<include name="*.jar" />
</fileset>
<pathelement location="${build.classes.dir}" />
</path>

<!-- =================================================================== -->
<!-- Prepares the build directory                                        -->
<!-- =================================================================== -->
<target name="prepare" depends="clean">
<mkdir dir="${build.dir}" />
<mkdir dir="${build.classes.dir}" />
</target>

<!-- =================================================================== -->
<!-- Compiles the source code                                            -->
<!-- =================================================================== -->
<target name="compile" depends="prepare" description="编绎">
<javac srcdir="${src.dir}" destdir="${build.classes.dir}" debug="on" deprecation="on" optimize="off" includes="**">
<classpath refid="build.classpath" />

<exclude name="junit/**/*.*" />
</javac>
</target>

<target name="ejbjar" depends="compile" description="创建EJB发布包">
<jar jarfile="${app.dir}/HelloWorld.jar">
<fileset dir="${build.classes.dir}">
<include name="com/**/*.class" />
</fileset>
<metainf dir="${src.dir}/META-INF">
<include name="**" />
</metainf>
</jar>
</target>

<target name="deploy" depends="ejbjar">
<copy file="${app.dir}/HelloWorld.jar" todir="${jboss.home}/server/${jboss.server.config}/deploy" />
</target>

<!-- =================================================================== -->
<!-- Cleans up generated stuff                                           -->
<!-- =================================================================== -->
<target name="clean">
<delete dir="${build.dir}" />
<delete file="${jboss.home}/server/${jboss.server.config}/deploy/EntityBean.jar" />
</target>

</project>
**********************************
8:把实体类和persistence.xml文件打包成jar, persistence.xml文件放在jar文件的META-INF目录下
9:在客户端测试必须导入jboss安装目录下的client下所有的包
10:发布完成客户端测试代码:
  EJbFactory:
  package com.test;

import java.util.Properties;

import javax.naming.InitialContext;
import javax.naming.NamingException;

public class EJbFactory {
public static Object getEjB(String jndipath) {
try {
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:org.jnp.interfaces");
InitialContext ctx;
ctx = new InitialContext(props);
return ctx.lookup(jndipath);
} catch (NamingException e) {

e.printStackTrace();
}
return null;
}
}

*******************************************
测试类:EntityBeanTest:
package com.test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import com.ejb.interfaces.PersonDao;
import com.ejb.interfacesdao.Person;

public class EntityBeanTest {
public static void main(String[] args) throws ParseException {
PersonDao persondao = (PersonDao)EJbFactory.getEjB("PersonDaoBean/remote");
//插入数据
if(!true)
{
SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd");
persondao.insert("admin","women", format.parse("2007-07-25"));
}
//查找所有
if(!true)
{
List list = persondao.getPersonList();
for(Object o:list)
{
Person person = (Person)o;
System.out.println("姓名为:"+person.getName()+ "生日:"+ person.getBirthday() + "性别"+ person.getSex());
}
}
//根据编号找名字
if(true)
{
Person person = persondao.getPersonById(Integer.valueOf(2));
System.out.println("对应名字:"+person.getName());
}

}

}
*********************************************
11.在上述过程中一般会遇到的问题解决:
   (1).  localhost可以访问与本机IP不能访问
解决方式:
  修改JBOSS_HOME\server\default\deploy\jboss-web.deployer下的server.xml

<Connector port="8080" address="localhost"

将address改为0.0.0.0或者你的实际IP 重启 JBOSS 然后就可以通过ip访问。
(2). jboss-4.2.0.GA下发布EJB ,利用ip地址无法访问,抛出异常:
  Could not obtain connection to any of these urls: 192.168.1.15:1099 and discovery failed with error: javax.naming.CommunicationException: Receive timed out [Root exception is java.net.SocketTimeoutException: Receive timed out]

解决方式:
For Windows, use

run.bat -b 0.0.0.0

(3).java.lang.RuntimeException: Illegal @PersistenceUnit on protected javax.persiste
nce.EntityManager example.entity.PersonDAOBean.em :There is no default persisten
ce unit in this deployment.
解决方式:stateless Bean 定义的时候,加上:
  @PersistenceContext(unitName="jbossdb")
protected EntityManager em;
  制定数据库的名称即可。

(4).javax.naming.NameNotFoundException: PersonDAOBean not bound
解决方式:

(5).11:00:53,453 ERROR [URLDeploymentScanner] Incomplete Deployment listing:

--- MBeans waiting for other MBeans ---
ObjectName: jboss.j2ee:jar=HelloWorld.jar,name=PersonDAOBean,service=EJB3
  State: NOTYETINSTALLED
  I Depend On:
    persistence.units:unitName=jbossdb

--- MBEANS THAT ARE THE ROOT CAUSE OF THE PROBLEM ---
ObjectName: persistence.units:unitName=jbossdb
  State: NOTYETINSTALLED
  Depends On Me:
    jboss.j2ee:jar=HelloWorld.jar,name=PersonDAOBean,service=EJB3
解决方式:4和5是一个原因:
  修改build.xml
  <target name="ejbjar" depends="compile" description="创建EJB发布包">
<jar jarfile="${app.dir}/HelloWorld.jar">
<fileset dir="${build.classes.dir}">
<include name="**/*.class" />
<exclude name="junit/debug/*.*"/>
</fileset>
<metainf dir="${src.dir}/META-INF">
<include name="**" />
   </metainf>
</jar>
</target>
   因为缺少了metainf,导致.jar包里面没有persistence.xml文件。

(6).Caused by: java.sql.SQLException: Unknown type '16 in column 3 of 4 in binary-en
coded result set.
引起的愿意我把sex的属性设置为Boolean (EJB Entity Bean 定义)
解决方式:

(7).12:05:39,640 ERROR [JDBCExceptionReporter] Data too long for column 'sex' at row

  引起原因我在sex的字段里面插入了中文。
解决方案:在mysql的安装路径找到 my.ini 文件 ,修改 sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
为下面即可。 #sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
sql-mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
 



[size=18][/size]

你可能感兴趣的:(java,bean,mysql,jboss,ejb)