EJB3 step by step 1

EJB3 step by step 1

新建一个EJB3项目,在WETA-INF目录下新建persistence.xml文件,其中"hibernate.hbm2ddl.auto" value="create-drop",则不需要人工建立数据库表,会自动帮你建立。hibernate.dialect如果没写,也会提示出错。

persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence>
  <persistence-unit name="Ejb3">
    <jta-data-source>java:/ejb3Example</jta-data-source>
    <properties>
      <property name="hibernate.hbm2ddl.auto"
                value="create-drop"/>
      <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
    </properties>
  </persistence-unit>
</persistence>

建立entity bean:Book.java,这是一个普通POJO,里面使用JPA注释它是一个entity bean,在领域模型里,实体类继承Serializable接口实现序列化,有利于使用缓存。如果有提示@Table(name="book")
出错,找不到数据库表,不用管它,最后系统会自动建立数据库表,当然,自己手动建立一个也可。

Book.java
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.TableGenerator;

@Entity
@Table(name="book")
@TableGenerator(  name="book_id", table="primary_keys", pkColumnName="key", pkColumnValue="book",valueColumnName="value")
public class Book implements Serializable {
 private static final long serialVersionUID = 1L;
 private Integer id;
 private String title;
 private String author; 
 public String getAuthor() {
  return author;
 }

 public void setAuthor(String author) {
  this.author = author;
 }

 @Id
 @GeneratedValue(strategy = GenerationType.AUTO, generator = "book_id")
 
 public Integer getId() {
  return id;
 }

 public void setId(Integer id) {
  this.id = id;
 }

 public String getTitle() {
  return title;
 }

 public void setTitle(String title) {
  this.title = title;
 }

 public Book() {
  super();
  }
 
 public Book(Integer id, String title, String author) {
  super();
  this.id = id;
  this.title = title;
  this.author = author;
  }

 @Override
 public String toString() {
  // TODO Auto-generated method stub
  return "Book: " + getId() + " Title " + getTitle() + " Author "
  + getAuthor();
 }
}

建立一个session bean:BookTestBean.java,并添加本地和远程接口BookTestBeanLocal.java、BookTestBeanRemote.java

BookTestBean.java
import java.util.Iterator;
import java.util.List;

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

@Stateless
public class BookTestBean implements BookTestBeanLocal, BookTestBeanRemote {
 @PersistenceContext
 EntityManager em;
 public static final String RemoteJNDIName =  BookTestBean.class.getSimpleName() +
 "/remote";
 public static final String LocalJNDIName =  BookTestBean.class.getSimpleName() +
 "/local";
 public void test() {
  Book book = new Book(null, "My first bean book", "Sebastian");
  em.persist(book);
  Book book2 = new Book(null, "another book", "Paul");
  em.persist(book2);
  Book book3 = new Book(null, "EJB 3 developer guide, comes soon",
  "Sebastian");
  em.persist(book3);
  System.out.println("list some books");
  List someBooks = em.createQuery("from Book b where b.author=:name")
  .setParameter("name", "Sebastian").getResultList();
  for (Iterator iter = someBooks.iterator(); iter.hasNext();)
  {
  Book element = (Book) iter.next();
  System.out.println(element);
  }
  System.out.println("List all books");
  List allBooks = em.createQuery("from Book").getResultList();
  for (Iterator iter = allBooks.iterator(); iter.hasNext();)
  {
   Book element = (Book) iter.next();
   System.out.println(element);
   }
   System.out.println("delete a book");
   em.remove(book2);
   System.out.println("List all books");
    allBooks = em.createQuery("from Book").getResultList();
   for (Iterator iter = allBooks.iterator(); iter.hasNext();)
   {
   Book element = (Book) iter.next();
   System.out.println(element);
   }
   }
}

BookTestBeanLocal.java

import javax.ejb.Local;

@Local
public interface BookTestBeanLocal {
 public void test();
}


BookTestBeanRemote.java

import javax.ejb.Remote;

@Remote
public interface BookTestBeanRemote {
 public void test();
}


在%JBOSS_HOME%\server\default\deploy下新建文件EJB-DS.XML,相应的数据库写法,可在%JBOSS_HOME%\docs\examples\jca中找到。

EJB-DS.XML
<?xml version="1.0" encoding="UTF-8"?>
<datasources>
  <local-tx-datasource>
    <jndi-name>ejb3Example</jndi-name>
    <connection-url>jdbc:mysql://localhost:3306/mysql</connection-url>
    <driver-class>com.mysql.jdbc.Driver</driver-class>
    <user-name>xx</user-name>
    <password>xx</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>



这是所用到的包。
在JBOSS中部署成jar,查看是否部署成功。

编写测试客户端TestClient.java,并在META-INF下添加jndi.properies。

TestClient.java

import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class TestClient.java{

 /**
  * @param args
  */
 public static void main(String[] args) {

  Context context;
  try
  {
    context = new InitialContext();
    BookTestBeanRemote beanRemote = (BookTestBeanRemote) context.lookup(BookTestBean.RemoteJNDIName);
   beanRemote.test();
  } catch (NamingException e)
  {
   e.printStackTrace();
   throw new RuntimeException(e);
  }
 }
}

jndi.properies
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=localhost:1099

此时客户端测试只需要一个J2EE包和jbossall-client.jar便可。如果客户端与服务器端的包有冲突或版本不同,就会有stream classdesc serialVersionUID = 4582256576523491346, local class serialVersionUID = 3844706474734439975这样的序列化出错。

最后运行客户端测试。

你可能感兴趣的:(EJB3 step by step 1)