JPA动态操作

 

jpa动态查询语句

标签: jpa动态查询语句oa系统整理
  4865人阅读  评论(0)  收藏  举报

我们现在在做一个OA系统,将新增的那些数据都写到数据库的时候是采用jpa规范的,(不太理解jpa的相关知识点,今天看下相关知识,然后再补充jpa的知识点),现在记录jpa中的动态查询语句,其实这些语句都是可以用sql语句写的,但是sql语句写得查询,删除,插入数据等操作不安全,所以采用jpa的语句。我们的项目是分为三层结构,第一层是实体层,在该层中专门定义某一实体的相关字段,它的set(),get()方法。第二层是服务层,将service和dao都放在一个组件中,在dao层中定义和数据库相关的操作方法,在service层中定义相关的业务逻辑层要调用的方法。第三层是restful层,在这层定义的是和前端交互的组件。

首先讲讲第一层:实体层

定义一个实体

[java]  view plain  copy
  1. /** 
  2.  * 邮件实体 
  3.  * 
  4.  */  
  5. @Entity  
  6. @Table(name = "mail_tbl")  
  7. public class InnerMails implements Serializable {  
  8.   
  9.     private static final long serialVersionUID = 4999674279957375152L;  
  10.   
  11.     @Id  
  12.     @GeneratedValue  
  13.     private long id;  
  14.   
  15.     private String subject;// 主题  
  16.   
  17.     private String toMails;// 收件人 格式 :姓名<userId>;姓名<userId>  
  18.   
  19.     private String urgency;// 紧急程度  
  20.       
  21.     @Column(name = "sendDate")  
  22.     @Temporal(TemporalType.TIMESTAMP)  
  23.     private Date sendDate;// 发布日期  
  24.   
  25.     private String content;// 邮件内容  
  26.   
  27.     // 原文附件  
  28.     @OneToMany(cascade={ CascadeType.MERGE,CascadeType.REMOVE})  
  29.     @JoinColumn(name = "mail_id")  
  30.     @OrderBy(value = "id DESC")//注释指明加载Attachment时按id的降序排序    
  31.     private Set<AppendFile> appendFiles=new HashSet<AppendFile>();// 附件  
  32.   
  33.     private String mailUser;// 邮件拥有者 格式:userId  
  34.   
  35.     private String sendMail;// 邮件发送者 格式:姓名<userId>  
  36.   
  37.     private int type;// 状态标示:-1删除;0草稿;1发送;2未读收件,3已读收件  
  38.   
  39.     public long getId() {  
  40.         return id;  
  41.     }  
  42.   
  43.     public void setId(long id) {  
  44.         this.id = id;  
  45.     }  
  46.   
  47.     public String getSubject() {  
  48.         return subject;  
  49.     }  
  50.   
  51.     public void setSubject(String subject) {  
  52.         this.subject = subject;  
  53.     }  
  54.   
  55.     public String getToMails() {  
  56.         return toMails;  
  57.     }  
  58.   
  59.     public void setToMails(String toMails) {  
  60.         this.toMails = toMails;  
  61.     }  
  62.   
  63.     public String getUrgency() {  
  64.         return urgency;  
  65.     }  
  66.   
  67.     public void setUrgency(String urgency) {  
  68.         this.urgency = urgency;  
  69.     }  
  70.   
  71.     public Date getSendDate() {  
  72.         return sendDate;  
  73.     }  
  74.   
  75.     public void setSendDate(Date sendDate) {  
  76.         this.sendDate = sendDate;  
  77.     }  
  78.   
  79.     public String getContent() {  
  80.         return content;  
  81.     }  
  82.   
  83.     public void setContent(String content) {  
  84.         this.content = content;  
  85.     }  
  86.     public String getMailUser() {  
  87.         return mailUser;  
  88.     }  
  89.   
  90.       
  91.     public void setMailUser(String mailUser) {  
  92.         this.mailUser = mailUser;  
  93.     }  
  94.   
  95.     public Set<AppendFile> getAppendFiles() {  
  96.         return appendFiles;  
  97.     }  
  98.   
  99.     public void setAppendFiles(Set<AppendFile> appendFiles) {  
  100.         this.appendFiles = appendFiles;  
  101.     }  
  102.   
  103.     public String getSendMail() {  
  104.         return sendMail;  
  105.     }  
  106.   
  107.     public void setSendMail(String sendMail) {  
  108.         this.sendMail = sendMail;  
  109.     }  
  110.   
  111.     public int getType() {  
  112.         return type;  
  113.     }  
  114.   
  115.     public void setType(int type) {  
  116.         this.type = type;  
  117.     }  
  118.   
  119. }  
定义查询实体:

[java]  view plain  copy
  1. package com.gzydt.oa.commons;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7.   
  8. /** 
  9.  * 分页查询参数 
  10.  *  
  11.  * @author huangzhenwei 
  12.  * @since 2014-11-21 
  13.  *  
  14.  */  
  15. public class QueryParam {  
  16.   
  17.     // 排序字段,以“+”、“-”符号连接排序字段名:“+key”表示 按“key”字段升序,“-key”表示按“key”字段降序。  
  18.     private List<String> sorts = new ArrayList<String>();  
  19.     // 起始记录下标,从0开始计算  
  20.     private int first = 0;  
  21.     // 每页最大记录数  
  22.     private int max = 10;  
  23.     // 是否分页标志  
  24.     private boolean isPage = true;  
  25.   
  26.     // 查询参数  
  27.     private Map<String, String> param = new HashMap<String, String>();  
  28.   
  29.     public QueryParam() {  
  30.   
  31.     }  
  32.   
  33.     public int getFirst() {  
  34.         return first;  
  35.     }  
  36.   
  37.     public void setFirst(int first) {  
  38.         this.first = first;  
  39.     }  
  40.   
  41.     public int getMax() {  
  42.         return max;  
  43.     }  
  44.   
  45.     public void setMax(int max) {  
  46.         this.max = max;  
  47.     }  
  48.   
  49.     public Map<String, String> getParam() {  
  50.         return param;  
  51.     }  
  52.   
  53.     public void setParam(Map<String, String> param) {  
  54.         this.param = param;  
  55.     }  
  56.   
  57.     public boolean isPage() {  
  58.         return isPage;  
  59.     }  
  60.   
  61.     public void setPage(boolean isPage) {  
  62.         this.isPage = isPage;  
  63.     }  
  64.   
  65.     public List<String> getSorts() {  
  66.         return sorts;  
  67.     }  
  68.   
  69.     public void setSorts(List<String> sorts) {  
  70.         this.sorts = sorts;  
  71.     }  
  72. }  



第二层:服务层

dao层:定义和数据库相关操作的方法

[java]  view plain  copy
  1. package com.gzydt.oa.dao;  
  2.   
  3. import java.util.List;  
  4.   
  5. import com.gzydt.oa.commons.QueryParam;  
  6. import com.gzydt.oa.entity.AppendFile;  
  7. import com.gzydt.oa.entity.InnerMails;  
  8.   
  9. /** 
  10.  * 邮件发送dao接口 
  11.  * 
  12.  */  
  13. public interface InnerMailDao {  
  14.     /** 
  15.      * 保存邮件 
  16.      * @param mail 
  17.      * @return 
  18.      */  
  19.     public InnerMails save(InnerMails mail);  
  20.     /** 
  21.      * 更新邮件 
  22.      * @param mail 
  23.      * @return 
  24.      */  
  25.     public InnerMails update(InnerMails mail);  
  26.     /** 
  27.      * 删除邮件 
  28.      * @param id 
  29.      */  
  30.     public void delete(long id);  
  31.     /** 
  32.      * 查询邮件 
  33.      * @param queryParam 
  34.      * @return 
  35.      */  
  36.     public List<InnerMails> getlist(QueryParam queryParam);  
  37.     /** 
  38.      * 获取单个邮件 
  39.      * @param id 
  40.      * @return 
  41.      */  
  42.     public InnerMails get(long id);  
  43.     /** 
  44.      * 获取满足条件的邮件的总数 
  45.      * @param queryParam 
  46.      * @return 
  47.      */  
  48.     public int getCount(QueryParam queryParam);  
  49.    /** 
  50.     * 新增附件 
  51.     * @param id 
  52.     * @param appendFile 
  53.     */  
  54.     public void addAttach(long id,AppendFile appendFile);  
  55. }  


