Entity Bean的开发 和 Jboss 数据源的配置

11 篇文章 0 订阅
[size=medium][b]//-------------- 实体bean 的开发 [/b][/size]


1:实体bean 属于Java持久化规范 (简称JPA)里的技术,实体bean通过元数据在javabean和数据库表之间建立映射关系,然后java程序员就可以随性所欲 使用面向对象的编程思想来操作数据了.

2:JPA的出现主要是为了简化现有的持久化开发工作和整合ORM技术.

3:目前实现了JPA规范过的主流产品有Hibernate TopLink OpenJPA ibatis mybatis .

4:在 jboss中采用HIbernate 最为其持久化实现产品.


[img]http://dl.iteye.com/upload/attachment/0080/8636/cba1631a-30e4-387e-a3ca-72350aa84b89.jpg[/img]

[size=medium][b]------配置 jboss 的数据源[/b][/size]

1.数据库连接对象的创建是很耗性能的,配置数据源后可以提升性能..

jboss5.0 和 jboss 6.0 一样

EBJ 提供了模版啦!!
E:\jboss-5.0.0.GA\docs\examples\jca 里面就可以看到很多数据的配置模版
比如mysql 的配置模版 mysql-ds.xml

然后修改
比如
<jndi-name>MySqlDS</jndi-name>
<connection-url>jdbc:mysql://mysql-hostname:3306/jbossdb</connection-url>
<driver-class>com.mysql.jdbc.Driver</driver-class>
<user-name>x</user-name>
<password>y</password>

第一个:修改 jndi名称
第二个Ip地址: localhost:3306
第三个数据名称: jbossdb---> spdb1 (创建数据库的时候一般使用 UTF-8编码)
第四个用户名:x--->root
第五个密码y:123456

注意:
数据源的文件的取名:必须要以 -ds 结尾

发布之前 还要注意 "数据库的驱动类"
复制到 E:\jboss-5.0.0.GA\server\default\lib

完成后 将修改好的 mysql-ds.xml 拷贝到
E:\jboss-5.0.0.GA\server\default\deploy

此时就会看到 数据源的jndi名称为: java:MySqlDS

到jboss控制后台 查看 数据源
http://localhost:8080/jmx-console/ --->jboss.jca---name:java:MySqlDS;

然后要注意的一个 就是 查看数据源一些属性的配置
查看 连接池的 属性 点击进去
name=JbossOracleDS,service=ManagedConnectionPool

MaxSize :最大可以数量 默认 20 条
InUseConnectionCount :正在使用的连接统计.
MinSize :最小的连接数量
BlockingTimeoutMillis:最大等待时间 30秒

修改后 点击 Apply Changes 只用在jboss 运行时候就生效 关闭 就会丢失修改后的值 要永久的修改 就要修改数据源文件 mysql-ds.xml 添加参数

<min-pool-size>1</min-pool-size>
<min-pool-size>50</min-pool-size>

注意
正在使用人数 和 数据源的最大连接数 如果数量 一直是满的 就要考虑 是否扩大连接数了



--给出一个 oralce的配置 oracle-ds.xml

<?xml version="1.0" encoding="UTF-8"?>

<!-- ===================================================================== -->
<!-- -->
<!-- JBoss Server Configuration -->
<!-- -->
<!-- ===================================================================== -->

<!-- $Id: oracle-ds.xml 23720 2004-09-15 14:37:40Z loubyansky $ -->
<!-- ==================================================================== -->
<!-- Datasource config for Oracle originally from Steven Coy -->
<!-- ==================================================================== -->


<datasources>
<local-tx-datasource>
<jndi-name>JbossOracleDS</jndi-name>
<connection-url>jdbc:oracle:thin:@192.168.1.242:1521:ora11g</connection-url>
<!--

Here are a couple of the possible OCI configurations.
For more information, see http://otn.oracle.com/docs/products/oracle9i/doc_library/release2/java.920/a96654/toc.htm

<connection-url>jdbc:oracle:oci:@youroracle-tns-name</connection-url>
or
<connection-url>jdbc:oracle:oci:@(description=(address=(host=youroraclehost)(protocol=tcp)(port=1521))(connect_data=(SERVICE_NAME=yourservicename)))</connection-url>

Clearly, its better to have TNS set up properly.
-->
<driver-class>oracle.jdbc.driver.OracleDriver</driver-class>
<user-name>bjdata</user-name>
<password>bjdata</password>
<!-- Uses the pingDatabase method to check a connection is still valid before handing it out from the pool -->
<!--valid-connection-checker-class-name>org.jboss.resource.adapter.jdbc.vendor.OracleValidConnectionChecker</valid-connection-checker-class-name-->
<!-- Checks the Oracle error codes and messages for fatal errors -->
<exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.OracleExceptionSorter</exception-sorter-class-name>
<!-- sql to call when connection is created
<new-connection-sql>some arbitrary sql</new-connection-sql>
-->

<!-- sql to call on an existing pooled connection when it is obtained from pool - the OracleValidConnectionChecker is prefered
<check-valid-connection-sql>some arbitrary sql</check-valid-connection-sql>
-->

