时间:2020-12-24 11:36:17 | 栏目:JAVA代码 | 点击:次
上图是查询列表的接口,get方式
上图是用户注册的接口,同样是get,post方式也很简单
开发工具:IntelliJ IDEA 2016.3.5
ORM框架:MyBatis
数据库:MySql
服务器:tomcat7.0
公司使用的的orm框架是Hibernate,使用起来感觉比mybatis好用多了,毕竟经过了公司这么多项目的考验,总比自己用mybatis写的项目可靠,但以下分享的还是mybatis的代码
注册接口方法:http://192.168.1.116:8080/register?username=111&password=222
@RequestMapping(value = "register", method = RequestMethod.GET) @ResponseBody public Map<String, Object> register(@RequestParam("username") String username, @RequestParam("password") String password) { out.println("welcome to register,username=" + username + ";password=" + password); Map<String, Object> map = new HashMap<>(); ResultBean result = onRegister(username, password); out.println("result==>" + result); map.put("code", result.getCode()); map.put("reason", result.getReason()); map.put("success", result.isSuccess()); return map; }
具体的注册方法,获取session基本和Hibernate差不多
private ResultBean onRegister(String username, String password) { ResultBean resultBean = new ResultBean(); SqlSession session = null; try { session = sqlSessionFactory.openSession(); LoginMapper loginMapper = session.getMapper(LoginMapper.class); Map<String, Object> map = new HashMap<>(); map.put("name", username); map.put("password", password); LoginBean bean = new LoginBean(); bean.setName(username); bean.setPassword(password); // 查询用户是否存在 LoginBean userExist = loginMapper.findUserByName(map); if (userExist != null) { // 存在后无法注册 resultBean.setCode("001"); resultBean.setSuccess(false); resultBean.setReason("用户已存在"); } else { loginMapper.addUser(bean); session.commit();// 重要,一定要commit,否则无法insert System.out.println("当前增加的用户id为:" + bean.getId()); resultBean.setCode("200"); resultBean.setSuccess(true); resultBean.setReason("注册成功"); } } catch (Exception e) { e.printStackTrace(); out.println("注册异常==>" + e.getMessage()); resultBean.setCode("001"); resultBean.setSuccess(false); resultBean.setReason("注册异常"); } finally { session.close(); } return resultBean; }
这个Mapper需要在配置文件中指定
public interface LoginMapper { public LoginBean findUserByName(Map<String,Object> map) throws Exception; public void addUser(LoginBean bean) throws Exception; }
这是对应的LoginMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <mapper namespace="com.xm.travel.LoginMapper"> <select id="loadRunList" parameterType="java.util.Map" resultType="com.xm.travel.RunBean"> select * from run </select> <select id="loginUser" parameterType="java.util.Map" resultType="com.xm.travel.LoginBean"> select * from user where name = #{name} and password = #{password} </select> <select id="findUserByName" parameterType="java.util.Map" resultType="com.xm.travel.LoginBean"> select * from user where name = #{name} </select> <insert id="addUser" useGeneratedKeys="true" keyProperty="id" > insert into user(id,name,password) values(#{id},#{name},#{password}) </insert> </mapper>