[java]  view plain  copy
  1. package com.gzydt.oa.dao.impl;  
  2.   
  3. import java.text.DateFormat;  
  4. import java.text.SimpleDateFormat;  
  5. import java.util.ArrayList;  
  6. import java.util.Date;  
  7. import java.util.HashSet;  
  8. import java.util.Iterator;  
  9. import java.util.List;  
  10. import java.util.Map;  
  11. import java.util.Set;  
  12.   
  13. import javax.persistence.EntityManager;  
  14. import javax.persistence.TypedQuery;  
  15. import javax.persistence.criteria.CriteriaBuilder;  
  16. import javax.persistence.criteria.CriteriaQuery;  
  17. import javax.persistence.criteria.Predicate;  
  18. import javax.persistence.criteria.Root;  
  19.   
  20. import com.gzydt.oa.commons.QueryParam;  
  21. import com.gzydt.oa.dao.InnerMailDao;  
  22. import com.gzydt.oa.entity.AppendFile;  
  23. import com.gzydt.oa.entity.InnerMails;  
  24.   
  25. /** 
  26.  * 邮件实现类 
  27.  */  
  28. public class InnerMailDaoImpl implements InnerMailDao{  
  29.   
  30.     private EntityManager entityManager;  
  31.     public void setEntityManager(EntityManager entityManager) {  
  32.         this.entityManager = entityManager;  
  33.     }  
  34.     /** 
  35.      * 保存邮件 
  36.      * @param mail 
  37.      * @return 
  38.      */  
  39.     @Override  
  40.     public InnerMails save(InnerMails mail) {  
  41.         try {  
  42.             entityManager.persist(mail);  
  43.             entityManager.flush();  
  44.             return mail;  
  45.         } catch ( Exception e ) {  
  46.             e.printStackTrace();  
  47.             return null;  
  48.         }  
  49.     }  
  50.     /** 
  51.      * 更新邮件 
  52.      * @param mail 
  53.      * @return 
  54.      */  
  55.     @Override  
  56.     public InnerMails update(InnerMails mail) {  
  57.         try {  
  58.             entityManager.merge(mail);  
  59.             return mail;  
  60.         } catch ( Exception e ) {  
  61.             e.printStackTrace();  
  62.             return null;  
  63.         }  
  64.     }  
  65.     /** 
  66.      * 删除邮件 
  67.      * @param id 
  68.      */  
  69.     @Override  
  70.     public void delete(long id) {  
  71.           
  72.             entityManager.createQuery("delete from  PhoneRecord e where e.id=:id").setParameter("id", id).executeUpdate();  
  73.              
  74.           
  75.     }  
  76.     /** 
  77.      * 查询邮件 
  78.      * @param queryParam 
  79.      * @return 
  80.      */  
  81.     @Override  
  82.     public List<InnerMails> getlist(QueryParam queryParam) {  
  83.         CriteriaBuilder cb = entityManager.getCriteriaBuilder();  
  84.         CriteriaQuery<InnerMails> criteriaQuery = cb.createQuery(InnerMails.class);  
  85.         Root<InnerMails> register = criteriaQuery.from(InnerMails.class);  
  86.         // 过滤条件  
  87.         Predicate[] predicates = createPredicate(queryParam, cb, register);  
  88.         criteriaQuery.where(predicates);  
  89.         int start = queryParam.getFirst();  
  90.         int end = queryParam.getMax();  
  91.         TypedQuery<InnerMails> typedQuery = entityManager.createQuery(criteriaQuery);  
  92.         typedQuery.setFirstResult(start).setMaxResults(end);  
  93.         return typedQuery.getResultList();  
  94.     }  
  95.   //设置查询条件  
  96.     private Predicate[] createPredicate(QueryParam queryParam, CriteriaBuilder cb, Root<InnerMails> entity) {  
  97.         List<Predicate> predicates=new ArrayList<Predicate>();  
  98.         //取出查询条件  
  99.         Map<String, String> param= queryParam.getParam();  
  100.         for(Map.Entry entry:param.entrySet()){  
  101.             String key=entry.getKey().toString();  
  102.             String value=entry.getValue().toString();  
  103.             if(key.equals("sendDate")){  
  104.                Predicate conditionTime = createOperateTime(key,cb,value,entity);  
  105.                if(null!=conditionTime){  
  106.                    predicates.add(conditionTime);  
  107.                }         
  108.             }else{  
  109.                 predicates.add(cb.like(entity.<String> get(key),"%"+value+"%"));   
  110.             }  
  111.         }  
  112.         return predicates.toArray(new Predicate[0]);  
  113.     }  
  114.   
  115.     /** 
  116.      * 将时间作为查询条件的方法 
  117.      * @param cb 
  118.      * @param value 
  119.      * @param entity 
  120.      */  
  121.     private Predicate createOperateTime(String key,CriteriaBuilder cb, String value, Root<InnerMails> entity) {    
  122.         if(null == value){  
  123.             return null;  
  124.         }  
  125.         String[] operateTime=value.split("~");  
  126.         if(operateTime.length!=2){  
  127.             return null;  
  128.         }  
  129.         try {  
  130.             DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//格式一定要写正确,  
  131.             Date t1=df.parse(operateTime[0] + " 00:00:00");  
  132.             Date t2=df.parse(operateTime[1] + " 23:59:59");  
  133.             return cb.between(entity.<Date> get(key), t1, t2);  
  134.         } catch ( Exception e ) {  
  135.            e.printStackTrace();  
  136.         }  
  137.         return null;  
  138.           
  139.     }  
  140.   
  141.     /** 
  142.      * 获取单个邮件 
  143.      * @param id 
  144.      * @return 
  145.      */  
  146.     @Override  
  147.     public InnerMails get(long id) {  
  148.         InnerMails innersMails=entityManager.find(InnerMails.class, id);  
  149.        Iterator<AppendFile> iterator=innersMails.getAppendFiles().iterator();  
  150.         Set<AppendFile> attachs=new HashSet<AppendFile>();  
  151.         while(iterator.hasNext()){  
  152.             AppendFile appendFile=new AppendFile();  
  153.             appendFile=iterator.next();  
  154.             attachs.add(appendFile);     
  155.         }  
  156.         innersMails.setAppendFiles(attachs);  
  157.        return innersMails;  
  158.     }  
  159.     /** 
  160.      * 获取满足条件的邮件的总数 
  161.      * @param queryParam 
  162.      * @return 
  163.      */  
  164.     @Override  
  165.     public int getCount(QueryParam queryParam) {  
  166.         CriteriaBuilder cb = entityManager.getCriteriaBuilder();  
  167.         CriteriaQuery<Long> criteriaQuery = cb.createQuery(Long.class);  
  168.         Root<InnerMails> mails = criteriaQuery.from(InnerMails.class);  
  169.         criteriaQuery.select(cb.countDistinct(mails));  
  170.         // 过滤条件  
  171.         Predicate[] predeicates = createPredicate(queryParam, cb, mails);  
  172.         criteriaQuery.where(predeicates);  
  173.         TypedQuery<Long> typedQuery = entityManager.createQuery(criteriaQuery);  
  174.         int count = 0;  
  175.         try {  
  176.             count = typedQuery.getSingleResult().intValue();  
  177.         } catch ( Exception e ) {  
  178.             e.printStackTrace();  
  179.         }  
  180.         return count;  
  181.     }  
  182.     /** 
  183.      * 新增附件 
  184.      * @param id 
  185.      * @param appendFile 
  186.      */  
  187.     @Override  
  188.     public void addAttach(long id, AppendFile appendFile) {  
  189.         InnerMails entity=this.get(id);  
  190.         entity.getAppendFiles().add(appendFile);  
  191.         entityManager.merge(entity);  
  192.           
  193.     }  
  194.   
  195. }  
动态查询语句的相关知识

1:查询User表中的字段adminlever的小于给定值的数据

第一种写法:(安全,推荐使用这种)

[java]  view plain  copy
  1. /** 
  2.     * 查询某一级别以上的用户 
  3.     */  
  4.    @Override  
  5.    public List<User> getOnLeverUper(int lever) {  
  6.      CriteriaBuilder cb =entityManager.getCriteriaBuilder();  
  7.      CriteriaQuery<User> criterQuery=cb.createQuery(User.class);  
  8.      Root<User> entity=criterQuery.from(User.class);  
  9.      Path<Integer> adminLever=entity.<Integer> get("adminlever") ;   
  10.      criterQuery.where(cb.lessThan(adminLever, lever));  
  11.      TypedQuery<User> typedQuery=entityManager.createQuery(criterQuery);  
  12.      return typedQuery.getResultList();  
  13.     
  14.    }  