<!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml (optional) -->
<metadata>
<type-mapping>Oracle10g</type-mapping>
</metadata>
</local-tx-datasource>

</datasources>



添加JPA的持久化配置文件 persistence.xml 类是 hibernate

<!--根据JPA的规范的要求,在实体bean的应用中,我们需要在应用的类路径下的META-INF目录加入持久化配置文件 persistence.xml-->

<?xml version="1.0" encoding="UTF-8"?>
<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">
<!-- 持久化单元 (可以配置多个)
JTA: 全局事物 ejb默认的事务类型 可以不用设置
RESOURCE_LOCAL:本地事务
添加数据源 :提高性能
-->
<persistence-unit name="mytest" transaction-type="JTA" >
<!-- 配置的jboss 数据源jndi名称 -->
<jta-data-source>java:JbossOracleDS</jta-data-source>

<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
<!-- 自动生存表接口
create-drop:启动创建表,程序 卸载的时候会删除表结构 测试的有用
create:启动创建, 卸载的时候不会删除
update:保留数据库的数据,如果添加新的字段后,会同步到数据库中.
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
-->
<!-- 打印 sql语句 -->
<property name="hibernate.show_sql" value="true"/>
<!--格式化sql语句 -->
<property name="hibernate.format_sql" value="true"/>
</properties>
</persistence-unit>

</persistence>


jndi.properties

java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.provider.url=localhost:1099


[b]---编写 实体bean [/b]
采用注解 配置 ORM 映射关系


BiAnswer.java

package com.sh.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.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity //@Entity(name="xxx") 可以修改
@Table(name="bi_answer")
public class BiAnswer implements Serializable{

private static final long serialVersionUID = 5687494436224059560L;

private Integer id;
@Column(name="answer",length=300,nullable=true)
private String answer;
private String correct;
private Integer sortid;
private Integer qid;
private Date createtime;

public BiAnswer() {
}
public BiAnswer(Integer id,String answer,Integer qid) {
this.id=id;
this.answer=answer;
this.qid=qid;
}

@Id @Column(name="id") //这些注解 只能标注在 get() 方法上 不能在set 上 还可以标注 字段上
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}

public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
@Column(name="correct",length=1,nullable=true)
public String getCorrect() {
return correct;
}
public void setCorrect(String correct) {
this.correct = correct;
}
@Column(name="sortid",length=10,nullable=true)
public Integer getSortid() {
return sortid;
}
public void setSortid(Integer sortid) {
this.sortid = sortid;
}
@Column(name="qid",length=10,nullable=true)
public Integer getQid() {
return qid;
}
public void setQid(Integer qid) {
this.qid = qid;
}
@Column(name="createtime",nullable=true)
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BiAnswer other = (BiAnswer) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}

BiAnswerService.java

package com.sh.ejb3.service;

import java.util.List;

import com.sh.ejb3.bean.BiAnswer;

public interface BiAnswerService {

public void save (BiAnswer answer);
public void update(BiAnswer answer);
public void delete(Integer answerid);
public BiAnswer getAnswer(Integer answerid);
public List<BiAnswer> getAnswers();
}


BiAnswerServiceBean.java

package com.sh.ejb3.service.impl;

import java.util.List;

import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;

import com.sh.ejb3.bean.BiAnswer;
import com.sh.ejb3.service.BiAnswerService;
@Stateless
@Remote(BiAnswerService.class)
public class BiAnswerServiceBean implements BiAnswerService {

//使用实体管理器 如果只有一个 持久化单元 unitName可以不用配置 否则有多个的话 就需要配置
@PersistenceContext(unitName="mytest") EntityManager em;

@Override
public void save(BiAnswer answer) {
// TODO Auto-generated method stub
em.persist(answer); //只将持久化字段保存到数据库中对应的字段
}

@Override
public void update(BiAnswer answer) {
// TODO Auto-generated method stub
em.merge(answer); //answer 为 游离状态 而且 进行了修改 使用 merge
}

@Override
public void delete(Integer answerid) {
// TODO Auto-generated method stub
//getReference 返回的是一个 代理对象 一般都是 懒加载 和 Hibernate中 一样
em.remove(em.getReference(BiAnswer.class, answerid)); //处于托管状态
}

@Override
public BiAnswer getAnswer(Integer answerid) {
// TODO Auto-generated method stub
return em.find(BiAnswer.class, answerid); //如果没有找到就返回一个null
}

@SuppressWarnings("unchecked") //终止警告
@Override
public List<BiAnswer> getAnswers() {
// TODO Auto-generated method stub
//注意 采用的 HQL 语句 注意 BiAnswer 的类的简单名称 可以通过 @Entity(name="xxx") 修改
return em.createQuery("SELECT o from BiAnswer o").getResultList();
}

}



BiAnswerServiceTest.java

package junit.test;

import static org.junit.Assert.fail;

import java.util.List;

import javax.naming.InitialContext;

import org.junit.BeforeClass;
import org.junit.Test;

import com.sh.ejb3.bean.BiAnswer;
import com.sh.ejb3.service.BiAnswerService;

