国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁 Java Java基礎(chǔ) JPA動(dòng)態(tài)查詢語句(代碼詳解)

JPA動(dòng)態(tài)查詢語句(代碼詳解)

Jun 18, 2020 pm 01:13 PM
jpa 動(dòng)態(tài)查詢

JPA動(dòng)態(tài)查詢語句(代碼詳解)

JPA動(dòng)態(tài)查詢語句 (代碼詳解)

我們現(xiàn)在在做一個(gè)OA系統(tǒng),將新增的那些數(shù)據(jù)都寫到數(shù)據(jù)庫的時(shí)候是采用jpa規(guī)范的,(不太理解jpa的相關(guān)知識點(diǎn),今天看下相關(guān)知識,然后再補(bǔ)充jpa的知識點(diǎn)),現(xiàn)在記錄jpa中的動(dòng)態(tài)查詢語句,其實(shí)這些語句都是可以用sql語句寫的,但是sql語句寫得查詢,刪除,插入數(shù)據(jù)等操作不安全,所以采用jpa的語句。我們的項(xiàng)目是分為三層結(jié)構(gòu),第一層是實(shí)體層,在該層中專門定義某一實(shí)體的相關(guān)字段,它的set(),get()方法。第二層是服務(wù)層,將service和dao都放在一個(gè)組件中,在dao層中定義和數(shù)據(jù)庫相關(guān)的操作方法,在service層中定義相關(guān)的業(yè)務(wù)邏輯層要調(diào)用的方法。第三層是restful層,在這層定義的是和前端交互的組件。

首先講講第一層:實(shí)體層

定義一個(gè)實(shí)體

/**
* 郵件實(shí)體
*
*/  
@Entity  
@Table(name = "mail_tbl")  
public class InnerMails implements Serializable {  

	private static final long serialVersionUID = 4999674279957375152L;  

	@Id  
	@GeneratedValue  
	private long id;  

	private String subject;// 主題  

	private String toMails;// 收件人 格式 :姓名<userId>;姓名<userId>  

	private String urgency;// 緊急程度  
	  
	@Column(name = "sendDate")  
	@Temporal(TemporalType.TIMESTAMP)  
	private Date sendDate;// 發(fā)布日期  

	private String content;// 郵件內(nèi)容  

	// 原文附件  
	@OneToMany(cascade={ CascadeType.MERGE,CascadeType.REMOVE})  
	@JoinColumn(name = "mail_id")  
	@OrderBy(value = "id DESC")//注釋指明加載Attachment時(shí)按id的降序排序	
	private Set<AppendFile> appendFiles=new HashSet<AppendFile>();// 附件  

	private String mailUser;// 郵件擁有者 格式:userId  

	private String sendMail;// 郵件發(fā)送者 格式:姓名<userId>  

	private int type;// 狀態(tài)標(biāo)示:-1刪除;0草稿;1發(fā)送;2未讀收件,3已讀收件  

	public long getId() {  
		return id;  
	}  

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

	public String getSubject() {  
		return subject;  
	}  

	public void setSubject(String subject) {  
		this.subject = subject;  
	}  

	public String getToMails() {  
		return toMails;  
	}  

	public void setToMails(String toMails) {  
		this.toMails = toMails;  
	}  

	public String getUrgency() {  
		return urgency;  
	}  

	public void setUrgency(String urgency) {  
		this.urgency = urgency;  
	}  

	public Date getSendDate() {  
		return sendDate;  
	}  

	public void setSendDate(Date sendDate) {  
		this.sendDate = sendDate;  
	}  

	public String getContent() {  
		return content;  
	}  

	public void setContent(String content) {  
		this.content = content;  
	}  
	public String getMailUser() {  
		return mailUser;  
	}  

	  
	public void setMailUser(String mailUser) {  
		this.mailUser = mailUser;  
	}  

	public Set<AppendFile> getAppendFiles() {  
		return appendFiles;  
	}  

	public void setAppendFiles(Set<AppendFile> appendFiles) {  
		this.appendFiles = appendFiles;  
	}  

	public String getSendMail() {  
		return sendMail;  
	}  

	public void setSendMail(String sendMail) {  
		this.sendMail = sendMail;  
	}  

	public int getType() {  
		return type;  
	}  

	public void setType(int type) {  
		this.type = type;  
	}  

}

定義查詢實(shí)體:

package com.gzydt.oa.commons;  

import java.util.ArrayList;  
import java.util.HashMap;  
import java.util.List;  
import java.util.Map;  

/**
* 分頁查詢參數(shù)
*  
* @author huangzhenwei
* @since 2014-11-21
*  
*/  
public class QueryParam {  

	// 排序字段,以“+”、“-”符號連接排序字段名:“+key”表示 按“key”字段升序,“-key”表示按“key”字段降序。  
	private List<String> sorts = new ArrayList<String>();  
	// 起始記錄下標(biāo),從0開始計(jì)算  
	private int first = 0;  
	// 每頁最大記錄數(shù)  
	private int max = 10;  
	// 是否分頁標(biāo)志  
	private boolean isPage = true;  

	// 查詢參數(shù)  
	private Map<String, String> param = new HashMap<String, String>();  

	public QueryParam() {  

	}  

	public int getFirst() {  
		return first;  
	}  

	public void setFirst(int first) {  
		this.first = first;  
	}  

	public int getMax() {  
		return max;  
	}  

	public void setMax(int max) {  
		this.max = max;  
	}  

	public Map<String, String> getParam() {  
		return param;  
	}  

	public void setParam(Map<String, String> param) {  
		this.param = param;  
	}  

	public boolean isPage() {  
		return isPage;  
	}  

	public void setPage(boolean isPage) {  
		this.isPage = isPage;  
	}  

	public List<String> getSorts() {  
		return sorts;  
	}  

	public void setSorts(List<String> sorts) {  
		this.sorts = sorts;  
	}  
}

第二層:服務(wù)層
dao層:定義和數(shù)據(jù)庫相關(guān)操作的方法

package com.gzydt.oa.dao;  
  
import java.util.List;  
  
import com.gzydt.oa.commons.QueryParam;  
import com.gzydt.oa.entity.AppendFile;  
import com.gzydt.oa.entity.InnerMails;  
  
/**
* 郵件發(fā)送dao接口
*
*/  
public interface InnerMailDao {  
	/**
	 * 保存郵件
	 * @param mail
	 * @return
	 */  
	public InnerMails save(InnerMails mail);  
	/**
	 * 更新郵件
	 * @param mail
	 * @return
	 */  
	public InnerMails update(InnerMails mail);  
	/**
	 * 刪除郵件
	 * @param id
	 */  
	public void delete(long id);  
	/**
	 * 查詢郵件
	 * @param queryParam
	 * @return
	 */  
	public List<InnerMails> getlist(QueryParam queryParam);  
	/**
	 * 獲取單個(gè)郵件
	 * @param id
	 * @return
	 */  
	public InnerMails get(long id);  
	/**
	 * 獲取滿足條件的郵件的總數(shù)
	 * @param queryParam
	 * @return
	 */  
	public int getCount(QueryParam queryParam);  
   /**
	* 新增附件
	* @param id
	* @param appendFile
	*/  
	public void addAttach(long id,AppendFile appendFile);  
}
package com.gzydt.oa.dao.impl;  
  
import java.text.DateFormat;  
import java.text.SimpleDateFormat;  
import java.util.ArrayList;  
import java.util.Date;  
import java.util.HashSet;  
import java.util.Iterator;  
import java.util.List;  
import java.util.Map;  
import java.util.Set;  
  