第二种写法:(不太安全,)

[java]  view plain  copy
  1. /** 
  2.     * 查询某一级别以上的用户 
  3.     */  
  4.    @Override  
  5.    public List<User> getOnLeverUper(int lever) {  
  6.        List<User> users=entityManager.createQuery("from User u where u.adminlever<:adminlever")  
  7.                .setParameter("adminlever",lever).getResultList();  
  8.         return users;    
  9.     
  10.    }  
第二种删除数据(有时候会由于某实体和另一实体设置了一对一或者多对一,或者多对多的关系而导致不能正常删除数据),解决方法:

[java]  view plain  copy
  1. /** 
  2.      * 删除登记信息 
  3.      *  
  4.      * @param id 
  5.      *            登记编号 
  6.      */  
  7.     @Override  
  8.     public void handleDelete(long id) throws Exception {  
  9.         ReceiptEntity entity = entityManager.find(ReceiptEntity.class, id);  
  10.         entityManager.remove(entity);  
  11.         //下面的的方法删除应为存在外键关联会删除失败  
  12.        /*entityManager.createQuery("delete from  ReceiptEntity e where e.id=:id"). 
  13.         setParameter("id", id).executeUpdate();*/  
  14.     }  
service层:接口

[java]  view plain  copy
  1. package com.gzydt.oa.service;  
  2.   
  3. import java.util.List;  
  4.   
  5. import com.gzydt.oa.commons.QueryParam;  
  6. import com.gzydt.oa.entity.AppendFile;  
  7. import com.gzydt.oa.entity.InnerMails;  
  8.   
  9. /** 
  10.  * 内部邮件接口 
  11.  * 
  12.  */  
  13. public interface InnerMailService {  
  14.     /** 
  15.      * 保存邮件 
  16.      * @param mail 
  17.      * @return 
  18.      */  
  19.     public InnerMails save(InnerMails mail);  
  20.     /** 
  21.      * 更新邮件 
  22.      * @param mail 
  23.      * @return 
  24.      */  
  25.     public InnerMails update(InnerMails mail);  
  26.     /** 
  27.      * 删除邮件 
  28.      * @param id 
  29.      */  
  30.     public void delete(long id);  
  31.     /** 
  32.      * 查询邮件 
  33.      * @param queryParam 
  34.      * @return 
  35.      */  
  36.     public List<InnerMails> getlist(QueryParam queryParam);  
  37.     /** 
  38.      * 获取单个邮件 
  39.      * @param id 
  40.      * @return 
  41.      */  
  42.     public InnerMails get(long id);  
  43.     /** 
  44.      * 获取满足条件的邮件的总数 
  45.      * @param queryParam 
  46.      * @return 
  47.      */  
  48.     public int getCount(QueryParam queryParam);  
  49.     /** 
  50.      * 发邮件 
  51.      * @param content 
  52.      *//* 
  53.     public void sendMail(String content);*/  
  54.     /** 
  55.      * 新增附件 
  56.      * @param id 
  57.      * @param appendFile 
  58.      */  
  59.     public void addAttach(long id,AppendFile appendFile);  
  60.   
  61. }  
service层:实现类
[java]  view plain  copy
  1. package com.gzydt.oa.service.impl;  
  2.   
  3. import java.util.List;  
  4.   
  5. import com.gzydt.oa.commons.QueryParam;  
  6. import com.gzydt.oa.dao.InnerMailDao;  
  7. import com.gzydt.oa.entity.AppendFile;  
  8. import com.gzydt.oa.entity.InnerMails;  
  9. import com.gzydt.oa.service.InnerMailService;  
  10.   
  11. /** 
  12.  * 内部邮件服务类 
  13.  * 
  14.  */  
  15. public class InnerMailServiceImpl implements InnerMailService{  
  16.   
  17.     private InnerMailDao mailDao;  
  18.       
  19.     public void setMailDao(InnerMailDao mailDao) {  
  20.         this.mailDao = mailDao;  
  21.     }  
  22.     /** 
  23.      * 保存邮件 
  24.      * @param mail 
  25.      * @return 
  26.      */  
  27.     @Override  
  28.     public InnerMails save(InnerMails mail) {  
  29.         return mailDao.save(mail);  
  30.     }  
  31.   
  32.     @Override  
  33.     public InnerMails update(InnerMails mail) {  
  34.         return mailDao.update(mail);  
  35.     }  
  36.     /** 
  37.      * 删除邮件 
  38.      * @param id 
  39.      */  
  40.     @Override  
  41.     public void delete(long id) {  
  42.        mailDao.delete(id);  
  43.           
  44.     }  
  45.     /** 
  46.      * 查询邮件 
  47.      * @param queryParam 
  48.      * @return 
  49.      */  
  50.     @Override  
  51.     public List<InnerMails> getlist(QueryParam queryParam) {  
  52.        return mailDao.getlist(queryParam);  
  53.     }  
  54.     /** 
  55.      * 获取单个邮件 
  56.      * @param id 
  57.      * @return 
  58.      */  
  59.     @Override  
  60.     public InnerMails get(long id) {  
  61.        return mailDao.get(id);  
  62.     }  
  63.     /** 
  64.      * 获取满足条件的邮件的总数 
  65.      * @param queryParam 
  66.      * @return 
  67.      */  
  68.     @Override  
  69.     public int getCount(QueryParam queryParam) {  
  70.         return mailDao.getCount(queryParam);  
  71.     }  
  72.   
  73.    /* @Override 
  74.     public void sendMail(String content) { 
  75.         
  76.          
  77.     }*/  
  78.     /** 
  79.      * 新增附件 
  80.      * @param id 
  81.      * @param appendFile 
  82.      */  
  83.     @Override  
  84.     public void addAttach(long id, AppendFile appendFile) {  
  85.        mailDao.addAttach(id, appendFile);  
  86.           
  87.     }  
  88.   
  89. }  
在服务层中定义相关的服务配置

[java]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <blueprint default-activation="eager"  
  3.     xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:jpa="http://aries.apache.org/xmlns/jpa/v1.0.0" xmlns:tx="http://aries.apache.org/xmlns/transactions/v1.0.0"  
  5.     xsi:schemaLocation="  
  6.       http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd  
  7.       http://cxf.apache.org/blueprint/jaxrs http://cxf.apache.org/schemas/blueprint/jaxrs.xsd  
  8.       http://cxf.apache.org/blueprint/core http://cxf.apache.org/schemas/blueprint/core.xsd">  
  9.   
  10.     <!-- This gets the container-managed EntityManager and injects it into the   
  11.         ServiceImpl bean. -->  
  12.   
  13.     <!-- dao -->  
  14.     <bean id="mailDao" class="com.gzydt.oa.dao.impl.InnerMailDaoImpl">  
  15.         <jpa:context unitname="com.gzydt.jpa.persistence"  
  16.             property="entityManager" />  
  17.         <tx:transaction method="*" value="Required" />  
  18.     </bean>  
  19.   
  20.     <!--新增结束 -->  
  21.   
  22.   
  23.     <!-- bean -->  
  24.       
  25.     <bean id="mailService" class="com.gzydt.oa.service.impl.InnerMailServiceImpl">  
  26.         <property name="mailDao" ref="mailDao" />  
  27.     </bean>  
  28.   
  29.        
  30.         <!--新增结束 -->  
  31.   
  32.     <!-- service -->  
  33.     <service ref="mailService" interface="com.gzydt.oa.service.InnerMailService" />  
  34.   
  35.      <!-- This bundle makes use of Karaf commands to demonstrate core persistence   
  36.         operations. Feel free to remove it. -->  
  37.     <command-bundle xmlns="http://karaf.apache.org/xmlns/shell/v1.1.0">  
  38.         <command name="msg/add">  
  39.             <action class="com.gzydt.oa.command.AddMessage">  
  40.                 <property name="messageService" ref="messageService" />  
  41.             </action>  
  42.         </command>  
  43.         <command name="msg/list">  
  44.             <action class="com.gzydt.oa.command.GetMessage">  
  45.                 <property name="messageService" ref="messageService" />  
  46.             </action>  
  47.         </command>  
  48.         <command name="msg/delete">  
  49.             <action class="com.gzydt.oa.command.DeleteMessage">  
  50.                 <property name="messageService" ref="messageService" />  
  51.             </action>  
  52.         </command>  
  53.   
  54.         <command name="dept/add">  
  55.             <action class="com.gzydt.oa.command.DeptAddCommand">  
  56.                 <property name="deptService" ref="deptService" />  
  57.             </action>  
  58.         </command>  
  59.         <command name="dept/list">  
  60.             <action class="com.gzydt.oa.command.DeptGetCommand">  
  61.                 <property name="deptService" ref="deptService" />  
  62.             </action>  
  63.         </command>  
  64.         <command name="dept/delete">  
  65.             <action class="com.gzydt.oa.command.DeptDeleteCommand">  
  66.                 <property name="deptService" ref="deptService" />  
  67.             </action>  
  68.         </command>  
  69.     </command-bundle>  
  70.   
  71. </blueprint>  

