关于后端:SpringBootSpring-JdbcTemplate后端开发实例连接mysql数据库

36次阅读

共计 13657 个字符,预计需要花费 35 分钟才能阅读完成。

我的项目整体目录如下:

用户表构造

mysql 数据库配置

user 实体类

package com.example.system.entity;
import java.util.Date;
/**
 * 用户信息对象
 * @author xutao
 * 创立工夫:2020-12-8 上午 13:59:23
 */public class sysUser{
    public int id;//id
 public String username;// 用户名
 public String loginname;// 登录账号
 public String password;// 明码
 public int areaid;// 区域编码
 public int orgid;// 机构 id
 public String sex;// 性别
 public String email;// 邮箱
 public int phone;// 手机号码
 public String ipaddress;//IP 地址
 public int errorcount;// 谬误计数
 public Date lastlogintime;// 上次登录工夫
 public Date passwdinvaltime;// 明码生效工夫
 public Date locktime;// 锁定工夫
 public int delflag;// 删除标识
 public Date createtime;// 创立工夫
 public String createuser;// 创立用户
 public Date updatetime;// 更新工夫
 public String updateuser;// 更新用户
 public int groupid;// 组别 id
 public int roleid;// 角色 id
 public int getId() {return id;}
    public void setId(int id) {this.id = id;}
    public String getUsername() {return username;}
    public void setUsername(String username) {this.username = username;}
    public String getLoginname() {return loginname;}
    public void setLoginname(String loginname) {this.loginname = loginname;}
    public String getPassword() {return password;}
    public void setPassword(String password) {this.password = password;}
    public int getAreaid() {return areaid;}
    public void setAreaid(int areaid) {this.areaid = areaid;}
    public int getOrgid() {return orgid;}
    public void setOrgid(int orgid) {this.orgid = orgid;}
    public String getSex() {return sex;}
    public void setSex(String sex) {this.sex = sex;}
    public String getEmail() {return email;}
    public void setEmail(String email) {this.email = email;}
    public int getPhone() {return phone;}
    public void setPhone(int phone) {this.phone = phone;}
    public String getIpaddress() {return ipaddress;}
    public void setIpaddress(String ipaddress) {this.ipaddress = ipaddress;}
    public int getErrorcount() {return errorcount;}
    public void setErrorcount(int errorcount) {this.errorcount = errorcount;}
    public Date getLastlogintime() {return lastlogintime;}
    public void setLastlogintime(Date lastlogintime) {this.lastlogintime = lastlogintime;}
    public Date getPasswdinvaltime() {return passwdinvaltime;}
    public void setPasswdinvaltime(Date passwdinvaltime) {this.passwdinvaltime = passwdinvaltime;}
    public Date getLocktime() {return locktime;}
    public void setLocktime(Date locktime) {this.locktime = locktime;}
    public int getDelflag() {return delflag;}
    public void setDelflag(int delflag) {this.delflag = delflag;}
    public Date getCreatetime() {return createtime;}
    public void setCreatetime(Date createtime) {this.createtime = createtime;}
    public String getCreateuser() {return createuser;}
    public void setCreateuser(String createuser) {this.createuser = createuser;}
    public Date getUpdatetime() {return updatetime;}
    public void setUpdatetime(Date updatetime) {this.updatetime = updatetime;}
    public String getUpdateuser() {return updateuser;}
    public void setUpdateuser(String updateuser) {this.updateuser = updateuser;}
    public int getGroupid() {return groupid;}
    public void setGroupid(int groupid) {this.groupid = groupid;}
    public int getRoleid() {return roleid;}
    public void setRoleid(int roleid) {this.roleid = roleid;}
}

长久层接口 dao

package com.example.system.dao;
import com.example.system.entity.sysUser;
/**
 * 登录性能 dao 接口
 * @author lmwang
 * 创立工夫:2020-12-9 下午 16:53:20
 */
public interface loginDao {
    // 登录验证账号密码
 public Object login(String loginName,String password);
    // 首次登录强制批改明码 / 重置明码(管理员权限)public void updatePd(int id,String password);
    // 登录胜利后获取用户惟一 id
 public Object queryById(String loginName);
    // 通过惟一 id 获取用户对象
 public sysUser userById(int id);
    // 用户批改个人信息
 public void updateSysUser(sysUser user);
}