import javax.persistence.EntityManager;  
import javax.persistence.TypedQuery;  
import javax.persistence.criteria.CriteriaBuilder;  
import javax.persistence.criteria.CriteriaQuery;  
import javax.persistence.criteria.Predicate;  
import javax.persistence.criteria.Root;  
  
import com.gzydt.oa.commons.QueryParam;  
import com.gzydt.oa.dao.InnerMailDao;  
import com.gzydt.oa.entity.AppendFile;  
import com.gzydt.oa.entity.InnerMails;  
  
/**
* 郵件實(shí)現(xiàn)類
*/  
public class InnerMailDaoImpl implements InnerMailDao{  
  
	private EntityManager entityManager;  
	public void setEntityManager(EntityManager entityManager) {  
		this.entityManager = entityManager;  
	}  
	/**
	 * 保存郵件
	 * @param mail
	 * @return
	 */  
	@Override  
	public InnerMails save(InnerMails mail) {  
		try {  
			entityManager.persist(mail);  
			entityManager.flush();  
			return mail;  
		} catch ( Exception e ) {  
			e.printStackTrace();  
			return null;  
		}  
	}  
	/**
	 * 更新郵件
	 * @param mail
	 * @return
	 */  
	@Override  
	public InnerMails update(InnerMails mail) {  
		try {  
			entityManager.merge(mail);  
			return mail;  
		} catch ( Exception e ) {  
			e.printStackTrace();  
			return null;  
		}  
	}  
	/**
	 * 刪除郵件
	 * @param id
	 */  
	@Override  
	public void delete(long id) {  
		  
			entityManager.createQuery("delete from  PhoneRecord e where e.id=:id").setParameter("id", id).executeUpdate();  
			
		  
	}  
	/**
	 * 查詢郵件
	 * @param queryParam
	 * @return
	 */  
	@Override  
	public List<InnerMails> getlist(QueryParam queryParam) {  
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();  
		CriteriaQuery<InnerMails> criteriaQuery = cb.createQuery(InnerMails.class);  
		Root<InnerMails> register = criteriaQuery.from(InnerMails.class);  
		// 過濾條件  
		Predicate[] predicates = createPredicate(queryParam, cb, register);  
		criteriaQuery.where(predicates);  
		int start = queryParam.getFirst();  
		int end = queryParam.getMax();  
		TypedQuery<InnerMails> typedQuery = entityManager.createQuery(criteriaQuery);  
		typedQuery.setFirstResult(start).setMaxResults(end);  
		return typedQuery.getResultList();  
	}  
  //設(shè)置查詢條件  
	private Predicate[] createPredicate(QueryParam queryParam, CriteriaBuilder cb, Root<InnerMails> entity) {  
		List<Predicate> predicates=new ArrayList<Predicate>();  
		//取出查詢條件  
		Map<String, String> param= queryParam.getParam();  
		for(Map.Entry entry:param.entrySet()){  
			String key=entry.getKey().toString();  
			String value=entry.getValue().toString();  
			if(key.equals("sendDate")){  
			   Predicate conditionTime = createOperateTime(key,cb,value,entity);  
			   if(null!=conditionTime){  
				   predicates.add(conditionTime);  
			   }		
			}else{  
				predicates.add(cb.like(entity.<String> get(key),"%"+value+"%"));  
			}  
		}  
		return predicates.toArray(new Predicate[0]);  
	}  
  
	/**
	 * 將時(shí)間作為查詢條件的方法
	 * @param cb
	 * @param value
	 * @param entity
	 */  
	private Predicate createOperateTime(String key,CriteriaBuilder cb, String value, Root<InnerMails> entity) {	
		if(null == value){  
			return null;  
		}  
		String[] operateTime=value.split("~");  
		if(operateTime.length!=2){  
			return null;  
		}  
		try {  
			DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//格式一定要寫正確,  
			Date t1=df.parse(operateTime[0] + " 00:00:00");  
			Date t2=df.parse(operateTime[1] + " 23:59:59");  
			return cb.between(entity.<Date> get(key), t1, t2);  
		} catch ( Exception e ) {  
		   e.printStackTrace();  
		}  
		return null;  
		  
	}  
  
	/**
	 * 獲取單個(gè)郵件
	 * @param id
	 * @return
	 */  
	@Override  
	public InnerMails get(long id) {  
		InnerMails innersMails=entityManager.find(InnerMails.class, id);  
	   Iterator<AppendFile> iterator=innersMails.getAppendFiles().iterator();  
		Set<AppendFile> attachs=new HashSet<AppendFile>();  
		while(iterator.hasNext()){  
			AppendFile appendFile=new AppendFile();  
			appendFile=iterator.next();  
			attachs.add(appendFile);	
		}  
		innersMails.setAppendFiles(attachs);  
	   return innersMails;  
	}  
	/**
	 * 獲取滿足條件的郵件的總數(shù)
	 * @param queryParam
	 * @return
	 */  
	@Override  
	public int getCount(QueryParam queryParam) {  
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();  
		CriteriaQuery<Long> criteriaQuery = cb.createQuery(Long.class);  
		Root<InnerMails> mails = criteriaQuery.from(InnerMails.class);  
		criteriaQuery.select(cb.countDistinct(mails));  
		// 過濾條件  
		Predicate[] predeicates = createPredicate(queryParam, cb, mails);  
		criteriaQuery.where(predeicates);  
		TypedQuery<Long> typedQuery = entityManager.createQuery(criteriaQuery);  
		int count = 0;  
		try {  
			count = typedQuery.getSingleResult().intValue();  
		} catch ( Exception e ) {  
			e.printStackTrace();  
		}  
		return count;  
	}  
	/**
	 * 新增附件
	 * @param id
	 * @param appendFile
	 */  
	@Override  
	public void addAttach(long id, AppendFile appendFile) {  
		InnerMails entity=this.get(id);  
		entity.getAppendFiles().add(appendFile);  
		entityManager.merge(entity);  
		  
	}  
  
}

動(dòng)態(tài)查詢語句的相關(guān)知識

1:查詢User表中的字段adminlever的小于給定值的數(shù)據(jù)

第一種寫法:(安全,推薦使用這種)

/**
	* 查詢某一級別以上的用戶
	*/  
   @Override  
   public List<User> getOnLeverUper(int lever) {  
	 CriteriaBuilder cb =entityManager.getCriteriaBuilder();  
	 CriteriaQuery<User> criterQuery=cb.createQuery(User.class);  
	 Root<User> entity=criterQuery.from(User.class);  
	 Path<Integer> adminLever=entity.<Integer> get("adminlever") ;  
	 criterQuery.where(cb.lessThan(adminLever, lever));  
	 TypedQuery<User> typedQuery=entityManager.createQuery(criterQuery);  
	 return typedQuery.getResultList();  
	
   }

第二種寫法:(不太安全,)

/**
	* 查詢某一級別以上的用戶
	*/  
   @Override  
   public List<User> getOnLeverUper(int lever) {  
	   List<User> users=entityManager.createQuery("from User u where u.adminlever<:adminlever")  
			   .setParameter("adminlever",lever).getResultList();  
		return users;	
	
   }

第二種刪除數(shù)據(jù)(有時(shí)候會由于某實(shí)體和另一實(shí)體設(shè)置了一對一或者多對一,或者多對多的關(guān)系而導(dǎo)致不能正常刪除數(shù)據(jù)),解決方法:

/**
	 * 刪除登記信息
	 *  
	 * @param id
	 *			登記編號
	 */  
	@Override  
	public void handleDelete(long id) throws Exception {  
		ReceiptEntity entity = entityManager.find(ReceiptEntity.class, id);  
		entityManager.remove(entity);  
		//下面的的方法刪除應(yīng)為存在外鍵關(guān)聯(lián)會刪除失敗  
	   /*entityManager.createQuery("delete from  ReceiptEntity e where e.id=:id").
		setParameter("id", id).executeUpdate();*/  
	}

service層:接口

package com.gzydt.oa.service;  
  
import java.util.List;  
  
import com.gzydt.oa.commons.QueryParam;  
import com.gzydt.oa.entity.AppendFile;  
import com.gzydt.oa.entity.InnerMails;  
  
/**
* 內(nèi)部郵件接口
*
*/  
public interface InnerMailService {  
	/**
	 * 保存郵件
	 * @param mail
	 * @return
	 */  
	public InnerMails save(InnerMails mail);  
	/**
	 * 更新郵件
	 * @param mail
	 * @return
	 */  
	public InnerMails update(InnerMails mail);  
	/**
	 * 刪除郵件
	 * @param id
	 */  
	public void delete(long id);  
	/**
	 * 查詢郵件
	 * @param queryParam
	 * @return
	 */  
	public List<InnerMails> getlist(QueryParam queryParam);  
	/**
	 * 獲取單個(gè)郵件
	 * @param id
	 * @return
	 */  
	public InnerMails get(long id);  
	/**
	 * 獲取滿足條件的郵件的總數(shù)
	 * @param queryParam
	 * @return
	 */  
	public int getCount(QueryParam queryParam);  
	/**
	 * 發(fā)郵件
	 * @param content
	 *//*
	public void sendMail(String content);*/  
	/**
	 * 新增附件
	 * @param id
	 * @param appendFile
	 */  
	public void addAttach(long id,AppendFile appendFile);  
  
}

service層:實(shí)現(xiàn)類

package com.gzydt.oa.service.impl;  
  
import java.util.List;  
  
import com.gzydt.oa.commons.QueryParam;  
import com.gzydt.oa.dao.InnerMailDao;  
import com.gzydt.oa.entity.AppendFile;  
import com.gzydt.oa.entity.InnerMails;  
import com.gzydt.oa.service.InnerMailService;  
  
/**
* 內(nèi)部郵件服務(wù)類
*
*/  
public class InnerMailServiceImpl implements InnerMailService{  
  
	private InnerMailDao mailDao;  
	  
	public void setMailDao(InnerMailDao mailDao) {  
		this.mailDao = mailDao;  
	}  
	/**
	 * 保存郵件
	 * @param mail
	 * @return
	 */  
	@Override  
	public InnerMails save(InnerMails mail) {  
		return mailDao.save(mail);  
	}  
  
	@Override  
	public InnerMails update(InnerMails mail) {  
		return mailDao.update(mail);  
	}  
	/**
	 * 刪除郵件
	 * @param id
	 */  
	@Override  
	public void delete(long id) {  
	   mailDao.delete(id);  
		  
	}  
	/**
	 * 查詢郵件
	 * @param queryParam
	 * @return
	 */  
	@Override  
	public List<InnerMails> getlist(QueryParam queryParam) {  
	   return mailDao.getlist(queryParam);  
	}  
	/**
	 * 獲取單個(gè)郵件
	 * @param id
	 * @return
	 */  
	@Override  
	public InnerMails get(long id) {  
	   return mailDao.get(id);  
	}  
	/**
	 * 獲取滿足條件的郵件的總數(shù)
	 * @param queryParam
	 * @return
	 */  
	@Override  
	public int getCount(QueryParam queryParam) {  
		return mailDao.getCount(queryParam);  
	}  
  
   /* @Override
	public void sendMail(String content) {
		
		
	}*/  
	/**
	 * 新增附件
	 * @param id
	 * @param appendFile
	 */  
	@Override  
	public void addAttach(long id, AppendFile appendFile) {  
	   mailDao.addAttach(id, appendFile);  
		  
	}  
  
}

在服務(wù)層中定義相關(guān)的服務(wù)配置

<?xml version="1.0" encoding="UTF-8"?>  
<blueprint default-activation="eager"  
	xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
	xmlns:jpa="http://aries.apache.org/xmlns/jpa/v1.0.0" xmlns:tx="http://aries.apache.org/xmlns/transactions/v1.0.0"  
	xsi:schemaLocation="  
	  http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd  
	  http://cxf.apache.org/blueprint/jaxrs http://cxf.apache.org/schemas/blueprint/jaxrs.xsd  
	  http://cxf.apache.org/blueprint/core http://cxf.apache.org/schemas/blueprint/core.xsd">  
  
	<!-- This gets the container-managed EntityManager and injects it into the  
		ServiceImpl bean. -->  
  
	<!-- dao -->  
	<bean id="mailDao" class="com.gzydt.oa.dao.impl.InnerMailDaoImpl">  
		<jpa:context unitname="com.gzydt.jpa.persistence"  
			property="entityManager" />  
		<tx:transaction method="*" value="Required" />  
	</bean>  
  
	<!--新增結(jié)束 -->  
  
  
	<!-- bean -->  
	  
	<bean id="mailService" class="com.gzydt.oa.service.impl.InnerMailServiceImpl">  
		<property name="mailDao" ref="mailDao" />  
	</bean>  
  
	  
		<!--新增結(jié)束 -->  
  
	<!-- service -->  
	<service ref="mailService" interface="com.gzydt.oa.service.InnerMailService" />  
  
	 <!-- This bundle makes use of Karaf commands to demonstrate core persistence  
		operations. Feel free to remove it. -->  
	<command-bundle xmlns="http://karaf.apache.org/xmlns/shell/v1.1.0">  
		<command name="msg/add">  
			<action class="com.gzydt.oa.command.AddMessage">  
				<property name="messageService" ref="messageService" />  
			</action>  
		</command>  
		<command name="msg/list">  
			<action class="com.gzydt.oa.command.GetMessage">  
				<property name="messageService" ref="messageService" />  
			</action>  
		</command>  
		<command name="msg/delete">  
			<action class="com.gzydt.oa.command.DeleteMessage">  
				<property name="messageService" ref="messageService" />  
			</action>  
		</command>  
  
		<command name="dept/add">  
			<action class="com.gzydt.oa.command.DeptAddCommand">  
				<property name="deptService" ref="deptService" />  
			</action>  
		</command>  
		<command name="dept/list">  
			<action class="com.gzydt.oa.command.DeptGetCommand">  
				<property name="deptService" ref="deptService" />  
			</action>  
		</command>  
		<command name="dept/delete">  
			<action class="com.gzydt.oa.command.DeptDeleteCommand">  
				<property name="deptService" ref="deptService" />  
			</action>  
		</command>  
	</command-bundle>  
  
</blueprint>

第三層:restful層

package com.gzydt.oa.resource;  
  
import java.text.ParseException;  
import java.util.List;  
  
import javax.ws.rs.Consumes;  
import javax.ws.rs.DELETE;  
import javax.ws.rs.GET;  
import javax.ws.rs.HeaderParam;  
import javax.ws.rs.POST;  
import javax.ws.rs.PUT;  
import javax.ws.rs.Path;  
import javax.ws.rs.PathParam;  
import javax.ws.rs.Produces;  
import javax.ws.rs.QueryParam;  
import javax.ws.rs.core.MediaType;  
import javax.ws.rs.core.Response;  
  
import org.apache.cxf.jaxrs.ext.multipart.Attachment;  
import org.apache.cxf.jaxrs.ext.multipart.Multipart;  
  