第三层:restful层

[java]  view plain  copy
  1. package com.gzydt.oa.resource;  
  2.   
  3. import java.text.ParseException;  
  4. import java.util.List;  
  5.   
  6. import javax.ws.rs.Consumes;  
  7. import javax.ws.rs.DELETE;  
  8. import javax.ws.rs.GET;  
  9. import javax.ws.rs.HeaderParam;  
  10. import javax.ws.rs.POST;  
  11. import javax.ws.rs.PUT;  
  12. import javax.ws.rs.Path;  
  13. import javax.ws.rs.PathParam;  
  14. import javax.ws.rs.Produces;  
  15. import javax.ws.rs.QueryParam;  
  16. import javax.ws.rs.core.MediaType;  
  17. import javax.ws.rs.core.Response;  
  18.   
  19. import org.apache.cxf.jaxrs.ext.multipart.Attachment;  
  20. import org.apache.cxf.jaxrs.ext.multipart.Multipart;  
  21.   
  22. /** 
  23.  * 内部邮件的restful 
  24.  */  
  25. @Path("/mails")  
  26. public interface InnerMailsResource {  
  27.     /** 
  28.      * 新增邮件 
  29.      * @param content 
  30.      * @return 
  31.      */  
  32.     @POST  
  33.     @Path("/")  
  34.     @Consumes("multipart/form-data")  
  35.     public Response save(@Multipart("content") String content,  
  36. List<Attachment> attachments) throws ParseException ;  
  37.     /** 
  38.      * 更新邮件 
  39.      * @param id 
  40.      * @param content 
  41.      * @return 
  42.      */  
  43.     @PUT  
  44.     @Path("/{id}")  
  45.     @Consumes("multipart/form-data")  
  46.     public Response update(@PathParam("id"long id,@Multipart("content") String content,  
  47. List<Attachment> attachments) throws ParseException;  
  48.     /** 
  49.      * 查询邮件 
  50.      * @param id 
  51.      * @return 
  52.      */  
  53.     @GET  
  54.     @Path("/{id}")  
  55.     public Response get(@PathParam("id"long id);  
  56.     /** 
  57.      * 查询邮件列表 
  58.      * @param range 
  59.      * @param query 
  60.      * @return 
  61.      */  
  62.     @GET  
  63.     @Path("/list")  
  64.     public Response getList(@HeaderParam("range") String range,@QueryParam("query") String query);  
  65.     /** 
  66.      * 删除邮件 
  67.      * @param id 
  68.      * @return 
  69.      */  
  70.     @DELETE  
  71.     @Path("/{id}")  
  72.     public Response delete(@PathParam("id"long id);  
  73.     /** 
  74.      * 发送邮件 
  75.      * @param content 
  76.      * @return  数据格式:{"data":{},"toMail":""} 
  77.      */  
  78.     @POST  
  79.     @Path("/sendMails/{id}")  
  80.     public Response sendMail(@PathParam("id")long id) ;  
  81.     /** 
  82.      * 下载附件 
  83.      * @param id(附件的id) 
  84.      * @return 
  85.      */  
  86.     @GET  
  87.     @Path("/getAttach/{id}")  
  88.     @Produces(MediaType.APPLICATION_OCTET_STREAM)  
  89.     public Response downLoadAttach(@PathParam("id"long id);  
  90.       
  91.       
  92.   
  93. }  

实现类:

[java]  view plain  copy
  1. package com.gzydt.oa.resource.impl;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.io.OutputStream;  
  9. import java.text.ParseException;  
  10. import java.text.SimpleDateFormat;  
  11. import java.util.Date;  
  12. import java.util.HashSet;  
  13. import java.util.List;  
  14. import java.util.Set;  
  15. import java.util.regex.Matcher;  
  16. import java.util.regex.Pattern;  
  17.   
  18. import javax.activation.DataHandler;  
  19. import javax.ws.rs.WebApplicationException;  
  20. import javax.ws.rs.core.MediaType;  
  21. import javax.ws.rs.core.Response;  
  22. import javax.ws.rs.core.Response.Status;  
  23. import javax.ws.rs.core.StreamingOutput;  
  24.   
  25. import net.sf.json.JSONArray;  
  26. import net.sf.json.JSONObject;  
  27. import net.sf.json.JsonConfig;  
  28.   
  29. import org.apache.cxf.jaxrs.ext.multipart.Attachment;  
  30. /*import org.json.JSONArray;*/  
  31.   
  32. import com.gzydt.oa.commons.QueryParam;  
  33. import com.gzydt.oa.entity.AppendFile;  
  34. import com.gzydt.oa.entity.InnerMails;  
  35. import com.gzydt.oa.resource.InnerMailsResource;  
  36. import com.gzydt.oa.service.AppendFileService;  
  37. import com.gzydt.oa.service.InnerMailService;  
  38. import com.gzydt.oa.util.Constant;  
  39. import com.gzydt.oa.util.QueryUtil;  
  40.   
  41. public class InnerMailsResourceImpl implements InnerMailsResource {  
  42.     private InnerMailService emailService;  
  43.   
  44.     public void setEmailService(InnerMailService emailService) {  
  45.         this.emailService = emailService;  
  46.     }  
  47.   
  48.     private AppendFileService appendFileService;  
  49.   
  50.     public void setAppendFileService(AppendFileService appendFileService) {  
  51.         this.appendFileService = appendFileService;  
  52.     }  
  53.   
  54.     private static final String PATH = "data/oa/upload/mails";  
  55.   
  56.     @Override  
  57.     public Response save(String content, List<Attachment> attachments) throws ParseException {  
  58.         //去掉懒加载字段  
  59.         JsonConfig jsonConfig = Constant.jsonDateConfig;  
  60.         jsonConfig.setExcludes(new String[] { "appendFiles"});  
  61.         JSONObject preceInfo = JSONObject.fromObject(content);  
  62.         JSONObject backInfo = new JSONObject();  
  63.         InnerMails entity = new InnerMails();  
  64.         Date sendDate = null;  
  65.         if ( preceInfo.optString("sendDate") != null && preceInfo.optString("sendDate") != "" ) {  
  66.         //这里的MM必须是要大写,若是写为mm,则是分钟,,格式一定要按照正规的来写<span class="con">yyyy-MM-dd HH:mm:ss</span>,  
  67. //该大写就大写,小写就小写,并且中间有空格等,都不能错误。不然时间会出错  
  68.         SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");  
  69.             sendDate = df.parse(preceInfo.optString("sendDate"));  
  70.         }  
  71.         preceInfo.put("sendDate", sendDate);  
  72.         entity = (InnerMails) JSONObject.toBean(preceInfo, InnerMails.class);  
  73.          
  74.         if ( !preceInfo.has("type") ) {  
  75.             entity.setType(0);  
  76.         }  
  77.         entity = emailService.save(entity);  
  78.      // 新增附件到附件表中  
  79.         Set<AppendFile> appfiles=addAttach(attachments, entity);  
  80.         entity.setAppendFiles(appfiles);  
  81.         entity=emailService.update(entity);  
  82.   
  83.         if ( null != entity ) {  
  84.             backInfo = JSONObject.fromObject(entity);  
  85.             return Response.ok(backInfo.toString(), MediaType.APPLICATION_JSON).build();  
  86.         }  
  87.         backInfo.put("message""保存失败");  
  88.         return Response.ok(backInfo.toString(), MediaType.APPLICATION_JSON).build();  
  89.   
  90.     }  
  91.       
  92.     // 保存并关联附件  
  93.     private  Set<AppendFile>  addAttach(List<Attachment> attachments,InnerMails entity){  
  94.         Set<AppendFile> appenFiles=new HashSet<AppendFile>();  
  95.         for (Attachment attachment : attachments) {  
  96.             if (attachment.getContentType().toString().startsWith("application/octet-stream")) {  
  97.                 DataHandler dh = attachment.getDataHandler();  
  98.                 long time = new Date().getTime();  
  99.                 String fileName = null;  
  100.                 try {  
  101.                     fileName = new String(dh.getName().getBytes("ISO-8859-1"), "UTF-8");  
  102.                     writeFile(dh, fileName);  
  103.                 } catch (Exception e) {  
  104.                     e.printStackTrace();  
  105.                      
  106.                 }  
  107.                 AppendFile file = new AppendFile();  
  108.                 file.setSerialNumber(time);// 唯一标识  
  109.                 file.setFileName(fileName);// 文件名  
  110.                 file.setExtension(fileName.substring(fileName.lastIndexOf(".") + 1));// 文件后缀    
  111.                 file.setType("email");// 文件类型  
  112.                 emailService.addAttach(entity.getId(), file);  
  113.                 AppendFile result = null;  
  114.                 result = appendFileService.getByNumber(time);  
  115.                 appenFiles.add(result);  
  116.                   
  117.             }  
  118.         }  
  119.         return appenFiles;  
  120.     }  
  121.      
  122.   
  123.     // 写文件  
  124.     private void writeFile(DataHandler dh, String fileName) throws IOException {  
  125.         InputStream is = dh.getInputStream();  
  126.         File file = new File(PATH);  
  127.         if ( !file.exists() ) {  
  128.             file.mkdirs();  
  129.         }  
  130.         // LOG.info("附件目录:" + file.getAbsolutePath());  
  131.         writeToFile(is, PATH + fileName);  
  132.     }  
  133.   
  134.     private void writeToFile(InputStream is, String path) throws IOException {  
  135.   
  136.         File file = new File(path);  
  137.         OutputStream out = new FileOutputStream(file);  
  138.         int len = 0;  
  139.         byte[] bytes = new byte[1024];  
  140.         while ( (len = is.read(bytes)) != -1 ) {  
  141.             out.write(bytes, 0, len);  
  142.         }  
  143.         out.flush();  
  144.         out.close();  
  145.   
  146.     }  
  147.   
  148.     @Override  
  149.     public Response update(long id, String content, List<Attachment> attachments) throws ParseException {  
  150.         InnerMails entity = emailService.get(id);  
  151.         JSONObject preceInfo = JSONObject.fromObject(content);  
  152.         JSONObject backInfo = new JSONObject();  
  153.         if ( null != entity ) {  
  154.             entity.setSubject(preceInfo.optString("subject"));  
  155.             entity.setToMails(preceInfo.optString("toMails"));  
  156.             entity.setUrgency(preceInfo.optString("urgency"));  
  157.             Date sendDate = null;  
  158.             if ( preceInfo.optString("sendDate") != null && preceInfo.optString("sendDate") != "" ) {  
  159.                 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");  
  160.                 sendDate = df.parse(preceInfo.optString("sendDate"));  
  161.             }  
  162.           //保存附件  
  163.             Set<AppendFile> appfiles=addAttach(attachments, entity);  
  164.             entity.setAppendFiles(appfiles);  
  165.             entity.setSendDate(sendDate);  
  166.             entity.setContent(preceInfo.optString("content"));  
  167.             entity.setMailUser(preceInfo.optString("mailUser"));  
  168.             entity.setSendMail(preceInfo.optString("sendMail"));  
  169.             entity.setType(preceInfo.optInt("type"));  
  170.             
  171.             addAttach(attachments, entity);  
  172.             entity = emailService.update(entity);  
  173.             if ( entity != null ) {  
  174.                 backInfo = JSONObject.fromObject(entity);  
  175.                 return Response.ok(backInfo.toString(), MediaType.APPLICATION_JSON).build();  
  176.             } else {  
  177.                 backInfo.put("message""修改失败");  
  178.                 return Response.ok(backInfo.toString(), MediaType.APPLICATION_JSON).build();  
  179.             }  
  180.   
  181.         }  
  182.         backInfo.put("message""没有找到指定的邮件");  
  183.         return Response.ok(backInfo.toString(), MediaType.APPLICATION_JSON).build();  
  184.     }  
  185.   
  186.     @Override  
  187.     public Response get(long id) {  
  188.         JSONObject backInfo = new JSONObject();  
  189.         InnerMails entity = emailService.get(id);  
  190.         JSONObject jo;  
  191.         /*JsonConfig JSONConfig = Constant.jsonDateConfigWithHour; 
  192.         JSONConfig.setExcludes(new String[] {"appendFiles"});*/  
  193.         // 去掉延迟加载的字段  
  194.         jo = JSONObject.fromObject(entity);  
  195.         //修改状态为已读  
  196.         entity.setType(3);  
  197.         emailService.update(entity);  
  198.         if ( null != entity ) {  
  199.             backInfo = JSONObject.fromObject(jo);  
  200.             return Response.ok(backInfo.toString(), MediaType.APPLICATION_JSON).build();  
  201.         }  
  202.         backInfo.put("message""没有找到指定的内部邮件");  
  203.         return Response.ok(backInfo.toString(), MediaType.APPLICATION_JSON).build();  
  204.     }  
  205.   
  206.     @Override  
  207.     public Response getList(String range, String query) {  
  208.         QueryParam queryParam = new QueryParam();  
  209.         int from = 0;  
  210.         int to = 9;  
  211.         try {  
  212.             
  213.             String[] ranges = range.replace("items=",  "").split("-");  
  214.             from = Integer.parseInt(ranges[0]);  
  215.             to = Integer.parseInt(ranges[1]);  
  216.         } catch ( Exception e ) {  
  217.             e.printStackTrace();  
  218.         }  
  219.   
  220.         queryParam.setFirst(from);  
  221.         int max = to - from + 1;  
  222.         if ( max > 0 ) {  
  223.             queryParam.setMax(max);  
  224.         }  
  225.         if(null!=query){  
  226.             QueryUtil.prepareQuery(query, queryParam);  
  227.         }  
  228.         int count=emailService.getCount(queryParam);  
  229.         List<InnerMails> list=emailService.getlist(queryParam);  
  230.        JsonConfig jsonconfig=Constant.jsonDateConfig;  
  231.         jsonconfig.setExcludes(new String[] {"appendFiles"});  
  232.         String contentRange=String.format("items %d-%d/%d", from,to,count);  
  233.         JSONArray ja = JSONArray.fromObject(list,jsonconfig);  
  234.         String entity = ja.toString();  
  235.         return Response.ok(entity, MediaType.APPLICATION_JSON).header("Content-Range", contentRange).build();  
  236.   
  237.     }  
  238.   
  239.     @Override  
  240.     public Response delete(long id) {  
  241.        JSONObject backInfo=new JSONObject();  
  242.        try {  
  243.         emailService.delete(id);  
  244.         backInfo.put("message""删除成功");  
  245.         return Response.ok(backInfo.toString(), MediaType.APPLICATION_JSON).build();  
  246.     } catch ( Exception e ) {  
  247.         backInfo.put("message","删除失败");  
  248.         return Response.ok(backInfo.toString(),MediaType.APPLICATION_JSON).build();  
  249.     }  
  250.     }  
  251.   
  252.     @Override  
  253.     public Response sendMail(/*String content,List<Attachment> attachments*/long id){  
  254.        JSONObject backInfo=new JSONObject();  
  255.         //通过id找到对应的邮件  
  256.         InnerMails entity=emailService.get(id);  
  257.         //将A的邮件mail状态改为发送  
  258.         entity.setType(1);  
  259.         entity=emailService.update(entity);  
  260.         //找到收件人,根据收件人的个数来新增多条邮件  
  261.         String toMail=entity.getToMails();  
  262.         String[] toMails=toMail.split(",");  
  263.           
  264.         for(String tomail:toMails){  
  265.             //新增邮件,修改mail1的拥有者,修改状态为未读  
  266.             InnerMails newMails=new InnerMails();  
  267.             newMails.setSubject(entity.getSubject());  
  268.             newMails.setToMails(entity.getToMails());  
  269.             newMails.setUrgency(entity.getUrgency());  
  270.             newMails.setAppendFiles(entity.getAppendFiles());  
  271.             newMails.setSendDate(entity.getSendDate());  
  272.             newMails.setContent(entity.getContent());  
  273.             newMails.setSendMail(entity.getSendMail());  
  274.             newMails.setType(2);  
  275.             newMails.setMailUser(getNoFromChar(tomail));  
  276.             emailService.save(newMails);  
  277.         }  
  278.           
  279.         backInfo.put("发送邮件的人数", toMails.length);  
  280.         return Response.ok(backInfo.toString(), MediaType.APPLICATION_JSON).build();  
  281.           
  282.           
  283.     }  
  284.     //截取字符串中的数字  
  285.      private String  getNoFromChar(String params) {   
  286.         String regex="[^0-9]";  
  287.         Pattern p=Pattern.compile(regex);  
  288.         Matcher m=p.matcher(params);  
  289.         return m.replaceAll("").trim();  
  290.     }  
  291.   
  292.     @Override  
  293.     public Response downLoadAttach(long id) {  
  294.        //根据附件名称去指定路径中找附件  
  295.         AppendFile appendFile=appendFileService.get(id);  
  296.         if ( null == appendFile ) {  
  297.             return Response.status(Status.NOT_FOUND).entity("找不到文件").build();  
  298.         }  
  299.         final File file=new File(PATH, appendFile.getFileName());  
  300.         JSONObject preceInfo=new JSONObject();  
  301.         if(!file.exists()||!file.isFile()){  
  302.             preceInfo.put("message","没有找到指定的文件");  
  303.             return Response.status(Status.NOT_FOUND).entity("找不到文件:"+file.getName()).build();  
  304.         }  
  305.         //下载附件  
  306.         StreamingOutput entity=downLoad(file);  
  307.         String fileName=file.getName().toLowerCase();  
  308.         String type=MediaType.APPLICATION_OCTET_STREAM;  
  309.         if(fileName.endsWith(".jpg")||fileName.endsWith(".png")){  
  310.             type="image/jpeg";  
  311.         }else if(fileName.endsWith(".doc")){  
  312.             type="application/msword;charset=utf-8";  
  313.         }else if(fileName.endsWith(".pdf")){  
  314.             type="application/pdf;charset=utf-8";  
  315.         }  
  316.         try {  
  317.             //结局中文名字乱码的问题  
  318.             fileName=new String(file.getName().getBytes("UTF-8"),"ISO-8859-1");  
  319.         } catch ( Exception e ) {  
  320.             // TODO: handle exception  
  321.         }  
  322.         return Response.ok(entity, type).header("Content-disposition""inline;filename="+fileName).build();  
  323.     }  
  324.   
  325.     //下载附件方法  
  326.     private StreamingOutput downLoad(final File file) {  
  327.         StreamingOutput entity=new StreamingOutput() {  
  328.               
  329.             @Override  
  330.             public void write(OutputStream output) throws IOException, WebApplicationException {  
  331.                 int len=0;  
  332.                 byte[] buffer=new byte[1024];  
  333.                 InputStream intpStream=new FileInputStream(file);  
  334.                 while((len = intpStream.read(buffer))>0){  
  335.                     output.write(buffer, 0,len);  
  336.                 }  
  337.                 intpStream.close();  
  338.                 output.flush();  
  339.                 output.close();  
  340.                   
  341.             }  
  342.         };  
  343.         return entity;  
  344.     }  
  345. }  
restful层的配置文件:

[java]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3. <blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/blueprint/jaxrs"  
  5.     xmlns:cxf="http://cxf.apache.org/blueprint/core"  
  6.     xsi:schemaLocation="  
  7.       http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd  
  8.       http://cxf.apache.org/blueprint/jaxrs http://cxf.apache.org/schemas/blueprint/jaxrs.xsd  
  9.       http://cxf.apache.org/blueprint/core http://cxf.apache.org/schemas/blueprint/core.xsd">  
  10.   
  11.     <jaxrs:server id="OARestService" address="/oa">  
  12.         <jaxrs:serviceBeans>  
  13.             <ref component-id="mailRestService" />  
  14.         </jaxrs:serviceBeans>  
  15.         <jaxrs:providers>  
  16.             <ref component-id="authFilter" />  
  17.         </jaxrs:providers>  
  18.     </jaxrs:server>  
  19.   
  20.     <!-- implements OAuthDataProvider -->  
  21.     <bean id="oauthProvider" class="com.gzydt.oa.auth.OAuthManager" />  
  22.     <bean id="authorizationService"  
  23.         class="org.apache.cxf.rs.security.oauth2.services.AuthorizationCodeGrantService">  
  24.         <property name="dataProvider" ref="oauthProvider" />  
  25.     </bean>  
  26.     <jaxrs:server id="appServer" address="/myapp">  
  27.         <jaxrs:serviceBeans>  
  28.             <ref component-id="authorizationService" />  
  29.         </jaxrs:serviceBeans>  
  30.     </jaxrs:server>  
  31.   
  32.     <!-- <cxf:bus> <cxf:features> <cxf:logging /> </cxf:features> </cxf:bus> -->  
  33.   
  34.   
  35.     <!-- We are using the OSGi Blueprint XML syntax to define a bean that we   
  36.         referred to in our JAX-RS server setup. This bean carries a set of JAX-RS   
  37.         annotations that allow its methods to be mapped to incoming requests. -->  
  38.     <bean id="authRestService" class="com.gzydt.oa.resource.impl.AuthResourceImpl">  
  39.         <property name="userService" ref="userService" />  
  40.     </bean>  
  41.     <bean id="authFilter" class="com.gzydt.oa.auth.AuthenticationFilter">  
  42.     </bean>  
  43.     <bean id="backlogRestService" class="com.gzydt.oa.resource.impl.BacklogResourceImpl">  
  44.         <property name="registerService" ref="registerService" />  
  45.     </bean>  
  46.     <bean id="securityResource" class="com.gzydt.oa.resource.impl.SecurityResourceImpl"  
  47.         scope="singleton" init-method="init" destroy-method="destroy">  
  48.         <property name="userService" ref="userService" />  
  49.         <property name="deptService" ref="deptService" />  
  50.         <property name="dutyUsersService" ref="dutyUsersService" />  
  51.         <property name="unitService" ref="unitService" />  
  52.   
  53.     </bean>  
  54.   
  55.     <!--添加bean -->  
  56.   
  57.     <bean id="mailRestService" class="com.gzydt.oa.resource.impl.InnerMailsResourceImpl">  
  58.         <property name="emailService" ref="emailService" />  
  59.         <property name="appendFileService" ref="appendFileService" />  
  60.     </bean>  
  61.   
  62.     <!--添加bean结束 -->  
  63.       
  64.     <reference id="emailService" interface="com.gzydt.oa.service.InnerMailService" />  
  65.       
  66.     <!--添加reference结束 -->  
  67.   
  68. </blueprint>  

解析前端传来的参数:

[java]  view plain  copy
  1. package com.gzydt.oa.util;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5. import java.util.Iterator;  
  6. import java.util.List;  
  7. import java.util.Map;  
  8.   
  9. import net.sf.json.JSONObject;  
  10.   
  11. import com.gzydt.oa.commons.QueryParam;  
  12.   
  13. public class QueryUtil {  
  14.   
  15.     /** 
  16.      * 解析url中的查询条件的参数 
  17.      *  
  18.      * @param query 
  19.      *            :查询标示 
  20.      * @param queryParam 
  21.      *            :url中的查询参数 
  22.      * @return 为空 
  23.      */  
  24.     public static void prepareQuery(String query, QueryParam queryParam) {  
  25.         try {  
  26.             JSONObject jo = JSONObject.fromObject(query);  
  27.             Map<String, String> param = new HashMap<String, String>();  
  28.             List<String> sorts = new ArrayList<String>();  
  29.             for ( @SuppressWarnings("unchecked")  
  30.             Iterator<String> iterator = jo.keySet().iterator(); iterator.hasNext(); ) {  
  31.                 String key = iterator.next();  
  32.                 String value = jo.optString(key);  
  33.                 if ( !value.isEmpty() ) {  
  34.                     if ( "sort".equals(key) ) {  
  35.                         for ( String s : value.split(",") ) {  
  36.                             if ( null != s ) {  
  37.                                 if ( s.startsWith("8") ) {// 前端无法传“+”  
  38.                                     s = "+" + s.substring(1, s.length());  
  39.                                 } else {  
  40.                                     s = "-" + s.substring(1, s.length());  
  41.                                 }  
  42.                                 sorts.add(s);  
  43.                             }  
  44.                         }  
  45.                     } else {  
  46.                         param.put(key, value);  
  47.                     }  
  48.                 }  
  49.             }  
  50.             queryParam.setParam(param);  
  51.             queryParam.setSorts(sorts);  
  52.         } catch ( Exception e ) {  
  53.             e.printStackTrace();  
  54.         }  
  55.     }  
  56.   
  57. }  

内部邮件的测试类:

[java]  view plain  copy
  1. package com.gzydt.oa.resource;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.IOException;  
  6. import java.io.UnsupportedEncodingException;  
  7. import java.util.ArrayList;  
  8. import java.util.List;  
  9.   
  10. import org.apache.commons.httpclient.HttpClient;  
  11. import org.apache.commons.httpclient.HttpException;  
  12. import org.apache.commons.httpclient.NameValuePair;  
  13. import org.apache.commons.httpclient.methods.DeleteMethod;  
  14. import org.apache.commons.httpclient.methods.GetMethod;  
  15. import org.apache.commons.httpclient.methods.PostMethod;  
  16. import org.apache.commons.httpclient.methods.PutMethod;  
  17. import org.apache.commons.httpclient.methods.RequestEntity;  
  18. import org.apache.commons.httpclient.methods.StringRequestEntity;  
  19. import org.apache.commons.httpclient.methods.multipart.FilePart;  
  20. import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;  
  21. import org.apache.commons.httpclient.methods.multipart.Part;  
  22. import org.apache.commons.httpclient.methods.multipart.StringPart;  
  23. import org.apache.commons.httpclient.params.HttpMethodParams;  
  24. import org.json.JSONObject;  
  25. import org.junit.Assert;  
  26. import org.junit.Test;  
  27. import org.slf4j.Logger;  
  28. import org.slf4j.LoggerFactory;  
  29.   
  30. public class MailTest extends Tester {  
  31.     private static final String TEST_URL = "http://localhost:8181/cxf/oa/mails";  
  32.   
  33.     private static final Logger LOG = LoggerFactory.getLogger(MailTest.class);  
  34.   
  35.     /** 
  36.      * 登记信息写邮件 
  37.      *  
  38.      * @throws FileNotFoundException 
  39.      */  
  40.     @Test  
  41.     public void uploadOrigText() throws FileNotFoundException {  
  42.   
  43.         /* 
  44.          * JSONObject jo = new JSONObject(); jo.put("subject", "周末计划");// 主题 
  45.          * jo.put("toMails", "aa<13>,bb<2>");// 收件人 格式 :姓名<userId>;姓名<userId> 
  46.          * jo.put("urgency", "加急");// 紧急程度 jo.put("sendDate", "2015-4-11");// 
  47.          * 发布日期 jo.put("content", "周末购物");// 邮件内容 jo.put("mailUser", "14");// 
  48.          * 邮件拥有者 格式:userId jo.put("sendMail", "cc<14>");// 邮件发送者 
  49.          * 格式:姓名<userId>,若只是新建,则不需要改字段 jo.put("type", "0");// 
  50.          * 状态标示:-1删除;0草稿;1发送;2未读收件,3已读收件 //新增不需要增加type 
  51.          */  
  52.         // 要上传的文件  
  53.         String path = "F:\\1.doc";  
  54.         String path1 = "F:\\3.doc";  
  55.         long start = System.currentTimeMillis();  
  56.   
  57.         File file = new File(path);  
  58.         File fileText = new File(path1);  
  59.   
  60.         // 'type': '0',  
  61.         String content = "{ 'content''周末野炊','sendDate''2015-04-11',  
  62. 'toMails''aa<13>,bb<2>','mailUser''14','subject''周末计划','sendMail''','urgency''加急'}";  
  63.         Part[] parts = { new FilePart("file", file, "application/octet-stream""UTF-8"),  
  64.                 new FilePart("file", fileText, "application/octet-stream""UTF-8"),  
  65.  new StringPart("content", content, "UTF-8") };  
  66.   
  67.         PostMethod post = new PostMethod(TEST_URL);  
  68.         post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));  
  69.   
  70.         HttpClient httpclient = new HttpClient();  
  71.         String res = "";  
  72.   
  73.         try {  
  74.             int result = httpclient.executeMethod(post);  
  75.             LOG.info("Response status code: " + result);  
  76.             LOG.info("Response body: ");  
  77.             res = getStringFromInputStream(post.getResponseBodyAsStream());  
  78.             LOG.info(res);  
  79.         } catch ( Exception e ) {  
  80.             LOG.error("Error connecting to {}", TEST_URL);  
  81.             Assert.fail("Connection error");  
  82.         } finally {  
  83.             // Release current connection to the connection pool once you  
  84.             // are  
  85.             // done  
  86.             post.releaseConnection();  
  87.         }  
  88.         LOG.info("断言:验证成功返回【ok】响应!");  
  89.         Assert.assertTrue("ok".equals(res));  
  90.         long end = System.currentTimeMillis();  
  91.         LOG.info("验证用时(毫秒):" + (end - start));  
  92.     }  
  93.   
  94.     /** 
  95.      * 发邮件 
  96.      * @throws Exception  
  97.      * @throws FileNotFoundException 
  98.      */  
  99.     @Test  
  100.     public void sendEmail() throws Exception {  
  101.         long id = 2l;  
  102.         LOG.info("开始测试发送邮件");  
  103.         PostMethod post = new PostMethod(TEST_URL +"/sendMails/"+ id);  
  104.         post.addRequestHeader("Accept""application/json");  
  105.         post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");  
  106.          
  107.            /* JSONObject jo = new JSONObject(); 
  108.             jo.put("subject", "周末计划");// 主题 
  109.             jo.put("toMails", "aa<13>,bb<2>");// 收件人 格式 :姓名<userId>;姓名<userId> 
  110.             jo.put("urgency", "加急");// 紧急程度 
  111.             jo.put("sendDate", "2015-4-11");// 发布日期 
  112.             jo.put("content", "周末购物");// 邮件内容 
  113.             jo.put("mailUser", "14");// 邮件拥有者 格式:userId 
  114.             jo.put("sendMail", "cc<14>");// 邮件发送者 格式:姓名<userId>,若只是新建,则不需要改字段 
  115. */          //  LOG.debug("设置请求参数:" + jo.toString());  
  116.         JSONObject jo = new JSONObject();  
  117.             RequestEntity entity = new StringRequestEntity(jo.toString(), "application/json""UTF-8");  
  118.             post.setRequestEntity(entity);  
  119.             HttpClient httpclient = new HttpClient();  
  120.             String res = "";  
  121.             LOG.info("发送post请求");  
  122.             int result = httpclient.executeMethod(post);  
  123.             LOG.info(" 响应状态:" + result);  
  124.             res = this.getStringFromInputStream(post.getResponseBodyAsStream());  
  125.             LOG.info("响应结果::" + res);  
  126.             LOG.info("断言:");  
  127.              
  128.           
  129.     }  
  130.   
  131.     // 将邮件放进回收站,是将状态改为-1  
  132.     @Test  
  133.     public void updateTest() throws FileNotFoundException {  
  134.         LOG.info("开始测试更新");  
  135.         long id = 1;  
  136.         PutMethod put = new PutMethod(TEST_URL + "/" + id);  
  137.         // 要上传的文件  
  138.         String path = "F:\\1.doc";  
  139.         String path1 = "F:\\3.doc";  
  140.         long start = System.currentTimeMillis();  
  141.   
  142.         File file = new File(path);  
  143.         File fileText = new File(path1);  
  144.   
  145.         String content = "{ 'content''周末加班','sendDate''2015-4-11','toMails''aa<13>,bb<2>',  
  146. 'mailUser''14','subject''周末计划','type''0','sendMail''','urgency''加急'}";  
  147.         Part[] parts = { new FilePart("file", file, "application/octet-stream""UTF-8"),  
  148.                 new FilePart("file", fileText, "application/octet-stream""UTF-8"),  
  149.  new StringPart("content", content, "UTF-8") };  
  150.   
  151.         put.addRequestHeader("Accept""application/json");  
  152.         put.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");  
  153.         put.setRequestEntity(new MultipartRequestEntity(parts, put.getParams()));  
  154.         HttpClient httpclient = new HttpClient();  
  155.         String res = "";  
  156.   
  157.         try {  
  158.             int result = httpclient.executeMethod(put);  
  159.             LOG.info("Response status code: " + result);  
  160.             LOG.info("Response body: ");  
  161.             res = getStringFromInputStream(put.getResponseBodyAsStream());  
  162.             LOG.info(res);  
  163.         } catch ( Exception e ) {  
  164.             LOG.error("Error connecting to {}", TEST_URL);  
  165.             Assert.fail("Connection error");  
  166.         } finally {  
  167.             put.releaseConnection();  
  168.         }  
  169.         LOG.info("断言:验证成功返回【ok】响应!");  
  170.         Assert.assertTrue("ok".equals(res));  
  171.         long end = System.currentTimeMillis();  
  172.         LOG.info("验证用时(毫秒):" + (end - start));  
  173.     }  
  174.   
  175.     /** 
  176.      * 根据特定的id来找到值班人员的用户信息 
  177.      */  
  178.     @Test  
  179.     public void findTest() {  
  180.         long id = 15L;  
  181.         GetMethod get = new GetMethod(TEST_URL + "/" + id);  
  182.         HttpClient client = new HttpClient();  
  183.         String res = "";  
  184.         try {  
  185.             int retCode = client.executeMethod(get);  
  186.             LOG.info("响应状态 " + retCode);  
  187.             res = this.getStringFromInputStream(get.getResponseBodyAsStream());  
  188.             LOG.info("响应结果" + res);  
  189.         } catch ( Exception e ) {  
  190.             LOG.error("该url路径出错,服务未开启,请检查", TEST_URL + "/" + id);  
  191.             Assert.fail("连接失败.");  
  192.         } finally {  
  193.             get.releaseConnection();  
  194.         }  
  195.     }  
  196.   
  197.     @Test  
  198.     public void queryTest() {  
  199.         LOG.info("开始测试分页查询");  
  200.         GetMethod get = new GetMethod(TEST_URL + "/list");  
  201.         get.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");  
  202.         List<NameValuePair> params = new ArrayList<NameValuePair>();  
  203.         // 设置分页有信息  
  204.         get.setRequestHeader("Range""items=0-9");  
  205.   
  206.         JSONObject jo = new JSONObject();  
  207.         LOG.debug("请求参数::" + jo.toString());  
  208.   
  209.         // jo.put("mailUser", "14");  
  210.         jo.put("sendDate""2015-01-10~2015-01-13");  
  211.         /* 
  212.          * jo.put("type", "0"); jo.put("content","周末"); 
  213.          */  
  214.         // jo.put("issueDate", "2015-01-10~2015-02-24");  
  215.         // jo.put("sendFileDate", "2015-01-14~2015-02-04");  
  216.         // jo.put("getFileDate", "2015-01-11~2015-02-04");  
  217.         // jo.put("fromUnit", "Scgovernment");  
  218.         /* jo.put("issueDate", "2015-3") */  
  219.         // jo.put("number","Yfp");  
  220.         // jo.put("refNumber", "a11111");  
  221.         // jo.put("sendUnit", "Shengbangongting");  
  222.         // jo.put("title","22222");  
  223.         JSONObject jb = new JSONObject();  
  224.         params.add(new NameValuePair("query", jo.toString()));// 从0开始的  
  225.         get.setQueryString(params.toArray(new NameValuePair[0]));  
  226.   
  227.         HttpClient httpClient = new HttpClient();  
  228.         String res = "";  
  229.         try {  
  230.   
  231.             int result = httpClient.executeMethod(get);  
  232.             LOG.info("响应状态 " + result);  
  233.             res = this.getStringFromInputStream(get.getResponseBodyAsStream());  
  234.             LOG.info("响应结果 " + res);  
  235.         } catch ( Exception e ) {  
  236.             LOG.error("该url路径出错,服务未开启,请检查", TEST_URL);  
  237.             Assert.fail("连接失败.");  
  238.         } finally {  
  239.             get.releaseConnection();  
  240.         }  
  241.     }  
  242.   
  243.     /** 
  244.      * 测试删除周知事项 
  245.      */  
  246.     @Test  
  247.     public void TestDelete() {  
  248.         LOG.info("开始测试删除通知");  
  249.         long id = 1L;  
  250.         DeleteMethod delete = new DeleteMethod(TEST_URL + "/" + id);  
  251.         HttpClient client = new HttpClient();  
  252.         String res = "";  
  253.         try {  
  254.             LOG.info("发送delete请求删除通知");  
  255.             int retCode = client.executeMethod(delete);  
  256.             LOG.info("响应状态:" + retCode);  
  257.   
  258.             res = this.getStringFromInputStream(delete.getResponseBodyAsStream());  
  259.             LOG.info("响应结果: " + res);  
  260.         } catch ( Exception e ) {  
  261.             LOG.error("测试错误", e);  
  262.             Assert.fail("连接出错");  
  263.         } finally {  
  264.             /* 释放url的资源 */  
  265.             delete.releaseConnection();  
  266.         }  
  267.         LOG.info(res);  
  268.     }  
  269.   
  270. }  

