zoukankan      html  css  js  c++  java
  • mybatis学习(二)

    1.创建数据库:

    #创建数据库
    create DATABASE mydb;
    USE mydb;
    CREATE Table  users(
        id INT AUTO_INCREMENT PRIMARY KEY comment '用户编号',
        username VARCHAR(50) NOT NULL COMMENT '登录账号',
        userpass varchar(50) NoT NULL COMMENT '登录密码',
        nickname VARCHAR(50) comment '昵称',
        age Int  COMMENT '用户年龄',
       gender varchar(5) COMMENT '用户性别',
       phone varchar(13) comment '联系方式',
       email varchar(20) comment '用户邮箱',
       createTime DATETIME COMMENT '账号创建时间',
       updateTime DATETIME COMMENT '更新时期 ',
       lastLogin  DATETIME COMMENT '最后登录时间',
       userStatus INT COMMENT '永固账号的状态 0 ',
       remark TEXT COMMENT '备注'
    );

    2.配置mybatis核心xml文件:

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <!--properties配置,用于加载外部的properties配置文件-->
        <properties resource="db.properties" ></properties>
        <!--environments 主要用于进行数据源的配置,可以配置多个数据源~通过default属性来指定当前项目运行过程中使用的的是你哪个数据源-->
        <environments default="development">
            <!--environment 用来配置一个独立的数据源 id属性用于给当前数据源定义一个名称,方便我们的项目指定-->
            <environment id="development">
                <!--transactionManger用于配置事务管理,默认情况下使用的是jdbc事务管理-->
                <transactionManager type="JDBC"/>
                <!--dataSource具体数据源的链接信息 type属性用于指定是否使用连接池-->
                <dataSource type="POOLED">
                    <property name="driver" value="${driver}"/>
                    <property name="url" value="${url}"/>
                    <property name="username" value="${username}"/>
                    <property name="password" value="${password}"/>
                </dataSource>
            </environment>
        </environments>
        <!-- mappers主要用于配置我们外部的映射配置文件在主配置文件中需要引入加载配置文件-->
        <mappers>
            <!--mapper主要配置引入某一个具体的映射文件,resource进行路径的引入-->
            <mapper resource="mapper/usersMapper.xml"/>
        </mappers>
    </configuration>

    配置数据源的连接信息

    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/mydb
    username=root
    password=root

    Mapper中标签的应用:

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <!--
    mapper 用于定义一个映射配置文件的根节点
    namespace属性是用来配置命名空间,主要进行session级别的缓存管理
    命名空间默认情况下,使用我们当前操作的实体类的全路径
    -->
    <mapper namespace="com.damu.entity.Users">
    
        <!--<select id="findUsers" resultType="com.damu.entity.Users">-->
        <select id="findUsers" resultMap="forUsers">
            select * from users
    
            <if test="id != null">
                where id = #{id}
            </if>
        </select>
    
        <!-- 自定义映射关系集合:主要包含对于一些自定义操作的配置,如不一致的属性和字段 -->
        <resultMap id="forUsers" type="com.damu.entity.Users">
            <!-- 绑定id主键 -->
            <id property="id" column="id"></id>
            <!-- result配置,主要配置普通属性,column表示配置的是数据库字段名称 property配置的是实体类的属性名称 -->
            <result column="username" property="name"></result>
            <!--一对多关系-->
            <collection property="addresses" column="id" ofType="com.damu.entity.Address" select="getAddress"></collection>
        </resultMap>
            
        <select id="getAddress" resultType="com.damu.entity.Address">
            select * from address where userid = #{id}
        </select>
    
    
    
        <sql id="user_fields">
            username, userpass, nickname, age, gender, email, phone, createTime, updateTime, lastLogin, userstatus, remark
        </sql>
    
        <insert id="addUser" useGeneratedKeys="true" keyProperty="id">
            insert into users( <include refid="user_fields"></include>)
            values(#{name},#{userpass}, #{nickname}, #{age}, #{gender}, #{email}, #{phone}, #{createTime}, #{updateTime}, #{lastLogin}, #{userStatus}, #{remark})
        </insert>
    
        <update id="updateUser">
            update users
            <set>
                <if test="name != null">username = #{name},</if>
                <if test="userpass != null">userpass = #{userpass},</if>
                <if test="nickname != null">nickname = #{nickname},</if>
                <if test="age != null">age = #{age},</if>
                <if test="gender != null">gender = #{gender},</if>
                <if test="email != null">email = #{email},</if>
                <if test="phone != null">phone = #{phone},</if>
                <if test="createTime != null">createTime = #{createTime},</if>
                <if test="updateTime != null">updateTime = #{updateTime},</if>
                <if test="lastLogin != null">lastlogin = #{lastLogin},</if>
                <if test="userStatus != null">userStatus = #{userStatus},</if>
                <if test="remark != null">remark = #{remark},</if>
            </set>
              where id = #{id}
        </update>
    
        <delete id="delUser">
            delete from users where id = #{id}
        </delete>
    </mapper>

    SqlSessionFactory工厂的处理类:

    package com.xiaoqiang.utils;
    
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    import java.io.IOException;
    import java.io.InputStream;
    
    public class SqlSessionFactoryUtils {
             private static  String RESOURCE="mybatis-config.xml";
             private static SqlSessionFactory sqlSessionFactory;
             private static  ThreadLocal<SqlSession> threadLocal=new ThreadLocal<SqlSession>();
    
    //         创建一个初始化SqlSessionFactory的方法
           public static  void  initSqlSessionFactory()
           {
               try {
                   InputStream inputStream= Resources.getResourceAsStream(RESOURCE);
                   sqlSessionFactory= new SqlSessionFactoryBuilder().build(inputStream);
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
    //       获取工厂对象方法
        public static  SqlSessionFactory getSqlSessionFactory()
        {
            return  sqlSessionFactory;
        }
    //    关闭sqlsession对象
        public  static  void close()
        {
            SqlSession sqlsession=threadLocal.get();
            if(sqlsession!=null)
            {
                sqlsession.close();
                threadLocal.set(null);
            }
        }
    }
    package com.xiaoqiang.dao;
    
    import com.xiaoqiang.entity.Users;
    import com.xiaoqiang.utils.SqlSessionFactoryUtils;
    import org.apache.ibatis.session.SqlSession;
    
    
    import java.util.List;
    
    public class UsersDao {
         private SqlSession session= SqlSessionFactoryUtils.getSqlSessionFactory().openSession();
         private List<Users> list;
    
        public List<Users> findALL() {
            try {
                list=session.selectList("findList");
            }
           catch (Exception e) {
    
           }
            finally {
                SqlSessionFactoryUtils.close();
            }
            return  list;
        }
    }
    package com.damu.dao;
    
    import com.damu.entity.Users;
    import com.damu.utils.SqlSessionFactoryUtils;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    
    import java.util.List;
    
    /**
     * 
     */
    public class UsersDAO {
        private SqlSession sqlSession;
        private List<Users> list;
        private Users user;
    
        private SqlSession getSession() {
            sqlSession = SqlSessionFactoryUtils.getSqlSessionFactory().openSession();
            return sqlSession;
        }
    
        /**
         * 查询全部用户
         * @return
         */
        public List<Users> findAll() {
            try {
                list = getSession().selectList("findUsers");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                sqlSession.close();
            }
            return list;
        }
    
        /**
         * 查询单个用户根据编号
         * @return
         */
        public Users findById(Integer id) {
            try {
                user = getSession().selectOne("findUsers", new Users(id));
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                sqlSession.close();
            }
            return user;
        }
    
        /**
         * 增加一个新用户数据到数据库的方法
         * @return
         */
        public Users addUser(Users user) {
            try {
    
                // 返回值:是insert执行过程中影响的行数
                getSession().insert("addUser", user);
    
                sqlSession.commit();
    
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                sqlSession.close();
            }
            return user;
        }
    
    
        /**
         * 用于修改用户资料的方法
         * @return
         */
        public Users updateUsers(Users user) {
            try {
    
                // 返回值:是insert执行过程中影响的行数
                getSession().update("updateUser", user);
    
                sqlSession.commit();
    
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                sqlSession.close();
            }
            return user;
        }
    
        /**
         * 用于修改用户资料的方法
         * @return
         */
        public void delUsers(Integer id) {
            try {
    
                // 返回值:是insert执行过程中影响的行数
                getSession().delete("delUser", id);
    
                sqlSession.commit();
    
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                sqlSession.close();
            }
        }
    
    }
    package com.damu.servlet;
    
    import com.damu.dao.UsersDAO;
    import com.damu.entity.Users;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.util.List;
    
    /**
     * 
     */
    @WebServlet("/index")
    public class UsersFindServlet extends HttpServlet {
    
        private UsersDAO usersDAO = new UsersDAO();
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            this.doPost(req, resp);
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            List<Users> list = usersDAO.findAll();
            System.out.println(list);
            req.setAttribute("usersList", list);
    
            req.getRequestDispatcher("index.jsp").forward(req, resp);
        }
    }
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
    <html>
    <head>
        <title>用户管理中心</title>
        <link rel="stylesheet" href="lib/bootstrap-3.3.7-dist/css/bootstrap.min.css">
        <script src="lib/2.2.4/jquery-1.12.4.min.js"></script>
        <script src="lib/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
    </head>
    <body>
    <div class="container">
        <div class="row">
            <div class="page-header">
                <h1>后台管理系统 <small>用户数据管理中心</small></h1>
            </div>
        </div>
        <div class="row">
            <div class="jumbotron">
                <h1>MyBatis基础入门课程!</h1>
                <p>通过一个项目来完成基础部分的学习</p>
                <p><a class="btn btn-primary btn-lg" href="#" role="button"></a></p>
                <p><a class="btn btn-primary btn-lg" href="${pageContext.request.contextPath}/addusers.jsp" role="button">新增用户</a></p>
            </div>
        </div>
        <div class="row">
            <table class="table table-hover table-striped">
                <tr>
                    <th>用户编号</th>
                    <th>登录账号</th>
                    <th>用户昵称</th>
                    <th>邮箱</th>
                    <th>联系方式</th>
                    <th>账号创建时间</th>
                    <th>用户状态</th>
                    <th>操作</th>
                </tr>
                <c:forEach var="user" items="${usersList}">
                <tr>
                    <td>${user.id}</td>
                    <%--<td>${user.username}</td>--%>
                    <td>${user.name}</td>
                    <td>${user.nickname}</td>
                    <td>${user.email}</td>
                    <td>${user.phone}</td>
                    <td>
                        <fmt:formatDate value="${user.createTime}" pattern="yyyy-MM-dd HH:mm:ss"></fmt:formatDate>
                    </td>
                    <c:if test="${user.userStatus == 0}">
                        <td>正常</td>
                    </c:if>
                    <c:if test="${user.userStatus == 1}">
                        <td>锁定</td>
                    </c:if>
                    <c:if test="${user.userStatus == 2}">
                        <td>删除</td>
                    </c:if>
                    <td>
                        <a href="${pageContext.request.contextPath}/detail?id=${user.id}">查看</a>
                        <c:if test="${user.userStatus == 0}">
                            <a href="${pageContext.request.contextPath}/deluser?id=${user.id}&type=lock">锁定</a>
                        </c:if>
                        <c:if test="${user.userStatus == 1}">
                            <a href="${pageContext.request.contextPath}/deluser?id=${user.id}&type=unlock">解锁</a>
                        </c:if>
                        <a href="${pageContext.request.contextPath}/deluser?id=${user.id}&type=del">删除</a>
                    </td>
                </tr>
                </c:forEach>
            </table>
        </div>
    </div>
    </body>
    </html>

    日志输出配置properties文件:

    log4j.rootLogger=DEBUG, A1
    log4j.appender.A1=org.apache.log4j.ConsoleAppender
    log4j.appender.A1.layout=org.apache.log4j.PatternLayout
    log4j.appender.A1.layout.ConversionPattern=%-4r %-5p [%t] %37c %3x - %m%n

    在servlet类里面打印输出日志:

    package com.damu.servlet;
    
    import com.damu.dao.UsersDAO;
    import com.damu.entity.Users;
    import org.apache.log4j.Logger;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    @WebServlet("/detail")
    public class UsersFindByIdServlet extends HttpServlet {
    
        /*
        创建对应的日志记录对象
        通过不同的级别进行日志的记录【DEBUGWARNINFO] DEBUG是最详细级别,也是最小的级别
         */
        private Logger log = Logger.getLogger(UsersFindByIdServlet.class);
    
    
        private UsersDAO usersDAO = new UsersDAO();
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            this.doPost(req, resp);
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            String id = req.getParameter("id");
    
            log.info("获取到查询参数id--》" + id);
    
            Users user = usersDAO.findById(Integer.parseInt(id));
    
            log.info("查询数完成,查询到的数据:" + user);
    
            req.setAttribute("user", user);
    
            req.getRequestDispatcher("detail.jsp").forward(req, resp);
        }
    }
  • 相关阅读:
    2019年有谁放弃了创业当老板,选择打工或者待业?
    为什么很多人说现在做什么生意都不好做?
    创业是不是很难,假如只有500块如何创业?
    为什么生意越来越难做?
    我现在想做熟食行业,不知道现在的前景怎么样,能行吗?
    在北京十万元创业干什么好?
    风投公司会不会抄袭创业者的模式?
    利用快手抖音做小吃培训,年入100000+
    写车评兼职赚钱项目,每月稳赚2000-5000元
    【瓷博会】宝瓷林《锦绣中华》发布会
  • 原文地址:https://www.cnblogs.com/socketqiang/p/10834574.html
Copyright © 2011-2022 走看看