/**
* 內(nèi)部郵件的restful
*/  
@Path("/mails")  
public interface InnerMailsResource {  
	/**
	 * 新增郵件
	 * @param content
	 * @return
	 */  
	@POST  
	@Path("/")  
	@Consumes("multipart/form-data")  
	public Response save(@Multipart("content") String content,  
List<Attachment> attachments) throws ParseException ;  
	/**
	 * 更新郵件
	 * @param id
	 * @param content
	 * @return
	 */  
	@PUT  
	@Path("/{id}")  
	@Consumes("multipart/form-data")  
	public Response update(@PathParam("id") long id,@Multipart("content") String content,  
List<Attachment> attachments) throws ParseException;  
	/**
	 * 查詢郵件
	 * @param id
	 * @return
	 */  
	@GET  
	@Path("/{id}")  
	public Response get(@PathParam("id") long id);  
	/**
	 * 查詢郵件列表
	 * @param range
	 * @param query
	 * @return
	 */  
	@GET  
	@Path("/list")  
	public Response getList(@HeaderParam("range") String range,@QueryParam("query") String query);  
	/**
	 * 刪除郵件
	 * @param id
	 * @return
	 */  
	@DELETE  
	@Path("/{id}")  
	public Response delete(@PathParam("id") long id);  
	/**
	 * 發(fā)送郵件
	 * @param content
	 * @return  數(shù)據(jù)格式:{"data":{},"toMail":""}
	 */  
	@POST  
	@Path("/sendMails/{id}")  
	public Response sendMail(@PathParam("id")long id) ;  
	/**
	 * 下載附件
	 * @param id(附件的id)
	 * @return
	 */  
	@GET  
	@Path("/getAttach/{id}")  
	@Produces(MediaType.APPLICATION_OCTET_STREAM)  
	public Response downLoadAttach(@PathParam("id") long id);  
	  
	  
  
}

實(shí)現(xiàn)類:

package com.gzydt.oa.resource.impl;  
  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.OutputStream;  
import java.text.ParseException;  
import java.text.SimpleDateFormat;  
import java.util.Date;  
import java.util.HashSet;  
import java.util.List;  
import java.util.Set;  
import java.util.regex.Matcher;  
import java.util.regex.Pattern;  
  
import javax.activation.DataHandler;  
import javax.ws.rs.WebApplicationException;  
import javax.ws.rs.core.MediaType;  
import javax.ws.rs.core.Response;  
import javax.ws.rs.core.Response.Status;  
import javax.ws.rs.core.StreamingOutput;  
  
import net.sf.json.JSONArray;  
import net.sf.json.JSONObject;  
import net.sf.json.JsonConfig;  
  
import org.apache.cxf.jaxrs.ext.multipart.Attachment;  
/*import org.json.JSONArray;*/  
  
import com.gzydt.oa.commons.QueryParam;  
import com.gzydt.oa.entity.AppendFile;  
import com.gzydt.oa.entity.InnerMails;  
import com.gzydt.oa.resource.InnerMailsResource;  
import com.gzydt.oa.service.AppendFileService;  
import com.gzydt.oa.service.InnerMailService;  
import com.gzydt.oa.util.Constant;  
import com.gzydt.oa.util.QueryUtil;  
  
public class InnerMailsResourceImpl implements InnerMailsResource {  
	private InnerMailService emailService;  
  
	public void setEmailService(InnerMailService emailService) {  
		this.emailService = emailService;  
	}  
  
	private AppendFileService appendFileService;  
  
	public void setAppendFileService(AppendFileService appendFileService) {  
		this.appendFileService = appendFileService;  
	}  
  
	private static final String PATH = "data/oa/upload/mails";  
  
	@Override  
	public Response save(String content, List<Attachment> attachments) throws ParseException {  
		//去掉懶加載字段  
		JsonConfig jsonConfig = Constant.jsonDateConfig;  
		jsonConfig.setExcludes(new String[] { "appendFiles"});  
		JSONObject preceInfo = JSONObject.fromObject(content);  
		JSONObject backInfo = new JSONObject();  
		InnerMails entity = new InnerMails();  
		Date sendDate = null;  
		if ( preceInfo.optString("sendDate") != null && preceInfo.optString("sendDate") != "" ) {  
		//這里的MM必須是要大寫,若是寫為mm,則是分鐘,,格式一定要按照正規(guī)的來寫<span class="con">yyyy-MM-dd HH:mm:ss</span>,  
//該大寫就大寫,小寫就小寫,并且中間有空格等,都不能錯(cuò)誤。不然時(shí)間會出錯(cuò)  
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");  
			sendDate = df.parse(preceInfo.optString("sendDate"));  
		}  
		preceInfo.put("sendDate", sendDate);  
		entity = (InnerMails) JSONObject.toBean(preceInfo, InnerMails.class);  
		
		if ( !preceInfo.has("type") ) {  
			entity.setType(0);  
		}  
		entity = emailService.save(entity);  
	 // 新增附件到附件表中  
		Set<AppendFile> appfiles=addAttach(attachments, entity);  
		entity.setAppendFiles(appfiles);  
		entity=emailService.update(entity);  
  
		if ( null != entity ) {  
			backInfo = JSONObject.fromObject(entity);  
			return Response.ok(backInfo.toString(), MediaType.APPLICATION_JSON).build();  
		}  
		backInfo.put("message", "保存失敗");  
		return Response.ok(backInfo.toString(), MediaType.APPLICATION_JSON).build();  
  
	}  
	  
	// 保存并關(guān)聯(lián)附件  
	private  Set<AppendFile>  addAttach(List<Attachment> attachments,InnerMails entity){  
		Set<AppendFile> appenFiles=new HashSet<AppendFile>();  
		for (Attachment attachment : attachments) {  
			if (attachment.getContentType().toString().startsWith("application/octet-stream")) {  
				DataHandler dh = attachment.getDataHandler();  
				long time = new Date().getTime();  
				String fileName = null;  
				try {  
					fileName = new String(dh.getName().getBytes("ISO-8859-1"), "UTF-8");  
					writeFile(dh, fileName);  
				} catch (Exception e) {  
					e.printStackTrace();  
					
				}  
				AppendFile file = new AppendFile();  
				file.setSerialNumber(time);// 唯一標(biāo)識  
				file.setFileName(fileName);// 文件名  
				file.setExtension(fileName.substring(fileName.lastIndexOf(".") + 1));// 文件后綴	
				file.setType("email");// 文件類型  
				emailService.addAttach(entity.getId(), file);  
				AppendFile result = null;  
				result = appendFileService.getByNumber(time);  
				appenFiles.add(result);  
				  
			}  
		}  
		return appenFiles;  
	}  
	
  
	// 寫文件  
	private void writeFile(DataHandler dh, String fileName) throws IOException {  
		InputStream is = dh.getInputStream();  
		File file = new File(PATH);  
		if ( !file.exists() ) {  
			file.mkdirs();  
		}  
		// LOG.info("附件目錄:" + file.getAbsolutePath());  
		writeToFile(is, PATH + fileName);  
	}  
  
	private void writeToFile(InputStream is, String path) throws IOException {  
  
		File file = new File(path);  
		OutputStream out = new FileOutputStream(file);  
		int len = 0;  
		byte[] bytes = new byte[1024];  
		while ( (len = is.read(bytes)) != -1 ) {  
			out.write(bytes, 0, len);  
		}  
		out.flush();  
		out.close();  
  
	}  
  
