SpringBoot+Spring JdbcTemplate后端开发实例(连接mysql数据库)

项目整体目录如下:
image.png

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  paralist = new ArrayList();
        return this.queryForList(sql,paralist);
    }
    @Override
 public Object queryById(String loginName) {
        String sql="select id from sys_user where login_name='"+loginName+"'";
        ArrayList  paralist = new ArrayList();
        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(){
            @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 queryByPage(String sql, ArrayList paralist, PageObj pageObj){
      Map modelMap = new HashMap();
      List list =this.queryByPage(sql, new RowMapper(){
         @Override
 public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
            Map row = new HashMap();  
             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 queryForList(String sql,ArrayList paralist){
      return this.getJdbcTemplate().query(sql, paralist.toArray(),new RowMapper(){
         @Override
 public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
            Map row = new HashMap();  
             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> 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> 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  List queryByPage(String sql, Object[] params, RowMapper 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  List queryByPage(String sql, RowMapper 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  List queryByPage(String sql, RowMapper 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 "";
}

你可能感兴趣的:(后端,mysql,sql,springboot,orm)