使用SSM和layui做了一个汽车租赁后台管理系统,功能还没有完善,先发出来再慢慢完善更新
包结构:
项目后期又用Maven整合了一下,jar包太多,把pom贴出来好了
pom.xml
<properties><aspectjweaver.version>1.9.4</aspectjweaver.version><classmate.version>1.3.4</classmate.version><commons-fileupload.version>1.3.1</commons-fileupload.version><commons-lang3.version>3.9</commons-lang3.version><commons-logging.version>1.2</commons-logging.version><druid.version>1.0.28</druid.version><fastjson.version>1.2.62</fastjson.version><hibernate-validator.version>5.1.1.Final</hibernate-validator.version><hutool-all.version>4.6.10</hutool-all.version><jackson-annotations.version>2.9.9</jackson-annotations.version><jackson-core.version>2.9.9</jackson-core.version><jackson-databind.version>2.9.9</jackson-databind.version><jsqlparser.version>1.3</jsqlparser.version><jstl.version>1.2</jstl.version><log4j.version>1.2.17</log4j.version><mybatis.version>3.5.0</mybatis.version><mybatis-spring.version>1.3.3</mybatis-spring.version><mysql-connector-java.version>5.1.47</mysql-connector-java.version><pagehelper.version>5.1.8</pagehelper.version><spring.version>5.2.0.RELEASE</spring.version><standard.version>1.1.2</standard.version><javax.servlet-api.version>3.1.0</javax.servlet-api.version><jsp-api.version>2.2</jsp-api.version></properties><dependencies><!-- /artifact/org.aspectj/aspectjweaver --><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>${aspectjweaver.version}</version></dependency><!-- /artifact/com.fasterxml/classmate --><dependency><groupId>com.fasterxml</groupId><artifactId>classmate</artifactId><version>${classmate.version}</version></dependency><!-- /artifact/commons-fileupload/commons-fileupload --><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>${commons-fileupload.version}</version></dependency><!-- /artifact/mons/commons-lang3 --><dependency><groupId>mons</groupId><artifactId>commons-lang3</artifactId><version>${commons-lang3.version}</version></dependency><!-- /artifact/commons-logging/commons-logging --><dependency><groupId>commons-logging</groupId><artifactId>commons-logging</artifactId><version>${commons-logging.version}</version></dependency><!-- /artifact/com.alibaba/druid --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>${druid.version}</version></dependency><!-- /artifact/com.alibaba/fastjson --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>${fastjson.version}</version></dependency><!-- /artifact/org.hibernate/hibernate-validator --><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-validator</artifactId><version>${hibernate-validator.version}</version></dependency><!-- /artifact/cn.hutool/hutool-all --><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>${hutool-all.version}</version></dependency><!-- /artifact/com.fasterxml.jackson.core/jackson-annotations --><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>${jackson-annotations.version}</version></dependency><!-- /artifact/com.fasterxml.jackson.core/jackson-core --><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>${jackson-core.version}</version></dependency><!-- /artifact/com.fasterxml.jackson.core/jackson-databind --><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>${jackson-databind.version}</version></dependency><!-- /artifact/com.github.jsqlparser/jsqlparser --><dependency><groupId>com.github.jsqlparser</groupId><artifactId>jsqlparser</artifactId><version>${jsqlparser.version}</version></dependency><!-- /artifact/javax.servlet/jstl --><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>${jstl.version}</version></dependency><!-- /artifact/log4j/log4j --><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>${log4j.version}</version></dependency><!-- /artifact/org.mybatis/mybatis --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>${mybatis.version}</version></dependency><!-- /artifact/org.mybatis/mybatis-spring --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>${mybatis-spring.version}</version></dependency><!-- /artifact/mysql/mysql-connector-java --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>${mysql-connector-java.version}</version></dependency><!-- /artifact/com.github.pagehelper/pagehelper --><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper</artifactId><version>${pagehelper.version}</version></dependency><!-- /artifact/org.springframework/spring-aspects --><dependency><groupId>org.springframework</groupId><artifactId>spring-aspects</artifactId><version>${spring.version}</version></dependency><!-- /artifact/org.springframework/spring-context-support --><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><version>${spring.version}</version></dependency><!-- /artifact/org.springframework/spring-oxm --><dependency><groupId>org.springframework</groupId><artifactId>spring-oxm</artifactId><version>${spring.version}</version></dependency><!-- /artifact/org.springframework/spring-webmvc --><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>${spring.version}</version></dependency><!-- /artifact/taglibs/standard --><dependency><groupId>taglibs</groupId><artifactId>standard</artifactId><version>${standard.version}</version></dependency><!-- /artifact/javax.servlet/javax.servlet-api --><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>${javax.servlet-api.version}</version><scope>provided</scope></dependency><!-- /artifact/javax.servlet.jsp/jsp-api --><dependency><groupId>javax.servlet.jsp</groupId><artifactId>jsp-api</artifactId><version>${jsp-api.version}</version><scope>provided</scope></dependency></dependencies>
抽取出了使用较多的增删改查方法,封装了一套base公共类
其中,BaseForm和BaseQuery都负责接收前端ajax请求传过来的参数,不同的是,前端的添加、修改操作,用Form接收,查询操作用Query接收。BaseVO作为mybatis的返回类型。所有表的Form,Query,VO,都继承自他们,方便面向父类编程
细节如下:
public class BaseForm {}
查询操作涉及到分页查询,由于使用的是layui框架,所以把layui中分页的两个参数封装了一下
public class BaseQuery {/*** 页码 */private Integer page;/*** 每页数据条数*/private Integer limit;public Integer getPage() {return page;}public void setPage(Integer page) {this.page = page;}public Integer getLimit() {return limit;}public void setLimit(Integer limit) {this.limit = limit;}
public class BaseVO {}
BaseMapper
public interface BaseMapper<F,V> {/*** 添加* @param form* @return*/int insert(F form);/*** 根据id删除* @param id* @return*/int delete(@Param("id") Integer id);/*** 根据id查询单个* @param id* @return*/V selectOne(@Param("id") Integer id);/*** 查询全部* @param query* @return*/List<V> selectList(BaseQuery query);/*** 更新* @param form* @return*/int update(F form);}
IBaseService
public interface IBaseService<F,V> {Result add(F form);Result delete(Integer id);Result queryOne(Integer id);Result queryList(BaseQuery query);Result queryPage(BaseQuery query);Result modify(F form);}
BaseServiceImpl
public class BaseServiceImpl<F, V> implements IBaseService<F, V> {BaseMapper<F, V> baseMapper;public BaseServiceImpl(BaseMapper<F, V> baseMapper) {this.baseMapper = baseMapper;}@Overridepublic Result add(F form) {int row = baseMapper.insert(form);if(row>0) {return new Result();}return new Result(CodeMsg.SYS_ADD_ERROR);}@Overridepublic Result delete(Integer id) {// TODO Auto-generated method stubreturn null;}@Overridepublic Result queryOne(Integer id) {// TODO Auto-generated method stubreturn null;}@Overridepublic Result queryList(BaseQuery query) {List<V> list = baseMapper.selectList(query);if(null == list) {return new Result(CodeMsg.SYS_QUERY_ERROR);}return new Result(list);}@Overridepublic Result queryPage(BaseQuery query) {Page<Object> page = PageHelper.startPage(query.getPage(), query.getLimit());baseMapper.selectList(query);PageInfo pageInfo = new PageInfo();pageInfo.setCount(page.getTotal());pageInfo.setLimit(page.getPageSize());pageInfo.setPage(page.getPageNum());pageInfo.setData(page.getResult());return new Result(pageInfo);}@Overridepublic Result modify(F form) {int row = baseMapper.update(form);if(row > 0){return new Result();}return new Result(CodeMsg.SYS_UPDATE_ERROR);}}
上面的类就是我封装的最主要的一部分公共类,还有一些其他的,贴在下面
CodeMsg枚举类,前端请求处理完成之后,和数据一起返回给前端,方便前端提示
public enum CodeMsg {SUCCESS(200,"OK"),ERROR(2002001,"下雨了,程序员正在路上"),SYS_QUERY_ERROR(4001001,"查询失败"),SYS_ADD_ERROR(4002002,"添加失败"),SYS_DELETE_ERROR(400,"删除失败"),SYS_UPDATE_ERROR(400,"修改失败"),SYS_USER_VERIF_CODE_ERROR(4002001,"验证码错误,请重新输入"),SYS_USER_LOGIN_NAME_EMPTY_ERROR(4002002,"用户名不能为空"),SYS_USER_LOGIN_PASSWORD_EMPTY_ERROR(400,"用户密码不能为空"),SYS_USER_LOGIN_ERROR(400,"用户密码不正确"),SYS_USER_ADD_ERROR(400,"添加用户失败"),SYS_USER_DELETE_ERROR(400,"删除用户失败"),SYS_USER_RESET_PASSWORD_ERROR(400,"重置密码失败"), BUSI_RENT_IDCARD_ERROR(400,"用户身份证不存在"),/** 车辆管理*/BUSI_CAR_NUM_EXIST_ERROR(4003001,"车牌号已存在"),BUSI_CAR_IMG_SAVE_ERROR(4003002,"汽车图片保存失败"), BUSI_RENT_CARNUM_ERROR(4003003,"车牌号错误"), BUSI_CAR_RENTED_ERROR(4003004,"车辆出租状态异常"), BUSI_CAR_RENT_ERROR(4003005,"修改出租状态失败"),/*** 租车*/BUSI_CAR_RENT_TIME_ERROR(4004001,"租车、还车时间异常"),BUSI_RENT_RENTNO_ERROR(4004002,"出租单号异常"),BUSI_RENT_FLAG_RETURNED_ERROR(4004003,"该订单状态为已归还"),/*** 检查*/BUSI_INSERT_CHECK_ERROR(4005001,"生成检查记录失败"),//菜单模块SYS_MENU_PARENTID_ERROR(4007001,"父菜单不存在"),//角色模块SYS_ROLE_NOT_EXIST_ERROR(4008001,"角色不存在");public Integer code;public String msg;public Integer getCode() {return code;}public void setCode(Integer code) {this.code = code;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}private CodeMsg(Integer code, String msg) {this.code = code;this.msg = msg;}}
Constant常量类,封装了一些常用的字符、数字
public class Constant {/*** 业务正常响应码*/public static final String CODE = "200";/*** 参数校验错误编码*/public static final Integer PARAM_CHECK_FAILD_CODE = 4001000;/*** 业务正常消息*/public static final String MESSAGE = "SUCCESS";/*** 作用域中当前用户key*/public static final String CURRENT_USER = "user";/*** 存储在 ServletContexty 作用域中 key web URL根路径*/public static final String WEB_URL = "cxt";/*** 存储在Session中验证码的key*/public static final String VERIFI_CODE = "verifiCode";/*** 默认密码*/public static final String DEFAULT_PASSWORD = "123456";/*** 超级管理员*/public static final Integer SYS_USER_TYPE_ADMIN = 1;/*** 系统用户*/public static final Integer SYS_USER_TYPE_NOMAL = 2;/*** 时间格式*/public static final String Y_M_D_H_M_S = "yyyy-MM-dd HH:mm:ss";/*** 时间格式:yyyyMMddHHmmssSS*/public static final String YMDHMSSS = "yyyyMMddHHmmssSS";/*** 文件存储的目录*/public static final String FILE_FOLDER = "resources/carImg";/*** 未出租*/public static final Integer CAR_NOT_RENT = 1;/*** 车辆已出租*/public static final Integer CAR_RENTED = 2;/*** 车辆未归还*/public static final Integer CAR_NOT_RETURN = 1;/*** 车辆已归还*/public static final Integer CAR_RETURNED = 2;/*** 出租单号前缀*/public static final String CAR_RENT_PRE = "RENT";/*** 检查单号前缀*/public static final String CAR_CHECK_PRE = "CHECK";}
PageInfo类,如果需要分页查询,就把这个类作为数据,封装到Result中,返回给前端
public class PageInfo {private Integer page;//页码private Integer limit;//每页数据条数private long count;// 总条数private List<Object> data;// 具体的数据public PageInfo() {}public PageInfo( Integer count, List<Object> list) {this.count = count;this.data = list;}public PageInfo(Integer page, Integer limit, long count, List<Object> list) {super();this.page = page;this.limit = limit;this.count = count;this.data = list;}public Integer getPage() {return page;}public void setPage(Integer page) {this.page = page;}public Integer getLimit() {return limit;}public void setLimit(Integer limit) {this.limit = limit;}public long getCount() {return count;}public void setCount(long count) {this.count = count;}public List<Object> getData() {return data;}public void setData(List<Object> data) {this.data = data;}}
Result类,这个类是最终以json格式返回给前端的,里面封装了前端需要的code(状态码) msg(提示信息) data(数据)
public class Result {Integer code;String msg;Object data;public Integer getCode() {return code;}public void setCode(Integer code) {this.code = code;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}public Object getData() {return data;}public void setData(Object data) {this.data = data;}/*** 操作成功,没有返回数据*/public Result() {this.code = CodeMsg.SUCCESS.code;this.msg = CodeMsg.SUCCESS.msg;}/*** 操作失败* @param codeMsg*/public Result(CodeMsg codeMsg) {this.msg = codeMsg.getMsg();this.code = codeMsg.getCode();}/***操作成功,有数据返回* @param data*/public Result(Object data) {this.data = data;this.code = CodeMsg.SUCCESS.code;this.msg = CodeMsg.SUCCESS.msg;}public Result(String msg,Integer code) {this.msg = msg;this.code = code;}}
PageController类,用于跳转页面,我的jsp是放在WEB-INF下的,需要controller帮助跳转
@Controller@RequestMapping("/page")public class PageController {/*** 用户列表* @return*/@RequestMapping("userList.do")public String userList() {return "sys/user/list.jsp";}@RequestMapping("carList.do")public String carList() {return "busi/car/list.jsp";}@RequestMapping("custList.do")public String custList() {return "busi/customer/custList.jsp";}@RequestMapping("rentList.do")public String rentList() {return "busi/rent/rentList.jsp";}@RequestMapping("checkList.do")public String checkList() {return "busi/check/checkList.jsp";}@RequestMapping("menuList.do")public String menuList() {return "sys/menu/menuList.jsp";}}
VerifiCodeController类,验证码生成类,我用的hutool的工具类,login页面加载时就会请求到这个类
@Controller@RequestMapping("/verifi")public class VerifiCodeController {@RequestMapping("/code.do")public void code(HttpServletResponse resp) {//创建验证码LineCaptcha captcha = CaptchaUtil.createLineCaptcha(200, 100, 4, 1);String code = captcha.getCode();WebUtil.setCurrentVerifiCode(code);try {captcha.write(resp.getOutputStream());} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
BusiException自定义异常类,用于处理业务逻辑中产生的异常
public class BusiException extends RuntimeException{private static final long serialVersionUID = -4331357754088686184L;/*** 自定义的异常编码*/private Integer code;/*** 自定义的异常信息*/private String msg;public BusiException(Integer code, String msg) {this.code = code;this.msg = msg;}/*** @Title:BusiException* @Description:使用声明的异常信息* @param codeMsg*/public BusiException(CodeMsg codeMsg) {this.code = codeMsg.code;this.msg = codeMsg.msg;}public Integer getCode() {return code;}public void setCode(Integer code) {this.code = code;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}}
GlobalExceptionHandler 全局异常处理类,程序产生的所有一场都会经过这个类的处理,然后返回相应的消息给前端页面
@ControllerAdvicepublic class GlobalExceptionHandler {@ExceptionHandler(value = Exception.class)@ResponseBodypublic Result busiExceptionHandler(HttpServletRequest req,Exception exception) {if (exception instanceof BusiException) {System.out.println("全局异常处理......");BusiException busiException = (BusiException) exception;System.out.println(busiException.getMessage());return new Result(busiException.getMsg(),busiException.getCode());}exception.printStackTrace();return new Result(CodeMsg.ERROR);}}
ApplicationListener 监听器,在程序启动时,加载我的url路径,放到context作用域中,前端用el表达式获取,作为前端页面静态资源的前缀
@WebListenerpublic class ApplicationListener implements ServletContextListener {@Overridepublic void contextDestroyed(ServletContextEvent sce) {}@Overridepublic void contextInitialized(ServletContextEvent sce) {//获取 contextServletContext context = sce.getServletContext();context.setAttribute(Constant.WEB_URL, PropertiesUtil.getProperty("WEB_URL", "web"));}}
PropertiesUtil 工具类,用于读取properties配置文件
public class PropertiesUtil {private PropertiesUtil() {}public static String getProperty(String key,String properties) {InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream(properties+".properties");Properties prop = new Properties();try {prop.load(in);} catch (IOException e) {e.printStackTrace();}return prop.getProperty(key);}}
WebUtil 工具类 封装了一些web相关的常用方法
public class WebUtil {private WebUtil() {}/***获取当前HttpServletRequest*/public static HttpServletRequest getRequest() {ServletRequestAttributes req = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();return req.getRequest();}/***获取当前HttpSession*/public static HttpSession getSession() {return getRequest().getSession();}/***获取当前ServletContext */public static ServletContext getServletContext() {return ContextLoader.getCurrentWebApplicationContext().getServletContext();}/***获取当前产生的验证码*/public static String getCurrentVerifiCode() {Object obj = getSession().getAttribute(Constant.VERIFI_CODE);return obj != null?obj.toString():null;}/***将验证码放入session*/public static void setCurrentVerifiCode(String verifiCode) {getSession().setAttribute(Constant.VERIFI_CODE,verifiCode);}/*** 将登陆用户放入Session*/public static <T> void setCurrentUser(T t) {getSession().setAttribute(Constant.CURRENT_USER, t);}/*** 获取当前登陆用户*/@SuppressWarnings("unchecked")public static <T> T getCurrentUser() {Object obj = getSession().getAttribute(Constant.CURRENT_USER);return obj != null?(T)obj:null;}
ValidatorUtil 数据校验工具类,用于执行新增、修改操作时,判断传入的数据是否合法
public class ValidatorUtil {private static Validator validator;static {validator = Validation.buildDefaultValidatorFactory().getValidator();}public static void validator(BaseForm baseForm) {Set<ConstraintViolation<BaseForm>> validate = validator.validate(baseForm);for (ConstraintViolation<BaseForm> constraintViolation : validate) {String message = constraintViolation.getMessage();throw new BusiException(Constant.PARAM_CHECK_FAILD_CODE,message);}}}
公共类和工具类贴完啦
表比较多,就只贴出一张car表的controller,service代码吧,其它表和它基本类似,都是按照相同的套路,
@RestController@RequestMapping("/car")public class BusiCarController {@AutowiredIBusiCarService carService;@RequestMapping("/list.do")@ResponseBodypublic Object list(BusiCarQuery query) {Result rs = carService.queryPage(query);return rs;}@RequestMapping("/addCar.do")@ResponseBodypublic Object addCar(MultipartFile carImg,BusiCarForm form) {//数据校验ValidatorUtil.validator(form);Result rs = carService.add(carImg, form);return rs;}@RequestMapping("/deleteCar.do")@ResponseBodypublic Object deleteCar(@RequestParam("carNum") List<String> carNums) {Result rs = carService.batchDeleteCar(carNums);return rs;}@RequestMapping("/updateCar.do")@ResponseBodypublic Object updateCar(MultipartFile carImg,BusiCarForm form) {//数据校验ValidatorUtil.validator(form);Result rs = carService.update(carImg, form);return rs;}@RequestMapping("/rentCar.do")@ResponseBodypublic Object rentCar(RentForm form) {ValidatorUtil.validator(form);Result rs = carService.rent(form);return rs;}}
public interface IBusiCarService extends IBaseService<BusiCarForm, BusiCarVO> {public Result batchDeleteCar(List<String> carNums);Result add(MultipartFile carImg, BusiCarForm form);Result update(MultipartFile carImg, BusiCarForm form);public Result rent( RentForm form);}
@Servicepublic class BusiCarServiceImpl extends BaseServiceImpl<BusiCarForm,BusiCarVO> implements IBusiCarService {@AutowiredBusiCarMapper<BusiCarForm, BusiCarVO> carMapper;@AutowiredBusiCustomerMapper<BusiCustomerForm, BusiCustomerVO> customerMapper;@Autowiredprivate BusRentsMapper<RentForm, BusiCarVO> busRentsMapper;public BusiCarServiceImpl(BusiCarMapper<BusiCarForm, BusiCarVO> carMapper) {super(carMapper);}@Overridepublic Result batchDeleteCar(List<String> carNums) {int rows = carMapper.batchDelete(carNums);if(rows>0) {return new Result();}return new Result(CodeMsg.SYS_DELETE_ERROR);}@Override@Transactionalpublic Result add(MultipartFile carImg, BusiCarForm form) {form.setIsRent(Constant.CAR_NOT_RENT);/*** 保存车辆数据* 1.校验车牌号是否已经被使用*/BusiCarQuery query = new BusiCarQuery();query.setCarNum(form.getCarNum());//校验车牌号List<BusiCarVO> vos = carMapper.selectList(query);if(!vos.isEmpty()) {return new Result(CodeMsg.BUSI_CAR_NUM_EXIST_ERROR);}//汽车图片存储的目录路径String realPath = WebUtil.getServletContext().getRealPath(Constant.FILE_FOLDER);//上传的文件的名称String originalFilename = carImg.getOriginalFilename();//获取文件后缀String suff = this.fileSuffix(originalFilename);// 产生文件名称 用于保存,String fileName = form.getCarNum()+suff;form.setImg(Constant.FILE_FOLDER+"/"+fileName);//更新车辆信息carMapper.insert(form);try {carImg.transferTo(new File(realPath+File.separator+fileName));} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();throw new BusiException(CodeMsg.BUSI_CAR_IMG_SAVE_ERROR);}return new Result();}private String fileSuffix(String fileName) {return fileName.substring(fileName.lastIndexOf("."));}@Override@Transactionalpublic Result update(MultipartFile carImg, BusiCarForm form) {//汽车图片存储的目录路径String realPath = WebUtil.getServletContext().getRealPath(Constant.FILE_FOLDER);//上传的文件的名称String originalFilename = carImg.getOriginalFilename();//获取文件后缀String suff = this.fileSuffix(originalFilename);// 产生文件名称 用于保存,String fileName = form.getCarNum()+suff;form.setImg(Constant.FILE_FOLDER+"/"+fileName);//更新车辆信息carMapper.update(form);//删除车辆之前的图片//String img = vos.get(0).getImg();try {//保存图片carImg.transferTo(new File(realPath+File.separator+fileName));//删除之前的图片//realPath = WebUtil.getServletContext().getRealPath(img);//File file = new File(realPath);//删除之前的文件//if(file.exists()) {//file.delete();//}} catch (Exception e) {e.printStackTrace();throw new BusiException(CodeMsg.BUSI_CAR_IMG_SAVE_ERROR);}return new Result();}@Transactional@Overridepublic Result rent(RentForm form) {//校验身份证号BusiCustomerQuery query = new BusiCustomerQuery();query.setIdCard(form.getIdCard());List<BusiCustomerVO> vos = customerMapper.selectList(query);if(vos.isEmpty()) {return new Result(CodeMsg.BUSI_RENT_IDCARD_ERROR);}//查询车辆状态BusiCarQuery carQuery = new BusiCarQuery();carQuery.setCarNum(form.getCarNum());List<BusiCarVO> cars = carMapper.selectList(carQuery);if(cars.isEmpty()) {return new Result(CodeMsg.BUSI_RENT_CARNUM_ERROR);}//校验是否出租if(cars.get(0).getIsRent() == Constant.CAR_RENTED) {return new Result(CodeMsg.BUSI_CAR_RENTED_ERROR);}//修改车辆出租状态int m = carMapper.updateRent(form.getCarNum(), Constant.CAR_RENTED,cars.get(0).getVersion());if(m == 0) {throw new BusiException(CodeMsg.BUSI_CAR_RENT_ERROR);}//创建出租单//创建出租单号String format = DateUtil.format(new Date(), Constant.YMDHMSSS);String rentNo = Constant.CAR_RENT_PRE+format+form.getCarNum();//设置出租单号form.setRentNo(rentNo);SysUserVO user = WebUtil.getCurrentUser();form.setUserId(user.getId());form.setCreateTime(DateUtil.format(new Date(), Constant.Y_M_D_H_M_S));//计算价格/*** 按小时计算 没有满24小时 算 24小时*///校验时间 比较还车时间 大于 租车时间long beginTimes = DateUtil.parse(form.getBeginTime(),Constant.Y_M_D_H_M_S).getTime();long returnTimes = DateUtil.parse(form.getReturnTime(),Constant.Y_M_D_H_M_S).getTime();if(beginTimes > returnTimes) {throw new BusiException(CodeMsg.BUSI_CAR_RENT_TIME_ERROR);}//计算价格double times = returnTimes - beginTimes;double time = Math.ceil(times/1000.0/60.0/60.0) ;if(time < 24) {form.setPrice(cars.get(0).getRentPrice());}else {// 总小时 * 每小时的租金 int money = (int) (time*(cars.get(0).getRentPrice() / 24));form.setPrice(money);}busRentsMapper.insert(form);return new Result();}
只用父类BaseMapper中的方法肯定是不够的,所以BusiCarMapper中又写了新的方法
public interface BusiCarMapper<F,V> extends BaseMapper<F,V> {public int batchDelete(@Param("carNums") List<String> carNums);public int updateRent(@Param("carNum")String carNum,@Param("rent")Integer rent,@Param("version")Integer version);}
spring和mybatis的配置文件就不贴啦,配置文件都一样,没啥花样。有问题欢迎评论留言