封装增删查改返回json结构

master
WuXianChaoPin 7 years ago
parent cc40427b45
commit 5d5cfaab10
  1. 50
      core/src/main/java/core/dao/BaseDao1.java
  2. 16
      core/src/main/java/core/service/BaseService.java
  3. 10
      core/src/main/java/core/util/DBAction.java
  4. 50
      db/src/main/java/db/model/AbstractModel.java
  5. 17
      db/src/main/java/db/model/JsonResult.java
  6. 30
      db/src/main/java/db/model/ToJson.java
  7. 17
      web/src/main/java/web/controller/BaseController.java
  8. 2
      web/src/main/java/web/controller/DataController.java
  9. 13
      web/src/test/java/SpringTest.java
  10. 57
      web/src/test/java/db/model/TaskModel.java
  11. 17
      web/src/test/java/web/controller/TestController.java

@ -6,9 +6,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@ -25,54 +23,6 @@ public class BaseDao1 extends HibernateTemplate{
}
public <T extends AbstractModel> T save(T entity) {
try {
super.save(entity);
}catch (DataAccessException e){
entity.setDataAccessException(e);
}
return entity;
}
public <T extends AbstractModel> T update(T entity){
try {
super.update(entity);
}catch (DataAccessException e){
entity.setDataAccessException(e);
}
return entity;
}
public <T extends AbstractModel> T get(T entity){
try{
entity=(T)(super.get(entity.getClass(),entity.primaryKey()));
}catch (DataAccessException e){
entity.setDataAccessException(e);
}
return entity;
}
public <T extends AbstractModel> T delete(T entity) {
T model = get(entity);
try {
if ( entity.getDataAccessException()!= null) {
super.delete(model);
}
} catch (DataAccessException e) {
entity.setDataAccessException(e);
}
return entity;
}
public <T extends AbstractModel> List<T> delete(List<T> entitys) {
List<T> result=new ArrayList<>();
for(T entity:entitys){
result.add(delete(entity));
}
return result;
}
}

