EJB3.0连接数据库
此文配有视频(因为一个朋友需要录的。第一次录太紧张了。如果有人需要可以发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
- <?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="MySqlDS">
- <jta-data-source>java:/MySqlDS</jta-data-source>
- <properties>
- <property name="hibernate.hbm2ddl.auto" value="update" />
- <property name="hibernate.show_sql" value="true" />
- </properties>
- </persistence-unit>
- </persistence>
以上就把环境配好了,之后就可以写代码测试了。
5.写简单的实体bean(实体bean必须序列化)
- @Entity
- @Table
- public class Line implements Serializable {
- /**
- * 线的主键id,自动增长
- */
- private Integer lineId;
- @Id
- @GeneratedValue(strategy = GenerationType.AUTO)
- public Integer getLineId() {
- return lineId;
- }
- public void setLineId(Integer lineId) {
- this.lineId = lineId;
- }
- }
6.写会话bean
LineDAO.java:
- public interface LineDAO {
- public boolean insertLine();
- }
LineDAOBean.java:
- @Stateless
- @Remote (LineDAO.class)
- public class LineDAOBean implements LineDAO {
- @PersistenceContext
- protected EntityManager em;
- public boolean insertLine() {
- Line line=new Line();
- em.persist(line);
- return true;
- }
- }
7.junit测试