dao 映射层 daoimpl,继承 dao 接口

package com.example.system.dao.impl;
import com.example.system.dao.loginDao;
import com.example.system.entity.sysUser;
import com.example.system.util.JdbcDaoSupport4mysql;
import com.example.system.util.MysqlDb;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
@MysqlDb
@Repository
public class loginDaoImpl extends JdbcDaoSupport4mysql implements loginDao {
    @Override
 public Object login(String loginName, String password) {
        String sql="select password from sys_user where login_name='"+loginName+"'";
        ArrayList<Object>  paralist = new ArrayList<Object>();
        return this.queryForList(sql,paralist);
    }
    @Override
 public Object queryById(String loginName) {
        String sql="select id from sys_user where login_name='"+loginName+"'";
        ArrayList<Object>  paralist = new ArrayList<Object>();
        return this.queryForList(sql,paralist);
    }
    // 明码批改与重置
 @Override
 public void updatePd(int id,String password) {
        String sql="update sys_user set password='"+password+"'where id='"+id+"'";
        this.getJdbcTemplate().update(sql, new Object[]{id,password});
    }
    @Override
 public void updateSysUser(sysUser user) {if(null!=user){
            String sql="update sys_user set 1=1";
            if(null!=user.getLoginname()){ }
            if(0!=user.areaid){sql+=",area_id="+user.areaid;}
            if(null!=user.getSex()){sql=",sex='"+user.getSex()+"' ";
            }
            if(null!=user.getEmail()){sql=",email='"+user.getEmail()+"' ";
            }
            if(null!=user.getIpaddress()){sql=",ip_address='"+user.getIpaddress()+"'";
            }
            sql+= "where loginName='"+user.getLoginname()+"'where id="+user.getId();
            this.getJdbcTemplate().update(sql,new Object[]{user});
        }
    }
    @Override
 public sysUser userById(int id) {
        String  sql="select  id,username,login_name,password,area_id,org_id,sex,email," +
                "phone,ip_address,error_count,last_login_time,passwd_inval_time,lock_time," +
                "del_flag, create_time,create_user,update_time,update_user," +
                "group_id,role_id from sys_user where id='"+id+"'";
        return this.getJdbcTemplate().query(sql,new Object[]{id},new ResultSetExtractor<sysUser>(){
            @Override
 public sysUser extractData(ResultSet rs) throws SQLException, DataAccessException {sysUser user = new sysUser();
                while(rs.next()) {user.setId(rs.getInt("id"));
                    user.setUsername(rs.getString("username"));
                    user.setLoginname(rs.getString("login_name"));
                    user.setPassword(rs.getString("password"));
                    user.setAreaid(rs.getInt("area_id"));
                    user.setOrgid(rs.getInt("org_id"));
                    user.setSex(rs.getString("sex"));
                    user.setEmail(rs.getString("email"));
                    user.setPhone(rs.getInt("phone"));
                    user.setIpaddress(rs.getString("ip_address"));
                    user.setErrorcount(rs.getInt("error_count"));
                    user.setLastlogintime(rs.getDate("last_login_time"));
                    user.setPasswdinvaltime(rs.getDate("passwd_inval_time"));
                    user.setLocktime(rs.getDate("lock_time"));
                    user.setDelflag(rs.getInt("del_flag"));
                    user.setCreatetime(rs.getDate("create_time"));
                    user.setCreateuser(rs.getString("create_user"));
                    user.setUpdatetime(rs.getDate("update_time"));
                    user.setUpdateuser(rs.getString("update_user"));
                    user.setGroupid(rs.getInt("group_id"));
                    user.setRoleid(rs.getInt("role_id"));
                }
                return user;
            }
        });
    }
}

业务层 service

