---
title: "EJB3.0连接数据库"
author: "j040404"
date: "2008-11-04T01:11:00Z"
tags: []
slug: "ejb3-0"
draft: false
lastmod: "2008-11-04T01:11:00Z"
id: 263067
url: "https://j040404.iteye.com/blog/263067"
---

此文配有视频（因为一个朋友需要录的。第一次录太紧张了。如果有人需要可以发email索要：[lljangels@163.com](mailto:lljangels@163.com)）

 

目录树

![](http://p.blog.csdn.net/images/p_blog_csdn_net/j040404/EntryImages/20081104/ejb3.0%E8%BF%9E%E6%8E%A5%E6%95%B0%E6%8D%AE%E5%BA%93.jpg)

 

1.把数据库需要的jar包放进\\jboss-4.0.4.GA\\server\\all\\lib下  
(all是jboss服务最全的 可以选择其他)  
2.从jboss-4.0.4.GA\\docs\\examples\\jca下找mysql-ds.xml  
(有好多种类的数据库的配置文件模板)  
3.修改模板把主要有  
 数据库名：  &lt;connection-url&gt;jdbc:mysql://localhost:3306/map&lt;/connection-url&gt;  
用户名，密码

然后把修改好的模板放入\\jboss-4.0.4.GA\\server\\all\\deplxiay 下

4.新建项目  
src  
  --META-INF  
   --persistence.xml

01. &lt;?xml version="1.0"?&gt;
02. &lt;persistence xmlns="http://java.sun.com/xml/ns/persistence"
03. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
04. xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence\_1\_0.xsd"
05. version="1.0"&gt;
06. &lt;persistence-unit name="MySqlDS"&gt;
07. &lt;jta-data-source&gt;java:/MySqlDS&lt;/jta-data-source&gt;
08. &lt;properties&gt;
09. &lt;property name="hibernate.hbm2ddl.auto" value="update" /&gt;
10. &lt;property name="hibernate.show\_sql" value="true" /&gt;
11. &lt;/properties&gt;
12. &lt;/persistence-unit&gt;
13. &lt;/persistence&gt;

以上就把环境配好了，之后就可以写代码测试了。

5.写简单的实体bean(实体bean必须序列化)

01. @Entity
02. @Table
03. public class Line implements Serializable {
04. /\**
05. * 线的主键id，自动增长
06. \*/
07. private Integer lineId;
08. @Id
09. @GeneratedValue(strategy = GenerationType.AUTO)
10. public Integer getLineId() {
11. return lineId;
12. }
13. public void setLineId(Integer lineId) {
14. this.lineId = lineId;
15. }
16. }

6.写会话bean  
LineDAO.java：

1. public interface LineDAO {
2. public boolean insertLine();
3. }

LineDAOBean.java：

01. @Stateless
02. @Remote (LineDAO.class)
03. public  class LineDAOBean implements LineDAO {
04. @PersistenceContext
05. protected EntityManager em;
06. public boolean insertLine() {
07. Line line=new Line();
08. em.persist(line);
09. return true;
10. }
11. }

7.junit测试