@ -9,11 +9,8 @@ import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
import static core.util.DBAction.BD;
/**
* Created by reborn on 2017/7/28.
*/
@ -30,20 +27,21 @@ public class BaseService {
public<T extends AbstractModel> T curd(DBAction action, T command) {
switch (action) {
case C:
return baseDao1.save(command);
baseDao1.save(command);
case U:
return baseDao1.update(command);
baseDao1.update(command);
case R:
return baseDao1.get(command);
return baseDao1.get(command.getClass(), command.primaryKey()).cast();
case D:
return baseDao1.delete(command);
baseDao1.delete(command);
default:
throw new RuntimeException("非法操作:" + action);
}
}
public <T extends AbstractModel> List<T> find(T command, int firstResult, int maxResults){
return (List<T>) baseDao1.findByCriteria(command.getCriteria(),firstResult,maxResults);
public <T extends AbstractModel> List find(T command, int firstResult, int maxResults){
return baseDao1.findByCriteria(command.getCriteria(),firstResult,maxResults);
}

@ -11,15 +11,7 @@ public enum DBAction {
R("读取","Retrieve"),
D("删除","Delete"),
BC("批量创建","BatchCreate"),
BU("批量更新","BatchUpdate"),
BR("批量读取","BatchRetrieve"),
BD("批量删除","BatchDelete");
D("删除","Delete");
private String ch;

@ -15,57 +15,17 @@ import java.io.Serializable;
* Created by reborn on 2017/8/3.
*/
public abstract class AbstractModel {
protected Logger log=LogManager.getLogger();
public abstract class AbstractModel{
public abstract Serializable primaryKey();
public abstract String tableNote();
private DataAccessException dataAccessException;
private static ObjectMapper objectMapper=new ObjectMapper();
static {
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
private Serializable[] checkeds;
private DetachedCriteria criteria;
public Serializable[] getCheckeds() {
return checkeds;
}
public void setCheckeds(Serializable[] checkeds) {
this.checkeds = checkeds;
}
public DataAccessException getDataAccessException() {
return dataAccessException;
}
public void setDataAccessException(DataAccessException dataAccessException) {
this.dataAccessException = dataAccessException;
}
public DetachedCriteria getCriteria() {
return criteria;
}
public void setCriteria(DetachedCriteria criteria) {
this.criteria = criteria;
return DetachedCriteria.forClass(this.getClass());
}
@Override
public String toString() {
try {
return objectMapper.writeValueAsString(this);
} catch (JsonProcessingException e) {
log.info(e);
return super.toString();
}
@SuppressWarnings("unchecked")
public <T extends AbstractModel> T cast() throws ClassCastException{
return (T) this;
}
}

@ -0,0 +1,17 @@
package db.model;
public class JsonResult<T extends AbstractModel> extends ToJson{
private T data;
private JsonResult.type type;
public JsonResult(T data, JsonResult.type type) {
this.data = data;
this.type = type;
}
enum type{
success,
fail
}
}

@ -0,0 +1,30 @@
package db.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ToJson {
protected Logger log=LogManager.getLogger();
private static ObjectMapper objectMapper=new ObjectMapper();
protected void mapperConfig(){
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
@Override
public String toString() {
try {
return objectMapper.writeValueAsString(this);
} catch (JsonProcessingException e) {
log.info(e);
return super.toString();
}
}
}

@ -3,6 +3,7 @@ package web.controller;
import core.service.BaseService;
import core.util.DBAction;
import db.model.AbstractModel;
import db.model.JsonResult;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.ModelAttribute;
@ -11,6 +12,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
/**
@ -24,19 +26,26 @@ public abstract class BaseController<T extends AbstractModel>{
@ResponseBody
@RequestMapping(value = "{action}", produces = "application/json;charset=UTF-8")
public <T extends AbstractModel> T curd(@PathVariable DBAction action,T model) {
public <T extends AbstractModel> JsonResult curd(@PathVariable DBAction action, T model) {
log.info(model.tableNote()+ "进行" + action.getCh() + "操作请求");
return baseService.curd(action, model);
if(checkAction(action)) {
model=baseService.curd(action, model);
}else{
// model.setException(new Exception(model.tableNote()+"不允许" + action.getCh()+"操作"));
}
return null;
}
@ResponseBody
@RequestMapping(value = "batch/{action}", produces = "application/json;charset=UTF-8")
public <T extends AbstractModel> List<T> find(@PathVariable DBAction action,T queryCommand,Integer firstResult,Integer maxResults){
if(action.equals(DBAction.BR)) {
log.info(queryCommand.tableNote()+ "进行批量" + action.getCh() + "操作请求");
if(checkAction(action)) {
return baseService.find(queryCommand, firstResult, maxResults);
}else{
throw new RuntimeException("非法操作:" + action);
// queryCommand.setException(new Exception(queryCommand.tableNote()+"不允许批量" + action.getCh()+"操作"));
}
return Arrays.asList(queryCommand);
}

@ -30,6 +30,6 @@ public class DataController extends BaseController<DataModel> {
@Override
public boolean checkAction(DBAction action) {
return !EnumSet.of(DBAction.D,DBAction.BD).contains(action);
return !EnumSet.of(DBAction.D).contains(action);
}
}

@ -17,6 +17,7 @@ import org.hibernate.tool.schema.TargetType;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ -25,6 +26,7 @@ import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import web.config.AppConfig;
import web.config.SpringConfig;
import web.controller.DataController;
@ -46,22 +48,23 @@ public class SpringTest {
@Resource
private BaseDao1 baseDao1;
@Resource
private DataController dataController;
private MockMvc mockMvc;
@Autowired
WebApplicationContext wac;
@Before
public void setup(){
mockMvc = MockMvcBuilders.standaloneSetup(dataController).build();
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void test() throws Exception {
ResultActions resultActions = this.mockMvc.perform(MockMvcRequestBuilders.get("/data/R.do").param("cid", "103"));
ResultActions resultActions = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/R.do").param("id", "1"));
MvcResult mvcResult = resultActions.andReturn();
String result = mvcResult.getResponse().getContentAsString();
log.info("=====客户端获得反馈数据:" + result);
log.info("客户端获得反馈数据:\n" + result);
}
// @Test

@ -0,0 +1,57 @@
package db.model;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Objects;
@Entity
@Table(name = "task", schema = "bilibili", catalog = "")
public class TaskModel extends AbstractModel{
private int id;
private String api;
@Id
@Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Basic
@Column(name = "api")
public String getApi() {
return api;
}
public void setApi(String api) {
this.api = api;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TaskModel taskModel = (TaskModel) o;
return id == taskModel.id &&
Objects.equals(api, taskModel.api);
}
@Override
public int hashCode() {
return Objects.hash(id, api);
}
@Override
public Serializable primaryKey() {
return getId();
}
@Override
public String tableNote() {
return "测试表";
}
}

@ -0,0 +1,17 @@
package web.controller;
import core.util.DBAction;
import db.model.TaskModel;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/test")
public class TestController extends BaseController<TaskModel>{
@Override
public boolean checkAction(DBAction action) {
return false;
}
}
Loading…
Cancel
Save