J2EE之wildfly 实践3 --DAS服务开发

wildfly 实践3 --DAS服务开发,此服务基于JPA对数据进行CURD管理

IDE Eclipse mars,所在机器 192.168.50.253

  (转载请注明来源:cnblogs coder-fang)

 

  1. File->new ->maven project ,创建Maven工程,如图:
  2. 修改pom.xml文件:
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.sanjian.wildfly</groupId>
        <artifactId>ticket-agency-db</artifactId>
        <version>0.1</version>
        <packaging>ejb</packaging>
        <name>ticket-agency-db</name>
        <dependencies>
            <dependency>
                <groupId>org.jboss.logging</groupId>
                <artifactId>jboss-logging</artifactId>
                <version>3.1.4.GA</version>
    
            </dependency>
            <dependency>
                <groupId>javax</groupId>
                <artifactId>javaee-api</artifactId>
                <version>7.0</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-core</artifactId>
                <version>2.8.1</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-annotations</artifactId>
                <version>2.1.0</version>
            </dependency>
        </dependencies>
        <build>
            <finalName>${project.artifactId}</finalName>
            <plugins>
                <plugin>
                    <groupId>org.wildfly.plugins</groupId>
                    <artifactId>wildfly-maven-plugin</artifactId>
                    <version>1.0.2.Final</version>
                    <configuration>
                        <filename>${project.build.finalName}.jar</filename>
                        <hostname>192.168.50.123</hostname>
                        <port>8080</port>
                        <username>jboss</username>
                        <password>123</password>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.1</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-ejb-plugin</artifactId>
                    <version>2.3</version>
                    <configuration>
                        <ejbVersion>3.2</ejbVersion>
                        <generateClient>false</generateClient>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </project>

     

  3. 在src/main/resources/META-INF下增加两个xml配置文件,如图:
  4. ejb-jar.xml配置如下:
    <?xml version="1.0" encoding="UTF-8"?>
    <ejb-jar xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="3.2">
      <display-name>ticket-agency-db</display-name>
      <ejb-client-jar>ticket-agency-db.jar</ejb-client-jar>
    </ejb-jar>

     

  5. persistence.xml配置如下:
    <?xml version="1.0" encoding="UTF-8"?>
    <persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
        <persistence-unit name="ticket-agency-db" transaction-type="JTA">
            <jta-data-source>java:/XboMdtDS</jta-data-source>
            <class>com.sanjian.jpa.model.Patient</class>
            <class>com.sanjian.jpa.model.Site</class>
            <properties>
            <property name="hibernate.show_sql" value="true" />
            </properties>
              
        </persistence-unit>
    </persistence>

    注:本例中只对Patient表和Site表进行映射,所以class如上述所示

  6. 创建两个实体类com.sanjian.jpa.model.Patient,com.sanjian.jpa.model.Site.
  7. Patient代码片段如下:
    @Entity
    @Table(name="patient")
    @NamedQuery(name="Patient.findAll", query="SELECT p FROM Patient p")
    public class Patient implements Serializable {
        private static final long serialVersionUID = 1L;
    
        @Id
        @GeneratedValue(strategy=GenerationType.IDENTITY)
        private String id;
    
        @Column(name="pat_birth")
        private String patBirth;
    
        @Column(name="pat_id")
        private String patId;
    
        @Column(name="pat_name")
        private String patName;
    
        @Column(name="pat_sex")
        private String patSex;
    
        @Column(name="pat_weight")
        private String patWeight;
    
        private String version;
    
        //bi-directional many-to-one association to Site
        @ManyToOne
        @JoinColumn(name="created_site")
        private Site site;
    ......setter and getter

     

  8. Site代码片段如下:
    @Entity
    @Table(name="site")
    @NamedQuery(name="Site.findAll", query="SELECT s FROM Site s")
    public class Site implements Serializable {
        private static final long serialVersionUID = 1L;
    
        @Id
        @GeneratedValue(strategy=GenerationType.IDENTITY)
        private long id;
    
        private int canresetmcode;
    
        private String contact;
    
        private String maccode;
    
        private String offreason;
    
        private String siteaddress;
    ...getter and setter

     

  9. 右键此工程,执行maven-->update project,排除相关错误。
  10. 创建com.sanjian.jpa.model.dao.AbstractDao,代码如下:
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public abstract class AbstractDao<T extends Serializable> implements Serializable {
    
        private final Class<T> clazz;
    
        @PersistenceContext
        private EntityManager em;
    
        public AbstractDao(Class<T> clazz) {
            this.clazz = clazz;
        }
    
        @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)  
        public  long getCount() {  
            return (Long)em.createQuery("select count("+ getCountField() +") from "+ getEntityName()+ " o").getSingleResult();  
        }  
        public void delete(Object entityid) {
            em.remove(em.getReference(clazz, entityid));
        }
    
        public T find(Object entityId) {
            return em.find(clazz, entityId);
        }
        public void save(Object entity) {  
            em.persist(entity);  
        }  
         
        public void update(Object entity) {  
            em.merge(entity);  
        }
        
        @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)  
        public QueryResult<T> getScrollData(  
                int firstindex, int maxresult, LinkedHashMap<String, String> orderby) {  
            return getScrollData(firstindex,maxresult,null,null,orderby);  
        }  
          
        @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)    
        public QueryResult<T> getScrollData(  
                int firstindex, int maxresult, String wherejpql, Object[] queryParams) {  
            return getScrollData(firstindex,maxresult,wherejpql,queryParams,null);  
        }  
          
        @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)    
        public QueryResult<T> getScrollData(int firstindex, int maxresult) {  
            return getScrollData(firstindex,maxresult,null,null,null);  
        }  
          
        @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)    
        public QueryResult<T> getScrollData() {  
            return getScrollData(-1, -1);  
        }  
      
        @SuppressWarnings("unchecked")  
        @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)  
        public QueryResult<T> getScrollData(int firstindex, int maxresult  
                , String wherejpql, Object[] queryParams,LinkedHashMap<String, String> orderby) {  
            QueryResult<T> qr = new QueryResult<T>();  
            String entityname = getEntityName();  
            Query query = em.createQuery("select o from "+ entityname+ " o "+(wherejpql==null? "": "where "+ wherejpql)+ buildOrderby(orderby));  
            setQueryParams(query, queryParams);  
            if(firstindex!=-1 && maxresult!=-1) query.setFirstResult(firstindex).setMaxResults(maxresult);  
            qr.setResultlist(query.getResultList());  
            query = em.createQuery("select count("+ getCountField()+ ") from "+ entityname+ " o "+(wherejpql==null? "": "where "+ wherejpql));  
            setQueryParams(query, queryParams);  
            qr.setTotalrecord((Long)query.getSingleResult());  
            return qr;  
        }  
          
        protected void setQueryParams(Query query, Object[] queryParams){  
            if(queryParams!=null && queryParams.length>0){  
                for(int i=0; i<queryParams.length; i++){  
                    query.setParameter(i+1, queryParams[i]);  
                }  
            }  
        }  
        protected String buildOrderby(LinkedHashMap<String, String> orderby){  
            StringBuffer orderbyql = new StringBuffer("");  
            if(orderby!=null && orderby.size()>0){  
                orderbyql.append(" order by ");  
                for(String key : orderby.keySet()){  
                    orderbyql.append("o.").append(key).append(" ").append(orderby.get(key)).append(",");  
                }  
                orderbyql.deleteCharAt(orderbyql.length()-1);  
            }  
            return orderbyql.toString();  
        }  
       
        protected String getEntityName(){  
            String entityname = clazz.getSimpleName();  
            Entity entity = clazz.getAnnotation(Entity.class);  
            if(entity.name()!=null && !"".equals(entity.name())){  
                entityname = entity.name();  
            }  
            return entityname;  
        }  
        protected String getCountField(){  
            String out = "o";  
            try {  
                PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(clazz).getPropertyDescriptors();  
                for(PropertyDescriptor propertydesc : propertyDescriptors){  
                    Method method = propertydesc.getReadMethod();  
                    if(method!=null && method.isAnnotationPresent(EmbeddedId.class)){                     
                        PropertyDescriptor[] ps = Introspector.getBeanInfo(propertydesc.getPropertyType()).getPropertyDescriptors();  
                        out = "o."+ propertydesc.getName()+ "." + (!ps[1].getName().equals("class")? ps[1].getName(): ps[0].getName());  
                        break;  
                    }  
                }  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
            return out;  
        }  
    }
    View Code

     

  11. 创建com.sanjian.jpa.model.dao.QueryResult,代码如下:
    public class QueryResult<T> implements Serializable{
    
        /**
         * 
         */
        private static final long serialVersionUID = -4283264692574549712L;
        private List<T> resultlist;
        private Long totalrecord;
    
        /**
         * @return the resultlist
         */
        public List<T> getResultlist() {
            return resultlist;
        }
    
        /**
         * @param resultlist the resultlist to set
         */
        public void setResultlist(List<T> resultlist) {
            this.resultlist = resultlist;
        }
    
        /**
         * @return the totalrecord
         */
        public Long getTotalrecord() {
            return totalrecord;
        }
    
        /**
         * @param totalrecord the totalrecord to set
         */
        public void setTotalrecord(Long totalrecord) {
            this.totalrecord = totalrecord;
        }
    }
    View Code

     

  12. 创建com.sanjian.jpa.model.dao.SiteDao,代码片段如下:
    @Stateless
    public class SiteDao extends AbstractDao<Site>{
    
        /**
         * 
         */
        private static final long serialVersionUID = 461138635288849346L;
    
        public SiteDao() {
            super(Site.class);
            // TODO Auto-generated constructor stub
        }
    
    }
    View Code

    注:PatientDao代码类似

  13. 右键工程->New->Session Bean:如图:
  14. SiteManager代码如下:
    @Stateless
    @LocalBean
    public class SiteManager implements SiteManagerRemote {
        private static Logger logger = Logger.getLogger(SiteManager.class);
        
        @EJB
        SiteDao siteDao;
        @EJB
        PatientDao patientDao;
        /**
         * Default constructor. 
         */
        public SiteManager() {
            // TODO Auto-generated constructor stub        
        }        
        @Override
        public QueryResult<Site> listSites(int status) {
            
            QueryResult<Site> lst  = null;
            try {
                
                lst = siteDao.getScrollData(0, 100, "status=?1", new Object[]{status});
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
                     
            return lst;
            
        }
        
      
        
        public SiteDao getSiteDao() {
            return siteDao;
        }
    
    
        public void setSiteDao(SiteDao siteDao) {
            this.siteDao = siteDao;
        }
    
    }
    View Code

     

  15. 修改相关接口代码SiteManagerRemote,代码如下:
    @Remote
    public interface SiteManagerRemote {
        QueryResult<Site> listSites(int status);
        
    }

     

  16. 至此,EJB服务接口编写完成,使用maven->update project 更新代码并修复错误。
  17. 发布设置,打开Run->run configuration,配置如下:
  18. 确保50.123机器服务已运行,点击上图中的运行,则此ejb即可发布至50.123上,console控制台代码片段如下:
    [INFO] Building EJB ticket-agency-db with EJB version 3.2
    [INFO] Building jar: E:\StudyCode\WorkSpace\ticket-agency\ticket-agency-db\target\ticket-agency-db.jar
    [INFO] 
    [INFO] --- maven-install-plugin:2.4:install (default-install) @ ticket-agency-db ---
    [INFO] Installing E:\StudyCode\WorkSpace\ticket-agency\ticket-agency-db\target\ticket-agency-db.jar to E:\mavenrepo\com\sanjian\wildfly\ticket-agency-db\0.1\ticket-agency-db-0.1.jar
    [INFO] Installing E:\StudyCode\WorkSpace\ticket-agency\ticket-agency-db\pom.xml to E:\mavenrepo\com\sanjian\wildfly\ticket-agency-db\0.1\ticket-agency-db-0.1.pom
    [INFO] 
    [INFO] >>> wildfly-maven-plugin:1.0.2.Final:deploy (default-cli) > package @ ticket-agency-db >>>
    [INFO] 
    [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ ticket-agency-db ---
    [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
    [INFO] Copying 2 resources
    [INFO] 
    [INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ ticket-agency-db ---
    [INFO] Nothing to compile - all classes are up to date
    [INFO] 
    [INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ ticket-agency-db ---
    [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
    [INFO] Copying 0 resource
    [INFO] 
    [INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ ticket-agency-db ---
    [INFO] Nothing to compile - all classes are up to date
    [INFO] 
    [INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ ticket-agency-db ---
    [INFO] Skipping execution of surefire because it has already been run for this configuration
    [INFO] 
    [INFO] --- maven-ejb-plugin:2.3:ejb (default-ejb) @ ticket-agency-db ---
    [INFO] Building EJB ticket-agency-db with EJB version 3.2
    [INFO] Building jar: E:\StudyCode\WorkSpace\ticket-agency\ticket-agency-db\target\ticket-agency-db.jar
    [INFO] 
    [INFO] <<< wildfly-maven-plugin:1.0.2.Final:deploy (default-cli) < package @ ticket-agency-db <<<
    [INFO] 
    [INFO] --- wildfly-maven-plugin:1.0.2.Final:deploy (default-cli) @ ticket-agency-db ---
    十二月 13, 2016 4:10:16 下午 org.xnio.Xnio <clinit>
    INFO: XNIO version 3.2.2.Final
    十二月 13, 2016 4:10:16 下午 org.xnio.nio.NioXnio <clinit>
    INFO: XNIO NIO Implementation Version 3.2.2.Final
    十二月 13, 2016 4:10:17 下午 org.jboss.remoting3.EndpointImpl <clinit>
    INFO: JBoss Remoting version 4.0.3.Final
    Authenticating against security realm: ManagementRealm
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 7.803 s
    [INFO] Finished at: 2016-12-13T16:10:20+08:00
    [INFO] Final Memory: 25M/206M
    [INFO] ------------------------------------------------------------------------
    View Code

     

  19. 至此,DAS服务已发布至50.123的机器上,下篇文章,我们使用web服务访问DAS服务。

 

 

posted @ 2016-12-13 16:13  Coder_fang  阅读(517)  评论(0编辑  收藏  举报