• jboss+ejb entityManager操作数据库


    1、创建EJB服务端项目,右键->EJB PROJECT : ejbserver_jboss

    2、创建实体类User:

    package ejbtest01.entity;
    
    import java.io.Serializable;
    
    import javax.persistence.*;
    
    @Entity  //注明是实体类型
    @Table(name="ejb_user") //设置要映射的表名
    public class User implements Serializable{
        private int id;
        private String name;
        private int age;
        private String address;
        
        @Id  //将id设为该实体的主键
        //@GeneratedValue(strategy=GenerationType.AUTO) //生成数据表时才需要,表已存在,则不需要
    //    @GeneratedValue()
        @Column(nullable=false,name="id")
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        @Column(nullable=false,name="name")
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        @Column(nullable=true,name="age")
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        @Column(nullable=true,name="address")
        public String getAddress() {
            return address;
        }
        public void setAddress(String address) {
            this.address = address;
        }
        
        
    
    }
    View Code

    3、创建操作数据库接口类:UserDao

    package ejbtest01.dao;
    
    import java.io.Serializable;
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.ejb.EJBObject;
    import javax.persistence.Query;
    
    
    import ejbtest01.entity.User;
    
    public interface UserDao extends Serializable{
         public void insertUser(User user);
         public void updateUser(String name,int id);
         public void mergeUser(User user);
         public void deleteUser(int id);
         public User findUserByID(int id);
         public List<User> findAll();
         public String hello();
    }
    View Code

    4、创建操作数据库的实现类:UserDaoBean

    package ejbtest01.dao;
    
    import java.io.Serializable;
    import java.rmi.RemoteException;
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.annotation.PostConstruct;
    import javax.annotation.PreDestroy;
    import javax.ejb.EJBHome;
    import javax.ejb.EJBObject;
    import javax.ejb.Handle;
    import javax.ejb.Remote;
    import javax.ejb.RemoveException;
    import javax.ejb.Stateless;
    import javax.ejb.TransactionAttribute;
    import javax.ejb.TransactionAttributeType;
    import javax.persistence.EntityManager;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.PersistenceContext;
    import javax.persistence.Query;
    
    
    import ejbtest01.entity.User;
    
    @Stateless(name="hello") //name :改变Jndi的名称的, lookup("hello/remote"),默认是UserDaoBean/remote
    @Remote(UserDao.class) //指定远程调用的接口类
    public class UserDaoBean implements UserDao{
    
        //unitName:EJB_PU :与persistence.xml中配置的持久化单元名称一致
        @PersistenceContext(unitName="ejbserver_jbossPU")public EntityManager em;
        
    //    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
        public void insertUser(User user) {
            em.persist(user);
        }
    
        public void mergeUser(User user) {
            this.em.getTransaction().begin();
            em.merge(user);
        }
    
        public void updateUser(String name,int id) {
            User user = em.find(User.class, id);
            if(null!=user){
                user.setName(name);
            }
        }
    
         public String hello(){
             System.out.println("hello.........");
             return "hello, ";
         }
        public void deleteUser(int id) {
            // TODO Auto-generated method stub
    
        }
    
        public List<User> findAll() {
            Query query = em.createQuery("from User u");
            List<User> list = (ArrayList<User>)query.getResultList();
            return list;
        }
    
        public User findUserByID(int id) {
            return em.find(User.class, id);
        }
    
    
    }
    View Code

    5、配置数据源:
    在JBOSS目录:E:installjboss-5.1.0.GAdocsexamplesjca 下找到mysql-ds.xml文件,(数据源的配置文件命名是:*-ds.xml),将mysql-ds.xml文件拷贝到

    E:installjboss-5.1.0.GAserverdefaultdeploy目录下,然后在服务端项目ejbserver_jboss/src/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">
        
        <persistence-unit name="ejbserver_jbossPU" transaction-type="JTA">
              <jta-data-source>java:/MySqlDS</jta-data-source> <!-- MySqlDS与数据源配置文件mysql-ds.xml文件中的名称对应 -->
              <!-- 
              <provider>org.hibernate.ejb.HibernatePersistence</provider>
               -->
              <class>ejbtest01.entity.User</class>
              <properties>
                  <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
                  <property name="hibernate.show_sql" value="true"/>
                  <property name="hibernate.format_sql" value="false"/>
                  <property name="hibernate.hbm2ddl.auto" value="update"/>
              </properties>
        </persistence-unit>
      
    </persistence>
    View Code

    6、导入需要的jar包:mysql-connector-java-5.0.4-bin.jar,并将服务端项目打成jar包:ejbserver.jar,

    7、新建一个客户端web项目:ejbclientdemo

    8、将JBOSS目录下:E:installjboss-5.1.0.GAclient文件夹中的jar全部导入到客户端项目中+mysql-connector-java-5.0.4-bin.jar。+ 服务端项目jar包(ejbserver.jar)

    9、在SRC下创建jndi.properties文件:

    # DO NOT EDIT THIS FILE UNLESS YOU KNOW WHAT YOU ARE DOING
    
    ###new factory name远程实例化工厂的名字
    java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
    
    ##remote package path远程调用类的包路径
    
    java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
    
    ###remote class server path调用类的服务器路径
    
    ##localhost:8080 is not run  , must locahost
    java.naming.provider.url=localhost
    View Code

    10、配置客户端web.xml文件的数据源:

    <resource-ref>
      <description>DB Connection</description>
      <res-ref-name>jdbc/test</res-ref-name><!-- test:是对应的数据库名称,不是连接名称 -->
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
     </resource-ref>
    View Code

    11、在客户端的main方法中测试调用接口:

    package ejb.client;
    
    import java.io.Serializable;
    import java.util.List;
    
    import javax.naming.InitialContext;
    import javax.rmi.PortableRemoteObject;
    import ejbtest01.dao.UserDao;
    import ejbtest01.dao.UserDaoBean;
    import ejbtest01.entity.User;
    
    public class Client implements Serializable{
        
        public static void main(String[] args) {
            try{    
        InitialContext ctx = new InitialContext();
                UserDao dao = (UserDao)ctx.lookup("hello/remote");
                
                //1、先新增数据
              User user = new User();
              user.setId(10);
              user.setName("10000");
              user.setAge(30);
              user.setAddress("呵呵111");
              dao.insertUser(user);
                
                //2、再查询数据
                List<User> users = dao.findAll();
               for(User u : users){
                   System.out.println("===="+u.getName());
               }
    
                  
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    
    }
    View Code

    12、启动JBOSS,运行客户端Main方法,输出查询结果,即测试成功。

  • 相关阅读:
    [原创] 上海好买基金招聘测试经理/测试主管/测试工程师/测试开发工程师(长期有效)
    [原创]表达沟通SCQA架构思维导图
    [原创]PostMan接口测试神器
    [原创]2015年测试人员薪水分布图
    [推荐]大型网站开发知识介绍
    使用C#版OpenCV进行圆心求取
    使用C#版Tesseract库
    OCR库Tesseract初探
    pip的基本使用
    IPAddress.Any 解决本地ip和服务器ip切换问题
  • 原文地址:https://www.cnblogs.com/summer520/p/3184461.html
Copyright © 2020-2023  润新知