package com.example.system.service;
import com.example.system.dao.loginDao;
import com.example.system.dao.sysLoginLogDao;
import com.example.system.entity.sysUser;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service
public class loginService {
    @Resource
 private loginDao logindao;
    @Resource
 private sysLoginLogDao sysLoginLogDao;
    // 登录验证
 public boolean login(String loginName,String password){Object pd= logindao.login(loginName,password);
        // 明码验证
 if(pd.equals(password)){
            // 登录胜利
 return true;
        }
        return false;
    }
    // 批改 / 重置明码
 public void updatePd(int id[],String password){
        //password 为 null 时,默认为重置标识 reset,执行明码重置操作
 if(null==password){password="000000";}
        for (int i : id) {logindao.updatePd(i,password);
        }
    }
    // 批改用户信息
 public void updateSysUser(sysUser user){logindao.updateSysUser(user);
    }
    // 通过惟一 id 获取用户详情
 public sysUser queryUser(int id){return logindao.userById(id);
    }
    // 查问登录用户的惟一 id
 public int queryUserById(String loginName){return Integer.parseInt(logindao.queryById(loginName).toString());
    }
}

管制层 controller,前后端拆散开发,凋谢接口给前端调用

package com.example.system.controller;
import com.example.system.entity.sysUser;
import com.example.system.service.loginService;
import com.example.system.util.jwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
 * 登录验证及相干操作 Controller
 */@RestController
@RequestMapping(value="/system")
public class LoginController {
    @Autowired
 private loginService loginService;
    // 登录页
 @RequestMapping(value="/getLoginPage.do")
    public String getLoginPage(){return "";}
    // 辅控系统首页
 @RequestMapping(value="/getIndexPage.do")
    public String getIndexPage() {return "";}
    /**
 * 登录验证
 */
 @RequestMapping(value="/getLogin.do",method= RequestMethod.POST)
    @ResponseBody
 public Map getLogin(String loginName,String password){Map map = new HashMap();
        Boolean login=loginService.login(loginName,password);
        if(login==false){
            // 登录信息验证失败
 // 返回验证提醒
 map.put("flag",login);// 登录验证标识
 map.put("info","账号密码输出有误!");
            return map;
        }else{
            String token=null;// 登录令牌
 String refreshToken=null;// 刷新令牌
 int id=loginService.queryUserById(loginName);
            try {token=jwtUtil.createToken(id+"",loginName);
            } catch (Exception e) {e.printStackTrace();
            }
            // 刷新 token, 免密登陆
 refreshToken= UUID.randomUUID().toString().replaceAll("-","");
            map.put("flag",login);// 登录验证标识
 map.put("time",86400);// 1 天 =86400 秒
 map.put("token",token);
            map.put("refreshToken", refreshToken);
            return map;
        }
    }
    /**
 * 重置明码(管理员权限)*/
 @RequestMapping(value="/reset.do",method= RequestMethod.POST)
    @ResponseBody
 public void Reset(int[] id){loginService.updatePd(id,null);
    }
    /**
 * 批改明码
 */
 @RequestMapping(value="/updatePd.do",method= RequestMethod.POST)
    @ResponseBody
 public void updatePd(int[] id,String password){loginService.updatePd(id,password);
    }
    /**
 * 批改用户信息
 */
 @RequestMapping(value="/updateInfo.do",method= RequestMethod.POST)
    @ResponseBody
 public void updatePersonInfo(sysUser user){loginService.updateSysUser(user);
    }
}

工具类
JdbcDaoSupport4mysql

package com.example.system.util;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import com.example.system.entity.PageObj;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
/**
 * mysql dao 的父类
 * @author chen.kui
 * @date 2014 年 9 月 28 日 15:26:57
 */@Repository
public class JdbcDaoSupport4mysql{
   
   @Resource
 private JdbcTemplate jdbcTemplate;
   /**
 * 为以后的 DAO 返回 JdbcTemplate
 */ public final JdbcTemplate getJdbcTemplate() {return jdbcTemplate;}
   /**
 * sql 执行  分页
 * 2015-12-2 
    */
 public Map<String, Object> queryByPage(String sql, ArrayList<Object> paralist, PageObj pageObj){Map<String, Object> modelMap = new HashMap<String, Object>();
      List<Object> list =this.queryByPage(sql, new RowMapper<Object>(){
         @Override
 public Object mapRow(ResultSet rs, int rowNum) throws SQLException {Map<String,String> row = new HashMap<String,String>();  
             ResultSetMetaData rowdata =rs.getMetaData();
             for(int i = 1 ; i<= rowdata.getColumnCount() ; i++){row.put(rowdata.getColumnLabel(i), rs.getObject(i)==null?"":String.valueOf(rs.getObject(i)));
             }
            return row;
         }
      },pageObj,paralist.toArray());
      modelMap.put("pageObj", pageObj);
      modelMap.put("list", list);
      return modelMap;
   }
   