public class BiAnswerServiceTest {
private static BiAnswerService answerService;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
try {
//不采用硬编码 就可以直接 添加 一个jndi.properties 会自动从java类路径中 去寻找 服务器的配置文件
InitialContext ctx=new InitialContext();//InitialContext(props);
answerService=(BiAnswerService)ctx.lookup("BiAnswerServiceBean/remote"); //测试 远程接口
} catch (Exception e) {
e.printStackTrace();
}
}

@Test
public void testSave() {
answerService.save(new BiAnswer(1050,"5等南瓜多少分?",1040));
}

@Test
public void testUpdate() {
BiAnswer answer=answerService.getAnswer(1048);
answer.setAnswer("家园被污染了!!呜呜");
answerService.update(answer);
}
}


--使用 Ant 进行编译
build.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- ======================================================================
2013-2-25 下午1:53:33

project
description

Bin
====================================================================== -->
<project name="EntityBean" basedir=".">
<description>
description
</description>
<!-- 设置项目原目录 -->
<property name="src.dir" value="${basedir}\src" />
<!-- 获取环境变量 -->
<property environment="env"/>
<property name="jboss.home" value="${env.JBOSS_HOME}"/>
<property name="jboss.server.config" value="default"/>
<property name="build.dir" value="${basedir}\build"/>

<!-- 引入 jboss client 下的 所有jar -->
<path id="build.classpath">
<fileset dir="${jboss.home}\client">
<include name="*.jar"/>
</fileset>
<!-- 讲编译过后的路径加入到 path中去 方便 接口和实现的引用 -->
<pathelement location="${build.dir}"/>
</path>


<target name="prepare" description="创建build目录">
<delete dir="${build.dir}"/>
<mkdir dir="${build.dir}"/>
</target>

<!-- - - - - - - - - - - - - - - - - -
target: compile
- - - - - - - - - - - - - - - - - -->
<target name="compile" depends="prepare" description="编译">
<javac srcdir="${src.dir}" destdir="${build.dir}" includeantruntime="false" includes="com/**">
<classpath refid="build.classpath"/>
</javac>
</target>

<!-- =================================
target: ejbjar
================================= -->
<target name="ejbjar" depends="compile" description="创建EJB发布包">
<jar jarfile="${basedir}\${ant.project.name}.jar">
<fileset dir="${build.dir}">
<include name="**/*.class"/>
</fileset>
<!-- 将原目录下META-INF下的所有文件都打包到 jar文件的META-INF下-->
<metainf dir="${src.dir}\META-INF"></metainf>
</jar>
</target>

<!-- =================================
target: deploy
================================= -->
<target name="deploy" depends="ejbjar" description="发布EJB">
<copy file="${basedir}\${ant.project.name}.jar" todir="${jboss.home}\server\${jboss.server.config}\deploy"/>
</target>

<!-- - - - - - - - - - - - - - - - - -
target: undeploy
- - - - - - - - - - - - - - - - - -->
<target name="undeploy" description="卸载EJB">
<delete file="${jboss.home}\server\${jboss.server.config}\deploy\${ant.project.name}.jar"/>
</target>


</project>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 EJB(Enterprise JavaBeans)中,Session Bean 和 Entity Bean 是两种不同类型的组件,用于实现不同的功能。 1. Session Bean(会话Bean): Session Bean 是用于处理业务逻辑的组件。它代表了一个特定的会话,可以执行一系列相关的操作。Session Bean 可以分为以下两种类型: - Stateless Session Bean(无状态会话Bean):它不保存客户端的状态信息,每个方法调用都是独立的。适用于无需保存客户端状态的业务逻辑。 - Stateful Session Bean(有状态会话Bean):它保存了客户端的状态信息,可以跟踪多个方法调用之间的状态。适用于需要保存客户端状态的业务逻辑。 2. Entity Bean(实体Bean): Entity Bean 用于表示业务领域中的实体对象,例如数据库表中的行。它们持久化到数据库中,并提供对这些实体对象的增删改查等操作。Entity Bean 可以分为以下两种类型: - Container-Managed Persistence(CMP):容器管理持久化。在 CMP 中,容器负责管理实体的持久化,开发人员只需定义实体类和相关的映射关系。 - Bean-Managed Persistence(BMP):Bean管理持久化。在 BMP 中,开发人员需要自己编写代码来控制实体的持久化和数据库访问。 区别和含义: - Session Bean 主要用于处理业务逻辑,不负责持久化数据,而 Entity Bean 用于表示实体对象,并负责将实体对象持久化到数据库中。 - Session Bean 可以是无状态或有状态的,而 Entity Bean 通常是有状态的,因为它们需要维护实体对象的状态和标识。 - Session Bean 的生命周期由客户端决定,而 Entity Bean 的生命周期由容器管理。 - CMP 提供了更简单的持久化解决方案,开发人员无需编写 SQL 或 JDBC 代码,而 BMP 需要开发人员手动管理数据库访问和事务。 需要注意的是,EJB 在 Java EE 6 版本之后已经进入了轻量级的 CDI(Contexts and Dependency Injection)时代,推荐使用 CDI 来管理会话和实体等组件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值