在添加一个正常的测试新增的方法:
[java]  view plain  copy
  1. @Test  
  2.     public void testAdd(){  
  3.         LOG.info("开始测试增加");  
  4.         PostMethod post = new PostMethod(TEST_URL);  
  5.         post.addRequestHeader("Accept""application/json");  
  6.         post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,  
  7.                 "UTF-8");  
  8.         try {  
  9.             JSONObject jo = new JSONObject();  
  10.               
  11.             jo.put("day""2015-4-10");  
  12.             jo.put("type""0");  
  13.             jo.put("content""gfdz参加了2014年广东省某某某某活动");  
  14.             jo.put("mainLeaderIds""2,3");  
  15.             jo.put("relevantLeaderIds""5,6");  
  16.             // date  
  17.             jo.put("goverEvent"true);  
  18.             jo.put("ownEvent"false);  
  19.             jo.put("ownerId""2");  
  20.             LOG.debug("设置请求参数:" + jo.toString());  
  21.             RequestEntity entity = new StringRequestEntity(  
  22.                     jo.toString(), "application/json""UTF-8");  
  23.             post.setRequestEntity(entity);  
  24.             HttpClient httpclient = new HttpClient();  
  25.             String res = "";  
  26.             LOG.info("发送post请求");  
  27.             int result = httpclient.executeMethod(post);  
  28.             LOG.info(" 响应状态:" + result);  
  29.   
  30.             res = this.getStringFromInputStream(post.getResponseBodyAsStream());  
  31.             LOG.info("响应结果::" + res);  
  32.             Assert.assertTrue(res.contains("增加值班表"));  
  33.         } catch (Exception e) {  
  34.             LOG.error("测试错误", e);  
  35.             Assert.fail("连接出错");  
  36.         } finally {  
  37.             post.releaseConnection();  
  38.         }  
  39.     }  