   /**
 * 通用查问 返回 list  JSONObject 对象
 * @param sql
 * @param paralist
 * @return
 * 2015-12-2    */
 public List<Object> queryForList(String sql,ArrayList<Object> paralist){return this.getJdbcTemplate().query(sql, paralist.toArray(),new RowMapper<Object>(){
         @Override
 public Object mapRow(ResultSet rs, int rowNum) throws SQLException {Map<String,String> row = new HashMap<String,String>();  
             ResultSetMetaData rowdata =rs.getMetaData();
             for(int i = 1 ; i<= rowdata.getColumnCount() ; i++){row.put(rowdata.getColumnLabel(i), rs.getObject(i)==null?"":String.valueOf(rs.getObject(i)));
             }
            return row;
         }
      });
   }
   
   public List<Map<String, Object>> queryByPageForList(String sql, PageObj pageObj, Object... params) {int startIndex = (pageObj.getPage()-1) * pageObj.getRows();
      pageObj.setTotal(this.getJdbcTemplate().queryForObject("SELECT COUNT(*) TOTAL FROM ("+sql+")PAGE_", params, Integer.class));
      String pageSql = "SELECT PAGE_.* FROM("+sql+")PAGE_ LIMIT"+startIndex+","+pageObj.getRows();
      return this.jdbcTemplate.queryForList(pageSql, params);
   }
   
   public List<Map<String, Object>> queryByPageForList(String sql, PageObj pageObj) {int startIndex = (pageObj.getPage()-1) * pageObj.getRows();
      pageObj.setTotal(this.getJdbcTemplate().queryForObject("SELECT COUNT(*) TOTAL FROM ("+sql+")PAGE_", Integer.class));
      String pageSql = "SELECT PAGE_.* FROM("+sql+")PAGE_ LIMIT"+startIndex+","+pageObj.getRows();
      return this.jdbcTemplate.queryForList(pageSql);
   }
   
   /**
 * 通用的分页查问
 * @param sql
 * @param rowMapper
 * @param pageObj
 * @return
 */ public <T> List<T> queryByPage(String sql, Object[] params, RowMapper<T> rowMapper, PageObj pageObj) {int startIndex = (pageObj.getPage()-1) * pageObj.getRows();
      pageObj.setTotal(this.getJdbcTemplate().queryForObject("SELECT COUNT(*) TOTAL FROM ("+sql+") PAGE_", params, Integer.class));
      String pageSql = "SELECT PAGE_.* FROM("+sql+")PAGE_ LIMIT"+startIndex+","+pageObj.getRows();
      return this.jdbcTemplate.query(pageSql, params, rowMapper);
   }
   
   /**
 * 通用的分页查问
 * @param sql
 * @param params
 * @param rowMapper
 * @param pageObj
 * @return
 */ public <T> List<T> queryByPage(String sql, RowMapper<T> rowMapper, PageObj pageObj) {int startIndex = (pageObj.getPage()-1) * pageObj.getRows();
      pageObj.setTotal(this.getJdbcTemplate().queryForObject("SELECT COUNT(*) TOTAL FROM ("+sql+")PAGE_", Integer.class));
      String pageSql = "SELECT PAGE_.* FROM("+sql+")PAGE_ LIMIT"+startIndex+","+pageObj.getRows();
      return this.jdbcTemplate.query(pageSql, rowMapper);
   }
   
   public <T> List<T> queryByPage(String sql, RowMapper<T> rowMapper, PageObj pageObj, Object... params) {int startIndex = (pageObj.getPage()-1) * pageObj.getRows();
      pageObj.setTotal(this.getJdbcTemplate().queryForObject("SELECT COUNT(*) TOTAL FROM ("+sql+")PAGE_",params, Integer.class));
      String pageSql = "SELECT PAGE_.* FROM("+sql+")PAGE_ LIMIT"+startIndex+","+pageObj.getRows();
      return this.jdbcTemplate.query(pageSql, rowMapper,params);
   }
   
}

MysqlDb

package com.example.system.util;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * @Description 区别各数据库的实现类的注解
 * @author zhang.dechang
 * @date 2015 年 3 月 30 日 上午 10:06:00
 * */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MysqlDb {String value() default "";
}

正文完
 0