	@Override  
	public Response update(long id, String content, List<Attachment> attachments) throws ParseException {  
		InnerMails entity = emailService.get(id);  
		JSONObject preceInfo = JSONObject.fromObject(content);  
		JSONObject backInfo = new JSONObject();  
		if ( null != entity ) {  
			entity.setSubject(preceInfo.optString("subject"));  
			entity.setToMails(preceInfo.optString("toMails"));  
			entity.setUrgency(preceInfo.optString("urgency"));  
			Date sendDate = null;  
			if ( preceInfo.optString("sendDate") != null && preceInfo.optString("sendDate") != "" ) {  
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");  
				sendDate = df.parse(preceInfo.optString("sendDate"));  
			}  
		  //保存附件  
			Set<AppendFile> appfiles=addAttach(attachments, entity);  
			entity.setAppendFiles(appfiles);  
			entity.setSendDate(sendDate);  
			entity.setContent(preceInfo.optString("content"));  
			entity.setMailUser(preceInfo.optString("mailUser"));  
			entity.setSendMail(preceInfo.optString("sendMail"));  
			entity.setType(preceInfo.optInt("type"));  
			
			addAttach(attachments, entity);  
			entity = emailService.update(entity);  
			if ( entity != null ) {  
				backInfo = JSONObject.fromObject(entity);  
				return Response.ok(backInfo.toString(), MediaType.APPLICATION_JSON).build();  
			} else {  
				backInfo.put("message", "修改失敗");  
				return Response.ok(backInfo.toString(), MediaType.APPLICATION_JSON).build();  
			}  
  
		}  
		backInfo.put("message", "沒有找到指定的郵件");  
		return Response.ok(backInfo.toString(), MediaType.APPLICATION_JSON).build();  
	}  
  
	@Override  
	public Response get(long id) {  
		JSONObject backInfo = new JSONObject();  
		InnerMails entity = emailService.get(id);  
		JSONObject jo;  
		/*JsonConfig JSONConfig = Constant.jsonDateConfigWithHour;
		JSONConfig.setExcludes(new String[] {"appendFiles"});*/  
		// 去掉延遲加載的字段  
		jo = JSONObject.fromObject(entity);  
		//修改狀態(tài)為已讀  
		entity.setType(3);  
		emailService.update(entity);  
		if ( null != entity ) {  
			backInfo = JSONObject.fromObject(jo);  
			return Response.ok(backInfo.toString(), MediaType.APPLICATION_JSON).build();  
		}  
		backInfo.put("message", "沒有找到指定的內(nèi)部郵件");  
		return Response.ok(backInfo.toString(), MediaType.APPLICATION_JSON).build();  
	}  
  
	@Override  
	public Response getList(String range, String query) {  
		QueryParam queryParam = new QueryParam();  
		int from = 0;  
		int to = 9;  
		try {  
			
			String[] ranges = range.replace("items=",  "").split("-");  
			from = Integer.parseInt(ranges[0]);  
			to = Integer.parseInt(ranges[1]);  
		} catch ( Exception e ) {  
			e.printStackTrace();  
		}  
  
		queryParam.setFirst(from);  
		int max = to - from + 1;  
		if ( max > 0 ) {  
			queryParam.setMax(max);  
		}  
		if(null!=query){  
			QueryUtil.prepareQuery(query, queryParam);  
		}  
		int count=emailService.getCount(queryParam);  
		List<InnerMails> list=emailService.getlist(queryParam);  
	   JsonConfig jsonconfig=Constant.jsonDateConfig;  
		jsonconfig.setExcludes(new String[] {"appendFiles"});  
		String contentRange=String.format("items %d-%d/%d", from,to,count);  
		JSONArray ja = JSONArray.fromObject(list,jsonconfig);  
		String entity = ja.toString();  
		return Response.ok(entity, MediaType.APPLICATION_JSON).header("Content-Range", contentRange).build();  
  
	}  
  
	@Override  
	public Response delete(long id) {  
	   JSONObject backInfo=new JSONObject();  
	   try {  
		emailService.delete(id);  
		backInfo.put("message", "刪除成功");  
		return Response.ok(backInfo.toString(), MediaType.APPLICATION_JSON).build();  
	} catch ( Exception e ) {  
		backInfo.put("message","刪除失敗");  
		return Response.ok(backInfo.toString(),MediaType.APPLICATION_JSON).build();  
	}  
	}  
  
	@Override  
	public Response sendMail(/*String content,List<Attachment> attachments*/long id){  
	   JSONObject backInfo=new JSONObject();  
		//通過id找到對應(yīng)的郵件  
		InnerMails entity=emailService.get(id);  
		//將A的郵件mail狀態(tài)改為發(fā)送  
		entity.setType(1);  
		entity=emailService.update(entity);  
		//找到收件人,根據(jù)收件人的個(gè)數(shù)來新增多條郵件  
		String toMail=entity.getToMails();  
		String[] toMails=toMail.split(",");  
		  
		for(String tomail:toMails){  
			//新增郵件,修改mail1的擁有者,修改狀態(tài)為未讀  
			InnerMails newMails=new InnerMails();  
			newMails.setSubject(entity.getSubject());  
			newMails.setToMails(entity.getToMails());  
			newMails.setUrgency(entity.getUrgency());  
			newMails.setAppendFiles(entity.getAppendFiles());  
			newMails.setSendDate(entity.getSendDate());  
			newMails.setContent(entity.getContent());  
			newMails.setSendMail(entity.getSendMail());  
			newMails.setType(2);  
			newMails.setMailUser(getNoFromChar(tomail));  
			emailService.save(newMails);  
		}  
		  
		backInfo.put("發(fā)送郵件的人數(shù)", toMails.length);  
		return Response.ok(backInfo.toString(), MediaType.APPLICATION_JSON).build();  
		  
		  
	}  
	//截取字符串中的數(shù)字  
	 private String  getNoFromChar(String params) {  
		String regex="[^0-9]";  
		Pattern p=Pattern.compile(regex);  
		Matcher m=p.matcher(params);  
		return m.replaceAll("").trim();  
	}  
  
	@Override  
	public Response downLoadAttach(long id) {  
	   //根據(jù)附件名稱去指定路徑中找附件  
		AppendFile appendFile=appendFileService.get(id);  
		if ( null == appendFile ) {  
			return Response.status(Status.NOT_FOUND).entity("找不到文件").build();  
		}  
		final File file=new File(PATH, appendFile.getFileName());  
		JSONObject preceInfo=new JSONObject();  
		if(!file.exists()||!file.isFile()){  
			preceInfo.put("message","沒有找到指定的文件");  
			return Response.status(Status.NOT_FOUND).entity("找不到文件:"+file.getName()).build();  
		}  
		//下載附件  
		StreamingOutput entity=downLoad(file);  
		String fileName=file.getName().toLowerCase();  
		String type=MediaType.APPLICATION_OCTET_STREAM;  
		if(fileName.endsWith(".jpg")||fileName.endsWith(".png")){  
			type="image/jpeg";  
		}else if(fileName.endsWith(".doc")){  
			type="application/msword;charset=utf-8";  
		}else if(fileName.endsWith(".pdf")){  
			type="application/pdf;charset=utf-8";  
		}  
		try {  
			//結(jié)局中文名字亂碼的問題  
			fileName=new String(file.getName().getBytes("UTF-8"),"ISO-8859-1");  
		} catch ( Exception e ) {  
			// TODO: handle exception  
		}  
		return Response.ok(entity, type).header("Content-disposition", "inline;filename="+fileName).build();  
	}  
  