Spring JPA是Spring Data JPA的一个模块,它提供了一种更简单和优雅的方式来处理数据库操作动态SQL是指在运行时根据不同的条件动态生成SQL语句,通常用于查询操作。Spring JPA提供了一种方便的方式来生成动态SQL,这种方式称为Specification。 Specification是一个接口,它定义了一个生成动态SQL语句的方法。这个方法需要返回一个Predicate对象,Predicate对象可以用来表示查询条件。Specification接口可以被实现,以便为每个查询定义一个特定的规范。Spring Data JPA还提供了一个SpecificationExecutor接口,它提供了使用Specification进行查询的方法。 使用Spring JPA动态SQL有以下几个步骤: 1. 创建一个Specification对象,实现Specification接口,并实现toPredicate方法。 2. 在Repository接口中定义使用Specification查询的方法。 3. 在Service层中调用Repository中定义的方法,传入Specification对象和Pageable对象(如果需要分页)。 下面是一个示例Specification的实现: ```java public class UserSpecification implements Specification<User> { private SearchCriteria criteria; public UserSpecification(SearchCriteria criteria) { this.criteria = criteria; } @Override public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder builder) { if (criteria.getOperation().equalsIgnoreCase(">")) { return builder.greaterThanOrEqualTo(root.<String> get(criteria.getKey()), criteria.getValue().toString()); } else if (criteria.getOperation().equalsIgnoreCase("<")) { return builder.lessThanOrEqualTo(root.<String> get(criteria.getKey()), criteria.getValue().toString()); } else if (criteria.getOperation().equalsIgnoreCase(":")) { if (root.get(criteria.getKey()).getJavaType() == String.class) { return builder.like(root.<String> get(criteria.getKey()), "%" + criteria.getValue() + "%"); } else { return builder.equal(root.get(criteria.getKey()), criteria.getValue()); } } return null; } } ``` 在上面的代码中,我们实现了Specification接口的toPredicate方法,并根据SearchCriteria对象的属性值生成对应的Predicate对象。 下面是一个使用Specification进行查询的Repository方法: ```java @Repository public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> { } ``` 通过继承JpaSpecificationExecutor接口,我们可以使用Spring JPA提供的动态查询功能。 如果您有任何关于Spring JPA动态SQL方面的问题,欢迎随时问我!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值