這篇文章將為大家詳細講解有關java中JPA動態查詢語句的用法,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
我們現在在做一個OA系統,將新增的那些數據都寫到數據庫的時候是采用jpa規范的,(不太理解jpa的相關知識點,今天看下相關知識,然后再補充jpa的知識點),現在記錄jpa中的動態查詢語句,其實這些語句都是可以用sql語句寫的,但是sql語句寫得查詢,刪除,插入數據等操作不安全,所以采用jpa的語句。我們的項目是分為三層結構,第一層是實體層,在該層中專門定義某一實體的相關字段,它的set(),get()方法。第二層是服務層,將service和dao都放在一個組件中,在dao層中定義和數據庫相關的操作方法,在service層中定義相關的業務邏輯層要調用的方法。第三層是restful層,在這層定義的是和前端交互的組件。
首先講講第一層:實體層
定義一個實體
/**
* 郵件實體
*
*/
@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;// 發布日期
private String content;// 郵件內容
// 原文附件
@OneToMany(cascade={ CascadeType.MERGE,CascadeType.REMOVE})
@JoinColumn(name = "mail_id")
@OrderBy(value = "id DESC")//注釋指明加載Attachment時按id的降序排序
private Set<AppendFile> appendFiles=new HashSet<AppendFile>();// 附件
private String mailUser;// 郵件擁有者 格式:userId
private String sendMail;// 郵件發送者 格式:姓名<userId>
private int type;// 狀態標示:-1刪除;0草稿;1發送;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;
}
}定義查詢實體:
package com.gzydt.oa.commons;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 分頁查詢參數
*
* @author huangzhenwei
* @since 2014-11-21
*
*/
public class QueryParam {
// 排序字段,以“+”、“-”符號連接排序字段名:“+key”表示 按“key”字段升序,“-key”表示按“key”字段降序。
private List<String> sorts = new ArrayList<String>();
// 起始記錄下標,從0開始計算
private int first = 0;
// 每頁最大記錄數
private int max = 10;
// 是否分頁標志
private boolean isPage = true;
// 查詢參數
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;
}
}第二層:服務層
dao層:定義和數據庫相關操作的方法
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;
/**
* 郵件發送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);
/**
* 獲取單個郵件
* @param id
* @return
*/
public InnerMails get(long id);
/**
* 獲取滿足條件的郵件的總數
* @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;
/**
* 郵件實現類
*/
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();
}
//設置查詢條件
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]);
}
/**
* 將時間作為查詢條件的方法
* @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;
}
/**
* 獲取單個郵件
* @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;
}
/**
* 獲取滿足條件的郵件的總數
* @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);
}
}動態查詢語句的相關知識
1:查詢User表中的字段adminlever的小于給定值的數據
第一種寫法:(安全,推薦使用這種)
/**
* 查詢某一級別以上的用戶
*/
@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;
}第二種刪除數據(有時候會由于某實體和另一實體設置了一對一或者多對一,或者多對多的關系而導致不能正常刪除數據),解決方法:
/**
* 刪除登記信息
*
* @param id
* 登記編號
*/
@Override
public void handleDelete(long id) throws Exception {
ReceiptEntity entity = entityManager.find(ReceiptEntity.class, id);
entityManager.remove(entity);
//下面的的方法刪除應為存在外鍵關聯會刪除失敗
/*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;
/**
* 內部郵件接口
*
*/
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);
/**
* 獲取單個郵件
* @param id
* @return
*/
public InnerMails get(long id);
/**
* 獲取滿足條件的郵件的總數
* @param queryParam
* @return
*/
public int getCount(QueryParam queryParam);
/**
* 發郵件
* @param content
*//*
public void sendMail(String content);*/
/**
* 新增附件
* @param id
* @param appendFile
*/
public void addAttach(long id,AppendFile appendFile);
}service層:實現類
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;
/**
* 內部郵件服務類
*
*/
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);
}
/**
* 獲取單個郵件
* @param id
* @return
*/
@Override
public InnerMails get(long id) {
return mailDao.get(id);
}
/**
* 獲取滿足條件的郵件的總數
* @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);
}
}在服務層中定義相關的服務配置
<?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> <!--新增結束 --> <!-- bean --> <bean id="mailService" class="com.gzydt.oa.service.impl.InnerMailServiceImpl"> <property name="mailDao" ref="mailDao" /> </bean> <!--新增結束 --> <!-- 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;
/**
* 內部郵件的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);
/**
* 發送郵件
* @param content
* @return 數據格式:{"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);
}實現類:
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,則是分鐘,,格式一定要按照正規的來寫<span class="con">yyyy-MM-dd HH:mm:ss</span>,
//該大寫就大寫,小寫就小寫,并且中間有空格等,都不能錯誤。不然時間會出錯
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();
}
// 保存并關聯附件
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);// 唯一標識
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);
//修改狀態為已讀
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", "沒有找到指定的內部郵件");
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找到對應的郵件
InnerMails entity=emailService.get(id);
//將A的郵件mail狀態改為發送
entity.setType(1);
entity=emailService.update(entity);
//找到收件人,根據收件人的個數來新增多條郵件
String toMail=entity.getToMails();
String[] toMails=toMail.split(",");
for(String tomail:toMails){
//新增郵件,修改mail1的擁有者,修改狀態為未讀
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("發送郵件的人數", toMails.length);
return Response.ok(backInfo.toString(), MediaType.APPLICATION_JSON).build();
}
//截取字符串中的數字
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) {
//根據附件名稱去指定路徑中找附件
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 {
//結局中文名字亂碼的問題
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.oauth3.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結束 --> <reference id="emailService" interface="com.gzydt.oa.service.InnerMailService" /> <!--添加reference結束 --> </blueprint>
解析前端傳來的參數:
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中的查詢條件的參數
*
* @param query
* :查詢標示
* @param queryParam
* :url中的查詢參數
* @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();
}
}
}內部郵件的測試類:
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", "周末計劃");// 主題
* jo.put("toMails", "aa<13>,bb<2>");// 收件人 格式 :姓名<userId>;姓名<userId>
* jo.put("urgency", "加急");// 緊急程度 jo.put("sendDate", "2015-4-11");//
* 發布日期 jo.put("content", "周末購物");// 郵件內容 jo.put("mailUser", "14");//
* 郵件擁有者 格式:userId jo.put("sendMail", "cc<14>");// 郵件發送者
* 格式:姓名<userId>,若只是新建,則不需要改字段 jo.put("type", "0");//
* 狀態標示:-1刪除;0草稿;1發送;2未讀收件,3已讀收件 //新增不需要增加type
*/
// 要上傳的文件
String path = "F:\\1.doc";
String path2 = "F:\\3.doc";
long start = System.currentTimeMillis();
File file = new File(path);
File fileText = new File(path2);
// 'type': '0',
String content = "{ 'content': '周末野炊','sendDate': '2015-04-11',
'toMails': 'aa<13>,bb<2>','mailUser': '14','subject': '周末計劃','sendMail': '','urgency': '加急'}";
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("斷言:驗證成功返回【ok】響應!");
Assert.assertTrue("ok".equals(res));
long end = System.currentTimeMillis();
LOG.info("驗證用時(毫秒):" + (end - start));
}
/**
* 發郵件
* @throws Exception
* @throws FileNotFoundException
*/
@Test
public void sendEmail() throws Exception {
long id = 2l;
LOG.info("開始測試發送郵件");
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", "周末計劃");// 主題
jo.put("toMails", "aa<13>,bb<2>");// 收件人 格式 :姓名<userId>;姓名<userId>
jo.put("urgency", "加急");// 緊急程度
jo.put("sendDate", "2015-4-11");// 發布日期
jo.put("content", "周末購物");// 郵件內容
jo.put("mailUser", "14");// 郵件擁有者 格式:userId
jo.put("sendMail", "cc<14>");// 郵件發送者 格式:姓名<userId>,若只是新建,則不需要改字段
*/ // LOG.debug("設置請求參數:" + 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("發送post請求");
int result = httpclient.executeMethod(post);
LOG.info(" 響應狀態:" + result);
res = this.getStringFromInputStream(post.getResponseBodyAsStream());
LOG.info("響應結果::" + res);
LOG.info("斷言:");
}
// 將郵件放進回收站,是將狀態改為-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 path2 = "F:\\3.doc";
long start = System.currentTimeMillis();
File file = new File(path);
File fileText = new File(path2);
String content = "{ 'content': '周末加班','sendDate': '2015-4-11','toMails': 'aa<13>,bb<2>',
'mailUser': '14','subject': '周末計劃','type': '0','sendMail': '','urgency': '加急'}";
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("斷言:驗證成功返回【ok】響應!");
Assert.assertTrue("ok".equals(res));
long end = System.currentTimeMillis();
LOG.info("驗證用時(毫秒):" + (end - start));
}
/**
* 根據特定的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("響應狀態 " + retCode);
res = this.getStringFromInputStream(get.getResponseBodyAsStream());
LOG.info("響應結果" + res);
} catch ( Exception e ) {
LOG.error("該url路徑出錯,服務未開啟,請檢查", 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>();
// 設置分頁有信息
get.setRequestHeader("Range", "items=0-9");
JSONObject jo = new JSONObject();
LOG.debug("請求參數::" + 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("響應狀態 " + result);
res = this.getStringFromInputStream(get.getResponseBodyAsStream());
LOG.info("響應結果 " + res);
} catch ( Exception e ) {
LOG.error("該url路徑出錯,服務未開啟,請檢查", TEST_URL);
Assert.fail("連接失敗.");
} finally {
get.releaseConnection();
}
}
/**
* 測試刪除周知事項
*/
@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("發送delete請求刪除通知");
int retCode = client.executeMethod(delete);
LOG.info("響應狀態:" + retCode);
res = this.getStringFromInputStream(delete.getResponseBodyAsStream());
LOG.info("響應結果: " + res);
} catch ( Exception e ) {
LOG.error("測試錯誤", e);
Assert.fail("連接出錯");
} finally {
/* 釋放url的資源 */
delete.releaseConnection();
}
LOG.info(res);
}
}在添加一個正常的測試新增的方法:
@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年廣東省某某某某活動");
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("設置請求參數:" + jo.toString());
RequestEntity entity = new StringRequestEntity(
jo.toString(), "application/json", "UTF-8");
post.setRequestEntity(entity);
HttpClient httpclient = new HttpClient();
String res = "";
LOG.info("發送post請求");
int result = httpclient.executeMethod(post);
LOG.info(" 響應狀態:" + result);
res = this.getStringFromInputStream(post.getResponseBodyAsStream());
LOG.info("響應結果::" + res);
Assert.assertTrue(res.contains("增加值班表"));
} catch (Exception e) {
LOG.error("測試錯誤", e);
Assert.fail("連接出錯");
} finally {
post.releaseConnection();
}
}關于java中JPA動態查詢語句的用法就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。