	//下載附件方法  
	private StreamingOutput downLoad(final File file) {  
		StreamingOutput entity=new StreamingOutput() {  
			  
			@Override  
			public void write(OutputStream output) throws IOException, WebApplicationException {  
				int len=0;  
				byte[] buffer=new byte[1024];  
				InputStream intpStream=new FileInputStream(file);  
				while((len = intpStream.read(buffer))>0){  
					output.write(buffer, 0,len);  
				}  
				intpStream.close();  
				output.flush();  
				output.close();  
				  
			}  
		};  
		return entity;  
	}  
}

restful層的配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/blueprint/jaxrs"
xmlns:cxf="http://cxf.apache.org/blueprint/core"
xsi:schemaLocation="
	  http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd
	  http://cxf.apache.org/blueprint/jaxrs http://cxf.apache.org/schemas/blueprint/jaxrs.xsd
	  http://cxf.apache.org/blueprint/core http://cxf.apache.org/schemas/blueprint/core.xsd">
<jaxrs:server id="OARestService" address="/oa">
  <jaxrs:serviceBeans>
   <ref component-id="mailRestService" />
  </jaxrs:serviceBeans>
  <jaxrs:providers>
   <ref component-id="authFilter" />
  </jaxrs:providers>
</jaxrs:server>
<!-- implements OAuthDataProvider -->
<bean id="oauthProvider" class="com.gzydt.oa.auth.OAuthManager" />
<bean id="authorizationService"
  class="org.apache.cxf.rs.security.oauth2.services.AuthorizationCodeGrantService">
  <property name="dataProvider" ref="oauthProvider" />
</bean>
<jaxrs:server id="appServer" address="/myapp">
  <jaxrs:serviceBeans>
   <ref component-id="authorizationService" />
  </jaxrs:serviceBeans>
</jaxrs:server>
<!-- <cxf:bus> <cxf:features> <cxf:logging /> </cxf:features> </cxf:bus> -->

<!-- We are using the OSGi Blueprint XML syntax to define a bean that we
  referred to in our JAX-RS server setup. This bean carries a set of JAX-RS
  annotations that allow its methods to be mapped to incoming requests. -->
<bean id="authRestService" class="com.gzydt.oa.resource.impl.AuthResourceImpl">
  <property name="userService" ref="userService" />
</bean>
<bean id="authFilter" class="com.gzydt.oa.auth.AuthenticationFilter">
</bean>
<bean id="backlogRestService" class="com.gzydt.oa.resource.impl.BacklogResourceImpl">
  <property name="registerService" ref="registerService" />
</bean>
<bean id="securityResource" class="com.gzydt.oa.resource.impl.SecurityResourceImpl"
  scope="singleton" init-method="init" destroy-method="destroy">
  <property name="userService" ref="userService" />
  <property name="deptService" ref="deptService" />
  <property name="dutyUsersService" ref="dutyUsersService" />
  <property name="unitService" ref="unitService" />
</bean>
<!--添加bean -->
<bean id="mailRestService" class="com.gzydt.oa.resource.impl.InnerMailsResourceImpl">
  <property name="emailService" ref="emailService" />
  <property name="appendFileService" ref="appendFileService" />
</bean>
<!--添加bean結(jié)束 -->

<reference id="emailService" interface="com.gzydt.oa.service.InnerMailService" />
  
<!--添加reference結(jié)束 -->
</blueprint>

解析前端傳來的參數(shù):

package com.gzydt.oa.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONObject;
import com.gzydt.oa.commons.QueryParam;
public class QueryUtil {
	/**
	 * 解析url中的查詢條件的參數(shù)
	 *
	 * @param query
	 *			:查詢標(biāo)示
	 * @param queryParam
	 *			:url中的查詢參數(shù)
	 * @return 為空
	 */
	public static void prepareQuery(String query, QueryParam queryParam) {
		try {
			JSONObject jo = JSONObject.fromObject(query);
			Map<String, String> param = new HashMap<String, String>();
			List<String> sorts = new ArrayList<String>();
			for ( @SuppressWarnings("unchecked")
			Iterator<String> iterator = jo.keySet().iterator(); iterator.hasNext(); ) {
				String key = iterator.next();
				String value = jo.optString(key);
				if ( !value.isEmpty() ) {
					if ( "sort".equals(key) ) {
						for ( String s : value.split(",") ) {
							if ( null != s ) {
								if ( s.startsWith("8") ) {// 前端無法傳“+”
									s = "+" + s.substring(1, s.length());
								} else {
									s = "-" + s.substring(1, s.length());
								}
								sorts.add(s);
							}
						}
					} else {
						param.put(key, value);
					}
				}
			}
			queryParam.setParam(param);
			queryParam.setSorts(sorts);
		} catch ( Exception e ) {
			e.printStackTrace();
		}
	}
}

內(nèi)部郵件的測試類:

