chuxue1989的专栏

自己学习历程的记录,每天记录一点点

一、mybatis入门

我的理解mybatis就是把sql语句剥离出来。
mybatis基本配置

mybatis-config.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 resource="jdbc.properties"/>
    <typeAliases>
        <package name="com.hfview.po"/>
    </typeAliases>
    <!--定义数据源-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
                <property name="url" value="${url}"/>
            </dataSource>
        </environment>
    </environments>
    <!--这里就是剥离出来的sql语句-->
    <mappers>
        <mapper resource="com/hfview/po/user.xml"/>
        <mapper resource="com/hfview/po/menu.xml"/>
        <mapper resource="com/hfview/po/car.xml"/>
        <mapper resource="com/hfview/po/coach.xml"/>
        <mapper resource="com/hfview/po/driverecord.xml"/>
        <mapper resource="com/hfview/po/orderrecord.xml"/>
        <mapper resource="com/hfview/po/userscore.xml"/>
    </mappers>
</configuration>

其中一个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="com.hfview.po.User">

    <sql id="userColumns">id,password,name,sex,cellPhone,startTime,endTime,dropTime,nowType,expType,description,status,image,coachId,cardId</sql>
    <sql id="menuColumns">menuId,menuName,menuLevel,menuParentId,menuParentName,menuURL,menuOrder,description
    </sql>

    <insert id="add" parameterType="User">
        insert into T_User (password,name,sex,cellPhone,startTime,endTime,dropTime,nowType,expType,description,status,image,coachId,cardId) 
        values(#{password},#{name},#{sex},#{cellPhone},#{startTime},#{endTime},#{dropTime},
        #{nowType},#{expType},#{description},#{status},#{image},#{coachId},#{cardId})
    </insert>

    <insert id="add_batch" parameterType="map">
        insert into T_UserAction (userId,menuId) 
        values (#{userId},#{menuId})

    </insert>

    <update id="edit" parameterType="User">
        update T_User set password=#{password},name=#{name},sex=#{sex},cellPhone=#{cellPhone},startTime=#{startTime},endTime=#{endTime},dropTime=#{dropTime},
        nowType=#{nowType},expType=#{expType},description=#{description},status=#{status},image=#{image},coachId=#{coachId},cardId=#{cardId}
        where id=#{id}
    </update>

    <delete id="delete" parameterType="int">
        delete T_User where id=#{id}
    </delete>
    <delete id="delete_union" parameterType="int">
        delete T_UserAction where userId=#{userId}
    </delete>

    <select id="login" parameterType="int" resultType="User">
        select
        *
        from T_User where name=#{name}
    </select>

    <select id="getById" parameterType="int" resultType="User" >
        select
        *
        from T_User where id=#{id}
    </select>

    <select id="getAll" resultType="User" >
        select
        *
        from T_User 
    </select>

    <select id="getDiffType" parameterType="int" resultType="User" >
        select
        *
        from T_User where status=#{type}
    </select>

    <select id="getMenu" parameterType="int" resultType="Menu">
        select b.* from T_UserAction a,T_Menu b where a.MenuId = b.menuId and a.userId=#{id}
    </select>


</mapper>

然后定义SqlSessionFactory和SqlSession的获取方式

package com.hfview.utils;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtil {
    private static SqlSessionFactory factory;
    static {
        try {
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            factory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession createSession() {
        return factory.openSession();
    }

    public static void closeSession(SqlSession session) {
        if(session!=null) session.close();
    }
}

mybatis的使用

package com.hfview.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Component;

import com.hfview.dao.BaseDao;
import com.hfview.po.Menu;
import com.hfview.po.User;
import com.hfview.utils.DBConnection;
import com.hfview.utils.MyBatisUtil;

@Component
public class UserDaoImpl extends BaseDao<User> {
    public List<Menu> getMenu(Class<User> clz, int id) {
        SqlSession session = null;
        List<Menu> list = null;
        try {
            session = MyBatisUtil.createSession();
            list = session.selectList(clz.getName() + ".getMenu", id);
        } finally {
            MyBatisUtil.closeSession(session);
        }
        return list;
    }

    public void deleteUnion(Class<User> clz, int id) {
        SqlSession session = null;
        try {
            session = MyBatisUtil.createSession();
            session.delete(clz.getName() + ".delete_union", id);
        } finally {
            session.commit();
            MyBatisUtil.closeSession(session);
        }
    }

    public void giveAction(int userId, String[] action) {
        SqlSession session = null;
        Map<String ,Object> map = new HashMap<String, Object>();
        map.put("userId", userId);
        try {
            session = MyBatisUtil.createSession();
            session.delete(User.class.getName()+ ".delete_union", userId);
                for(int i=0;i<action.length;i++){
                    map.put("menuId", action[i]);
                    session.insert(User.class.getName()+ ".add_batch",map);
                    map.remove("menuId");
                }
        } finally {
            session.commit();
            MyBatisUtil.closeSession(session);
        }
    }
    /**
     * 0:退学 
     * 1:在培
     * 2:毕业
     * @return
     */
    public List<User> getDiffType(int type){
        SqlSession session = null;
        List<User> list=null;
        try {
            session = MyBatisUtil.createSession();
            list= session.selectList(User.class.getName() + ".getDiffType", type);
        } finally {
            session.commit();
            MyBatisUtil.closeSession(session);
        }
        return list;
    }
    /**
     * 级联的删除用户
     * @param userId
     */
    public void deleteUser(int userId){
        Connection conn =null;
        PreparedStatement  st=null;
        ResultSet rs=null;

        try {
            conn= DBConnection.getDBConnection();
            st = conn.prepareStatement("{call deleteUser(?)}");
            st.setInt(1,userId);
            st.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }



}

这个只是最基本的配置,后面会将mybatis和spring结合配置、事物配置、以及详细的用法

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chuxue1989/article/details/79974703
个人分类: mybatis
上一篇spring boot web开发------自定义springmvc配置
下一篇二、mybatis和spring结合
想对作者说点什么? 我来说一句

myBatis操作数据库

2013年07月25日 1.94MB 下载

MyBatis入门.7z

2017年12月07日 96.18MB 下载

mybatis入门案例 mybatis入门案例

2011年08月08日 1.22MB 下载

MyBatis入门到精通 中文完整版

2017年12月22日 100.17MB 下载

没有更多推荐了,返回首页

关闭
关闭