接下来我来编写业务代码
这么多的业务代码难道要自己编写吗?其实这些常用的逻辑完全可以使用代码生成器http://www.gaozz.club/一键生成N多张表基础代码及前端页面代码。
建表
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
`name` varchar(50) DEFAULT NULL COMMENT '姓名',
`birthday` date DEFAULT NULL COMMENT '生日',
`gender` tinyint(4) DEFAULT NULL COMMENT '性别',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8 COMMENT='用户';
-- ----------------------------
-- Records of sys_user
-- ----------------------------
INSERT INTO `sys_user` VALUES ('1', 'gzz', '2018-07-13', '1');
INSERT INTO `sys_user` VALUES ('2', 'gzz', '2018-07-13', '1');
INSERT INTO `sys_user` VALUES ('3', 'gzz', '2018-07-13', '1');
INSERT INTO `sys_user` VALUES ('4', 'gzz', '2018-07-13', '1');
INSERT INTO `sys_user` VALUES ('5', 'gzz', '2018-07-13', '1');
INSERT INTO `sys_user` VALUES ('6', 'gzz', '2018-07-13', '1');
INSERT INTO `sys_user` VALUES ('7', 'gzz', '2018-07-13', '1');
INSERT INTO `sys_user` VALUES ('8', 'gzz', '2018-07-13', '1');
INSERT INTO `sys_user` VALUES ('9', 'gzz', '2018-07-13', '1');
INSERT INTO `sys_user` VALUES ('10', 'gzz', '2018-07-13', '1');
INSERT INTO `sys_user` VALUES ('11', 'gzz', '2018-07-13', '1');
INSERT INTO `sys_user` VALUES ('12', 'gzz', '2018-07-13', '1');
INSERT INTO `sys_user` VALUES ('13', 'gzz', '2018-07-13', '1');
INSERT INTO `sys_user` VALUES ('14', 'gzz', '2018-07-13', '1');
User.java
package com.dl.notebook.sys.user;
import java.util.Date;
import lombok.Getter;
import lombok.Setter;
/**
* @类说明:用户实体类
* @author http://www.gaozz.club
* @date:2018-07-13 10:17:27
**/
@Setter
@Getter
public class User {
//数据库中的字段
private Long id;// 主键
private String name;// 姓名
//@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date birthday;// 生日
private Byte gender;// 性别
//此处可添加查询显示辅助字段
}
UserCond.java
package com.dl.notebook.sys.user;
import java.util.Date;
import java.util.List;
import com.dl.notebook.common.base.BaseCondition;
import lombok.Getter;
import lombok.Setter;
/**
* @类说明:用户查询条件实体类
* @author http://www.gaozz.club
* @date:2018-07-13 10:17:27
**/
@Setter
@Getter
public class UserCond extends BaseCondition {
/**
* @方法说明:拼加自定义条件
**/
@Override
public void addCondition() {
add(id, "AND t.id = ?");
add(name, "AND t.name LIKE ?", 3);
add(birthday, "AND t.birthday = ?");
add(gender, "AND t.gender = ?");
add(ids, "AND t.id IN ");
}
// 查询条件,把不用的条件清理掉
private Long id;// 主键
private String name;// 姓名
private Date birthday;// 生日
private Byte gender;// 性别
private List ids;// 主键列表
}
UserDao.java
package com.dl.notebook.sys.user;
import java.util.List;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Repository;
import com.dl.notebook.common.base.BaseDao;
import com.dl.notebook.common.base.Page;
import com.dl.notebook.common.base.SqlUtil;
/**
* @类说明:用户数据访问层
* @author http://www.gaozz.club
* @date:2018-07-13 10:17:27
**/
@Repository
public class UserDao extends BaseDao {
private StringBuilder select = new StringBuilder();
private StringBuilder insert = new StringBuilder();
/**
* @方法说明:构造方法,用于拼加SQL及初始化工作
**/
public UserDao() {
select.append("SELECT t.id,t.name,t.birthday,t.gender");
select.append(" FROM sys_user t WHERE 1=1");
insert.append("INSERT INTO sys_user (name,birthday,gender)");
insert.append(" VALUES (:name,:birthday,:gender)");
}
/**
* @方法说明:新增用户记录
**/
public int save(User vo) {
StringBuilder sql = new StringBuilder();
sql.append("INSERT INTO sys_user (id,name,birthday,gender)");
sql.append(" VALUES (?,?,?,?) ");
Object[] params = { vo.getId(), vo.getName(), vo.getBirthday(), vo.getGender() };
logger.info(SqlUtil.showSql(sql.toString(), params));// 显示SQL语句
return jdbcTemplate.update(sql.toString(), params);
}
/**
* @方法说明:新增用户记录并返回自增涨主键值
**/
public long saveReturnPK(User vo) {
return saveKey(vo, insert.toString(), "id");
}
/**
* @方法说明:批量插入用户记录
**/
public int[] insertBatch(List list) {
return batchOperate(list, insert.toString());
}
/**
* @方法说明:物理删除用户记录(多条)
**/
public int delete(Long ids[]) {
String sql = "DELETE FROM sys_user WHERE id" + SqlUtil.ArrayToIn(ids);
return jdbcTemplate.update(sql);
}
/**
* @方法说明:更新用户记录
**/
public int update(User vo) {
StringBuilder sql = new StringBuilder();
sql.append("UPDATE sys_user SET name=?,birthday=?,gender=?");
sql.append(" WHERE id=? ");
Object[] params = { vo.getName(), vo.getBirthday(), vo.getGender(), vo.getId() };
return jdbcTemplate.update(sql.toString(), params);
}
/**
* @方法说明:按条件查询分页用户列表
**/
public Page queryPage(UserCond cond) {
StringBuilder sb = new StringBuilder(select);
sb.append(cond.getCondition());
// sb.append(cond.getOrderSql());//增加排序子句;
logger.info(SqlUtil.showSql(sb.toString(), cond.getArray()));// 显示SQL语句
return queryPage(sb.toString(), cond, User.class);
}
/**
* @方法说明:按条件查询不分页用户列表
**/
public List queryList(UserCond cond) {
StringBuilder sb = new StringBuilder(select);
sb.append(cond.getCondition());
// sb.append(" ORDER BY operate_time DESC");
logger.info(SqlUtil.showSql(sb.toString(), cond.getArray()));// 显示SQL语句
return jdbcTemplate.query(sb.toString(), cond.getArray(), new BeanPropertyRowMapper<>(User.class));
}
/**
* @方法说明:按ID查找单个用户实体
**/
public User findById(Long id) {
StringBuilder sb = new StringBuilder(select);
sb.append(" AND t.id=?");
return jdbcTemplate.queryForObject(sb.toString(), new Object[] { id }, new BeanPropertyRowMapper<>(User.class));
}
/**
* @方法说明:按条件查询用户记录个数
**/
public long queryCount(UserCond cond) {
String countSql = "SELECT COUNT(1) FROM sys_user t WHERE 1=1" + cond.getCondition();
return jdbcTemplate.queryForObject(countSql, cond.getArray(), Long.class);
}
/**
* @方法说明:逻辑删除用户记录(多条)
**/
public int deleteLogic(Long ids[]) {
String sql = "UPDATE sys_user SET delete_remark=1 WHERE id" + SqlUtil.ArrayToIn(ids);
return jdbcTemplate.update(sql);
}
}
UserService.java
package com.dl.notebook.sys.user;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dl.notebook.common.base.Page;
/**
* @类说明:用户数据逻辑层
* @author http://www.gaozz.club
* @date:2018-07-13 10:17:27
**/
@Service
public class UserService {
@SuppressWarnings("unused")
private Log logger = LogFactory.getLog(getClass());
@Autowired
private UserDao dao; // 注入用户数据访问层
/**
* @方法说明:新增用户记录
**/
@Transactional
public int save(User user) {
return dao.save(user);
}
/**
* @方法说明:删除用户记录(多条)
**/
public int delete(Long ids[]) {
// return dao.deleteLogic(ids);//逻辑删除
return dao.delete(ids);// 物理删除
}
/**
* @方法说明:更新用户记录
**/
@Transactional
public int update(User user) {
return dao.update(user);
}
/**
* @方法说明:按条件查询分页用户列表
**/
public Page queryPage(UserCond cond) {
return dao.queryPage(cond);
}
/**
* @方法说明:按条件查询不分页用户列表(使用范型)
**/
public List queryList(UserCond cond) {
return dao.queryList(cond);
}
/**
* @方法说明:按ID查找单个用户记录
**/
public User findById(Long id) {
return dao.findById(id);
}
/**
* @方法说明:按条件查询用户记录个数
**/
public long queryCount(UserCond cond) {
return dao.queryCount(cond);
}
}
UserController.java
package com.dl.notebook.sys.user;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.dl.notebook.common.base.Page;
/**
* @类说明:用户数据控制器层
* @author http://www.gaozz.club
* @date:2018-07-13 10:17:27
**/
@RestController
@RequestMapping("user")
public class UserController {
@SuppressWarnings("unused")
private final Log logger = LogFactory.getLog(getClass());
@Autowired
private UserService service; // 注入用户数据逻辑层
/**
* @方法说明:新增用户记录
**/
@PostMapping("save")
public int save(@RequestBody User user) {
return service.save(user);
}
/**
* @方法说明:删除用户记录(多条)
**/
@PostMapping("delete")
public int delete(@RequestParam("ids[]") Long ids[]) {
return service.delete(ids);
}
/**
* @方法说明:修改用户记录
**/
@PostMapping("update")
public int update(@RequestBody User user) {
return service.update(user);
}
/**
* @方法说明:按条件查询分页用户列表
**/
@PostMapping("queryPage")
public Page queryPage(@RequestBody UserCond cond) {
return service.queryPage(cond);
}
/**
* @方法说明:按条件查询不分页用户列表
**/
@PostMapping("queryList")
public List queryList(@RequestBody UserCond cond) {
return service.queryList(cond);
}
/**
* @方法说明:按主键查单个用户记录
**/
@PostMapping("findById")
public User findById(@RequestParam("id") Long id) {
return service.findById(id);
}
/**
* @方法说明:按条件查询用户记录个数
**/
@PostMapping("queryCount")
public long queryCount(@RequestBody UserCond cond) {
return service.queryCount(cond);
}
}
重点在这儿
package com.dl.notebook;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.Date;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.dl.notebook.sys.user.User;
import com.dl.notebook.sys.user.UserCond;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserTests {
private static final Log logger = LogFactory.getLog(UserTests.class);
private ObjectMapper mapper = new ObjectMapper();
private MockMvc mockMvc; // 模拟MVC对象,通过MockMvcBuilders.webAppContextSetup(this.wac).build()初始化。
@Autowired
private WebApplicationContext wac; // 注入WebApplicationContext
@Before // 在测试开始前初始化工作
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void save() throws Exception {
User user = new User();
user.setBirthday(new Date());
user.setGender((byte) 1);
user.setName("gzz");
MvcResult result = mockMvc.perform(post("/user/save").contentType(MediaType.APPLICATION_JSON).content(mapper.writeValueAsString(user))).andExpect(status().isOk())// 模拟向testRest发送get请求
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))// 预期返回值的媒体类型text/plain;charset=UTF-8
.andReturn();// 返回执行请求的结果
logger.info(result.getResponse().getContentAsString());
}
@Test
public void queryList() throws Exception {
UserCond cond = new UserCond();
cond.setGender((byte) 1);
MvcResult result = mockMvc.perform(post("/user/queryList").contentType(MediaType.APPLICATION_JSON).content(mapper.writeValueAsString(cond))).andExpect(status().isOk())// 模拟向testRest发送get请求
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))// 预期返回值的媒体类型text/plain;charset=UTF-8
.andReturn();// 返回执行请求的结果
logger.info(result.getResponse().getContentAsString());
}
@Test
public void queryPage() throws Exception {
UserCond cond = new UserCond();
cond.setGender((byte) 1);
MvcResult result = mockMvc.perform(post("/user/queryPage").contentType(MediaType.APPLICATION_JSON).content(mapper.writeValueAsString(cond))).andExpect(status().isOk())// 模拟向testRest发送get请求
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))// 预期返回值的媒体类型text/plain;charset=UTF-8
.andReturn();// 返回执行请求的结果
logger.info(result.getResponse().getContentAsString());
}
}
运行测试类查看结果:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.6.RELEASE)
2018-07-13 13:33:57,471[StartupInfoLogger.java:48][INFO]:Starting UserTests on DESKTOP-T6F8K74 with PID 7492 (started by gzz in D:\github\springbootjdbc)
2018-07-13 13:33:57,479[SpringApplication.java:593][INFO]:No active profile set, falling back to default profiles: default
2018-07-13 13:33:57,652[Version.java:30][INFO]:HV000001: Hibernate Validator 5.3.5.Final
2018-07-13 13:33:59,165[StartupInfoLogger.java:57][INFO]:Started UserTests in 1.92 seconds (JVM running for 2.582)
2018-07-13 13:33:59,381[UserDao.java:96][INFO]:SELECT t.id,t.name,t.birthday,t.gender FROM sys_user t WHERE 1=1 AND t.gender = 1
2018-07-13 13:33:59,651[UserTests.java:64][INFO]:[{"id":1,"name":"gzz","birthday":1531411200000,"gender":1},{"id":2,"name":"gzz","birthday":1531411200000,"gender":1},{"id":3,"name":"gzz","birthday":1531411200000,"gender":1},{"id":4,"name":"gzz","birthday":1531411200000,"gender":1},{"id":5,"name":"gzz","birthday":1531411200000,"gender":1},{"id":6,"name":"gzz","birthday":1531411200000,"gender":1},{"id":7,"name":"gzz","birthday":1531411200000,"gender":1},{"id":8,"name":"gzz","birthday":1531411200000,"gender":1},{"id":9,"name":"gzz","birthday":1531411200000,"gender":1},{"id":10,"name":"gzz","birthday":1531411200000,"gender":1},{"id":11,"name":"gzz","birthday":1531411200000,"gender":1},{"id":12,"name":"gzz","birthday":1531411200000,"gender":1},{"id":13,"name":"gzz","birthday":1531411200000,"gender":1},{"id":14,"name":"gzz","birthday":1531411200000,"gender":1},{"id":15,"name":"gzz","birthday":1531411200000,"gender":1}]
2018-07-13 13:33:59,660[UserDao.java:85][INFO]:SELECT t.id,t.name,t.birthday,t.gender FROM sys_user t WHERE 1=1 AND t.gender = 1
2018-07-13 13:33:59,669[UserTests.java:75][INFO]:{"dataList":[{"id":1,"name":"gzz","birthday":1531411200000,"gender":1},{"id":2,"name":"gzz","birthday":1531411200000,"gender":1},{"id":3,"name":"gzz","birthday":1531411200000,"gender":1},{"id":4,"name":"gzz","birthday":1531411200000,"gender":1},{"id":5,"name":"gzz","birthday":1531411200000,"gender":1},{"id":6,"name":"gzz","birthday":1531411200000,"gender":1},{"id":7,"name":"gzz","birthday":1531411200000,"gender":1},{"id":8,"name":"gzz","birthday":1531411200000,"gender":1},{"id":9,"name":"gzz","birthday":1531411200000,"gender":1},{"id":10,"name":"gzz","birthday":1531411200000,"gender":1}],"pageSize":10,"rowCount":15,"curpage":0,"pageCount":2}
2018-07-13 13:33:59,680[UserDao.java:41][INFO]:INSERT INTO sys_user (id,name,birthday,gender) VALUES (null,'gzz','2018-07-13 13:33:59',1)
2018-07-13 13:33:59,691[UserTests.java:53][INFO]:1
至此我们就完成了一个springboot+springjdbc及测MOCK测试的完整例子。