package com.gzydt.oa.resource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MailTest extends Tester {
	private static final String TEST_URL = "http://localhost:8181/cxf/oa/mails";
	private static final Logger LOG = LoggerFactory.getLogger(MailTest.class);
	/**
	 * 登記信息寫郵件
	 *
	 * @throws FileNotFoundException
	 */
	@Test
	public void uploadOrigText() throws FileNotFoundException {
		/*
		 * JSONObject jo = new JSONObject(); jo.put("subject", "周末計(jì)劃");// 主題
		 * jo.put("toMails", "aa<13>,bb<2>");// 收件人 格式 :姓名<userId>;姓名<userId>
		 * jo.put("urgency", "加急");// 緊急程度 jo.put("sendDate", "2015-4-11");//
		 * 發(fā)布日期 jo.put("content", "周末購物");// 郵件內(nèi)容 jo.put("mailUser", "14");//
		 * 郵件擁有者 格式:userId jo.put("sendMail", "cc<14>");// 郵件發(fā)送者
		 * 格式:姓名<userId>,若只是新建,則不需要改字段 jo.put("type", "0");//
		 * 狀態(tài)標(biāo)示:-1刪除;0草稿;1發(fā)送;2未讀收件,3已讀收件 //新增不需要增加type
		 */
		// 要上傳的文件
		String path = "F:\\1.doc";
		String path1 = "F:\\3.doc";
		long start = System.currentTimeMillis();
		File file = new File(path);
		File fileText = new File(path1);
		// &#39;type&#39;: &#39;0&#39;,
		String content = "{ &#39;content&#39;: &#39;周末野炊&#39;,&#39;sendDate&#39;: &#39;2015-04-11&#39;,
&#39;toMails&#39;: &#39;aa<13>,bb<2>&#39;,&#39;mailUser&#39;: &#39;14&#39;,&#39;subject&#39;: &#39;周末計(jì)劃&#39;,&#39;sendMail&#39;: &#39;&#39;,&#39;urgency&#39;: &#39;加急&#39;}";
		Part[] parts = { new FilePart("file", file, "application/octet-stream", "UTF-8"),
				new FilePart("file", fileText, "application/octet-stream", "UTF-8"),
new StringPart("content", content, "UTF-8") };
		PostMethod post = new PostMethod(TEST_URL);
		post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
		HttpClient httpclient = new HttpClient();
		String res = "";
		try {
			int result = httpclient.executeMethod(post);
			LOG.info("Response status code: " + result);
			LOG.info("Response body: ");
			res = getStringFromInputStream(post.getResponseBodyAsStream());
			LOG.info(res);
		} catch ( Exception e ) {
			LOG.error("Error connecting to {}", TEST_URL);
			Assert.fail("Connection error");
		} finally {
			// Release current connection to the connection pool once you
			// are
			// done
			post.releaseConnection();
		}
		LOG.info("斷言:驗(yàn)證成功返回【ok】響應(yīng)!");
		Assert.assertTrue("ok".equals(res));
		long end = System.currentTimeMillis();
		LOG.info("驗(yàn)證用時(shí)(毫秒):" + (end - start));
	}
	/**
	 * 發(fā)郵件
	 * @throws Exception
	 * @throws FileNotFoundException
	 */
	@Test
	public void sendEmail() throws Exception {
		long id = 2l;
		LOG.info("開始測試發(fā)送郵件");
		PostMethod post = new PostMethod(TEST_URL +"/sendMails/"+ id);
		post.addRequestHeader("Accept", "application/json");
		post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
	  
		   /* JSONObject jo = new JSONObject();
			jo.put("subject", "周末計(jì)劃");// 主題
			jo.put("toMails", "aa<13>,bb<2>");// 收件人 格式 :姓名<userId>;姓名<userId>
			jo.put("urgency", "加急");// 緊急程度
			jo.put("sendDate", "2015-4-11");// 發(fā)布日期
			jo.put("content", "周末購物");// 郵件內(nèi)容
			jo.put("mailUser", "14");// 郵件擁有者 格式:userId
			jo.put("sendMail", "cc<14>");// 郵件發(fā)送者 格式:姓名<userId>,若只是新建,則不需要改字段
*/		  //  LOG.debug("設(shè)置請求參數(shù):" + jo.toString());
		JSONObject jo = new JSONObject();
			RequestEntity entity = new StringRequestEntity(jo.toString(), "application/json", "UTF-8");
			post.setRequestEntity(entity);
			HttpClient httpclient = new HttpClient();
			String res = "";
			LOG.info("發(fā)送post請求");
			int result = httpclient.executeMethod(post);
			LOG.info(" 響應(yīng)狀態(tài):" + result);
			res = this.getStringFromInputStream(post.getResponseBodyAsStream());
			LOG.info("響應(yīng)結(jié)果::" + res);
			LOG.info("斷言:");
		  
	  
	}
	// 將郵件放進(jìn)回收站,是將狀態(tài)改為-1
	@Test
	public void updateTest() throws FileNotFoundException {
		LOG.info("開始測試更新");
		long id = 1;
		PutMethod put = new PutMethod(TEST_URL + "/" + id);
		// 要上傳的文件
		String path = "F:\\1.doc";
		String path1 = "F:\\3.doc";
		long start = System.currentTimeMillis();
		File file = new File(path);
		File fileText = new File(path1);
		String content = "{ &#39;content&#39;: &#39;周末加班&#39;,&#39;sendDate&#39;: &#39;2015-4-11&#39;,&#39;toMails&#39;: &#39;aa<13>,bb<2>&#39;,
&#39;mailUser&#39;: &#39;14&#39;,&#39;subject&#39;: &#39;周末計(jì)劃&#39;,&#39;type&#39;: &#39;0&#39;,&#39;sendMail&#39;: &#39;&#39;,&#39;urgency&#39;: &#39;加急&#39;}";
		Part[] parts = { new FilePart("file", file, "application/octet-stream", "UTF-8"),
				new FilePart("file", fileText, "application/octet-stream", "UTF-8"),
new StringPart("content", content, "UTF-8") };
		put.addRequestHeader("Accept", "application/json");
		put.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
		put.setRequestEntity(new MultipartRequestEntity(parts, put.getParams()));
		HttpClient httpclient = new HttpClient();
		String res = "";
		try {
			int result = httpclient.executeMethod(put);
			LOG.info("Response status code: " + result);
			LOG.info("Response body: ");
			res = getStringFromInputStream(put.getResponseBodyAsStream());
			LOG.info(res);
		} catch ( Exception e ) {
			LOG.error("Error connecting to {}", TEST_URL);
			Assert.fail("Connection error");
		} finally {
			put.releaseConnection();
		}
		LOG.info("斷言:驗(yàn)證成功返回【ok】響應(yīng)!");
		Assert.assertTrue("ok".equals(res));
		long end = System.currentTimeMillis();
		LOG.info("驗(yàn)證用時(shí)(毫秒):" + (end - start));
	}
	/**
	 * 根據(jù)特定的id來找到值班人員的用戶信息
	 */
	@Test
	public void findTest() {
		long id = 15L;
		GetMethod get = new GetMethod(TEST_URL + "/" + id);
		HttpClient client = new HttpClient();
		String res = "";
		try {
			int retCode = client.executeMethod(get);
			LOG.info("響應(yīng)狀態(tài) " + retCode);
			res = this.getStringFromInputStream(get.getResponseBodyAsStream());
			LOG.info("響應(yīng)結(jié)果" + res);
		} catch ( Exception e ) {
			LOG.error("該url路徑出錯(cuò),服務(wù)未開啟,請檢查", TEST_URL + "/" + id);
			Assert.fail("連接失敗.");
		} finally {
			get.releaseConnection();
		}
	}
	@Test
	public void queryTest() {
		LOG.info("開始測試分頁查詢");
		GetMethod get = new GetMethod(TEST_URL + "/list");
		get.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		// 設(shè)置分頁有信息
		get.setRequestHeader("Range", "items=0-9");
		JSONObject jo = new JSONObject();
		LOG.debug("請求參數(shù)::" + jo.toString());
		// jo.put("mailUser", "14");
		jo.put("sendDate", "2015-01-10~2015-01-13");
		/*
		 * jo.put("type", "0"); jo.put("content","周末");
		 */
		// jo.put("issueDate", "2015-01-10~2015-02-24");
		// jo.put("sendFileDate", "2015-01-14~2015-02-04");
		// jo.put("getFileDate", "2015-01-11~2015-02-04");
		// jo.put("fromUnit", "Scgovernment");
		/* jo.put("issueDate", "2015-3") */
		// jo.put("number","Yfp");
		// jo.put("refNumber", "a11111");
		// jo.put("sendUnit", "Shengbangongting");
		// jo.put("title","22222");
		JSONObject jb = new JSONObject();
		params.add(new NameValuePair("query", jo.toString()));// 從0開始的
		get.setQueryString(params.toArray(new NameValuePair[0]));
		HttpClient httpClient = new HttpClient();
		String res = "";
		try {
			int result = httpClient.executeMethod(get);
			LOG.info("響應(yīng)狀態(tài) " + result);
			res = this.getStringFromInputStream(get.getResponseBodyAsStream());
			LOG.info("響應(yīng)結(jié)果 " + res);
		} catch ( Exception e ) {
			LOG.error("該url路徑出錯(cuò),服務(wù)未開啟,請檢查", TEST_URL);
			Assert.fail("連接失敗.");
		} finally {
			get.releaseConnection();
		}
	}
	/**
	 * 測試刪除周知事項(xiàng)
	 */
	@Test
	public void TestDelete() {
		LOG.info("開始測試刪除通知");
		long id = 1L;
		DeleteMethod delete = new DeleteMethod(TEST_URL + "/" + id);
		HttpClient client = new HttpClient();
		String res = "";
		try {
			LOG.info("發(fā)送delete請求刪除通知");
			int retCode = client.executeMethod(delete);
			LOG.info("響應(yīng)狀態(tài):" + retCode);
			res = this.getStringFromInputStream(delete.getResponseBodyAsStream());
			LOG.info("響應(yīng)結(jié)果: " + res);
		} catch ( Exception e ) {
			LOG.error("測試錯(cuò)誤", e);
			Assert.fail("連接出錯(cuò)");
		} finally {
			/* 釋放url的資源 */
			delete.releaseConnection();
		}
		LOG.info(res);
	}
}

