ITeye博客

EJB3.0连接数据库

j040404 · 2008-11-04 01:11 · Markdown

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

 

目录树

 

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.修改模板把主要有
 数据库名:  <connection-url>jdbc:mysql://localhost:3306/map</connection-url>
用户名,密码

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

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

  1. <?xml version="1.0"?>
  2. <persistence xmlns="http://java.sun.com/xml/ns/persistence"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
  5. version="1.0">
  6. <persistence-unit name="MySqlDS">
  7. <jta-data-source>java:/MySqlDS</jta-data-source>
  8. <properties>
  9. <property name="hibernate.hbm2ddl.auto" value="update" />
  10. <property name="hibernate.show_sql" value="true" />
  11. </properties>
  12. </persistence-unit>
  13. </persistence>

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

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

  1. @Entity
  2. @Table
  3. public class Line implements Serializable {
  4. /**
  5. * 线的主键id,自动增长
  6. */
  7. private Integer lineId;
  8. @Id
  9. @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:

  1. @Stateless
  2. @Remote (LineDAO.class)
  3. public  class LineDAOBean implements LineDAO {
  4. @PersistenceContext
  5. protected EntityManager em;
  6. public boolean insertLine() {
  7. Line line=new Line();
  8. em.persist(line);
  9. return true;
  10. }
  11. }

7.junit测试

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。