在添加一個(gè)正常的測試新增的方法:

@Test
public void testAdd(){
  LOG.info("開始測試增加");
  PostMethod post = new PostMethod(TEST_URL);
  post.addRequestHeader("Accept", "application/json");
  post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,
	"UTF-8");
  try {
   JSONObject jo = new JSONObject();
  
   jo.put("day", "2015-4-10");
   jo.put("type", "0");
   jo.put("content", "gfdz參加了2014年廣東省某某某某活動(dòng)");
   jo.put("mainLeaderIds", "2,3");
   jo.put("relevantLeaderIds", "5,6");
   // date
   jo.put("goverEvent", true);
   jo.put("ownEvent", false);
   jo.put("ownerId", "2");
   LOG.debug("設(shè)置請求參數(shù):" + jo.toString());
   RequestEntity entity = new StringRequestEntity(
	 jo.toString(), "application/json", "UTF-8");
   post.setRequestEntity(entity);
   HttpClient httpclient = new HttpClient();
   String res = "";
   LOG.info("發(fā)送post請求");
   int result = httpclient.executeMethod(post);
   LOG.info(" 響應(yīng)狀態(tài):" + result);
   res = this.getStringFromInputStream(post.getResponseBodyAsStream());
   LOG.info("響應(yīng)結(jié)果::" + res);
   Assert.assertTrue(res.contains("增加值班表"));
  } catch (Exception e) {
   LOG.error("測試錯(cuò)誤", e);
   Assert.fail("連接出錯(cuò)");
  } finally {
   post.releaseConnection();
  }
}

感謝大家的閱讀,希望大家收益多多。

本文轉(zhuǎn)自:?http://community.itbbs.cn/thread/758207/

推薦教程:《java視頻教程

以上是JPA動(dòng)態(tài)查詢語句(代碼詳解)的詳細(xì)內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻(xiàn),版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動(dòng)的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Clothoff.io

Clothoff.io

AI脫衣機(jī)

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強(qiáng)大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級代碼編輯軟件(SublimeText3)

熱門話題

Laravel 教程
1601
29
PHP教程
1502
276
jpa和mybatis哪個(gè)好 jpa和mybatis哪個(gè)好 Jan 15, 2024 pm 01:48 PM

選擇JPA還是MyBatis取決于具體需求和偏好。JPA和MyBatis都是Java持久層框架,都提供了將Java對象與數(shù)據(jù)庫表進(jìn)行映射的功能。如果需要一個(gè)成熟的、支持跨數(shù)據(jù)庫操作的框架,或者項(xiàng)目已經(jīng)采用了JPA作為持久層解決方案,繼續(xù)使用JPA可能是一個(gè)更好的選擇。如果要更高的性能和更靈活的SQL編寫能力,或者正在尋找一個(gè)對數(shù)據(jù)庫依賴性較小的解決方案,MyBatis更適合。

對比分析JPA和MyBatis的功能和性能 對比分析JPA和MyBatis的功能和性能 Feb 19, 2024 pm 05:43 PM

JPA和MyBatis:功能與性能對比分析引言:在Java開發(fā)中,持久化框架扮演著非常重要的角色。常見的持久化框架包括JPA(JavaPersistenceAPI)和MyBatis。本文將對這兩個(gè)框架的功能和性能進(jìn)行對比分析,并提供具體的代碼示例。一、功能對比:JPA:JPA是JavaEE的一部分,提供了一種面向?qū)ο蟮臄?shù)據(jù)持久化解決方案。它通過注解或X

Java JPA 開源項(xiàng)目推薦:為你的項(xiàng)目注入新的活力 Java JPA 開源項(xiàng)目推薦:為你的項(xiàng)目注入新的活力 Feb 20, 2024 am 09:09 AM

在Java編程領(lǐng)域,JPA(JavaPersistenceapi)作為一種流行的持久化框架,為開發(fā)者提供了對關(guān)系型數(shù)據(jù)庫進(jìn)行操作的便捷方式。通過使用JPA,開發(fā)者可以輕松地將Java對象持久化到數(shù)據(jù)庫中,并從數(shù)據(jù)庫中檢索數(shù)據(jù),從而極大地提高了應(yīng)用程序的開發(fā)效率和維護(hù)性。本文精心挑選了10個(gè)高質(zhì)量的JavaJPA開源項(xiàng)目,涵蓋了各種不同的功能和應(yīng)用場景,旨在為開發(fā)者提供更多的靈感和解決方案,助力打造更高效和可靠的應(yīng)用程序。這些項(xiàng)目包括:SpringDataJPA:springDataJPA是Spr

JPA和MyBatis:哪個(gè)更適合你的項(xiàng)目? JPA和MyBatis:哪個(gè)更適合你的項(xiàng)目? Feb 20, 2024 am 08:28 AM

JPA和MyBatis:哪個(gè)更適合你的項(xiàng)目?引言:在如今的軟件開發(fā)領(lǐng)域,數(shù)據(jù)庫是項(xiàng)目中不可或缺的一部分。為了方便對數(shù)據(jù)庫進(jìn)行操作,開發(fā)人員使用各種ORM(Object-RelationalMapping)框架來簡化開發(fā)過程。其中,JPA(JavaPersistenceAPI)和MyBatis是兩個(gè)廣泛使用的ORM框架。本篇文章將探討JPA和MyBati

比較JPA和MyBatis:如何確定最適合的持久化框架? 比較JPA和MyBatis:如何確定最適合的持久化框架? Feb 18, 2024 pm 02:12 PM

JPAvsMyBatis:如何選擇最佳的持久化框架?引言:在現(xiàn)代軟件開發(fā)中,使用持久化框架來處理數(shù)據(jù)庫操作是必不可少的。JPA(Java持久化API)和MyBatis是兩個(gè)常用的持久化框架。然而,如何選擇最適合你的項(xiàng)目的持久化框架是一個(gè)具有挑戰(zhàn)性的任務(wù)。本文將分析JPA和MyBatis的特點(diǎn),并提供具體的代碼示例,幫助你做出更明智的選擇。JPA的特點(diǎn):J

springboot jpa延遲加載問題怎么解決 springboot jpa延遲加載問題怎么解決 May 12, 2023 pm 01:58 PM

springbootjpa延遲加載問題在springboot中,在application.properties的配置文件中新增spring.jpa.open-in-view=true方法失效經(jīng)過測試,有兩種解決辦法:1、在application.properties的配置文件中新增spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true;2、在測試的方法上添加@Transactional注解。關(guān)于springboot延遲加載懶加

JPA還是MyBatis:選擇合適的ORM工具的準(zhǔn)則 JPA還是MyBatis:選擇合適的ORM工具的準(zhǔn)則 Feb 22, 2024 pm 09:57 PM

JPA還是MyBatis:選擇合適的ORM工具的準(zhǔn)則,需要具體代碼示例引言:在現(xiàn)代軟件開發(fā)中,使用ORM(對象關(guān)系映射)工具是非常常見的。ORM工具能夠?qū)㈥P(guān)系型數(shù)據(jù)庫中的表與對象模型間進(jìn)行映射,大大簡化了開發(fā)過程。然而,在選擇使用哪個(gè)ORM工具時(shí),很多開發(fā)者常常感到困惑。本文將討論如何選擇適合的ORM工具,重點(diǎn)比較JPA和MyBatis,并給出具體的代碼示例

See all articles