首页 > 代码库 > mybatis(单表增删改查)

mybatis(单表增删改查)

(mybatis注意各个文件的映射问题)

用到的t_user数据库脚本:

-- 导出 mybatis 的数据库结构
CREATE DATABASE IF NOT EXISTS `mybatis` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `mybatis`;
-- 导出  表 mybatis.t_user 结构
CREATE TABLE IF NOT EXISTS `t_user` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) DEFAULT NULL,
  `password` varchar(50) DEFAULT NULL,
  `nickname` varchar(50) DEFAULT NULL,
  `type` tinyint(4) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

MyBatisUtil助手类

 

package edu.hhxy.btais.util;

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 SqlSession session = null;

    public static SqlSession createSeqSession() {
        try {
            // 1、创建配置文件(mybatis-config.xml)的输入流
            InputStream is = Resources
                    .getResourceAsStream("mybatis-config.xml");
            // 2、创建SQLSessionFactory
            SqlSessionFactory factory = new SqlSessionFactoryBuilder()
                    .build(is);
            // 3、创建SQLSessioin
            session = factory.openSession();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return session;
    }

    public static void closeSeqSession(SqlSession sqlSession) {
        try {
            sqlSession.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession = null;
        }
    }
}

 

User.xml

<?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="edu.hhxy.btais.User">
    <insert id="add" parameterType="User">
        insert into t_user
        (username,password,nickname,type)
        value(#{username},#{password},#{nickname},#{type})
    </insert>
    <update id="update" parameterType="User">
        update t_user set
        password=#{password},nickname=#{nickname},type=#{type} where id=#{id}
    </update>
    <delete id="delete" parameterType="int">
        delete from t_user where
        id=#{id}
    </delete>
    <select id="load" parameterType="int" resultType="User">
        select * from
        t_user where id=#{id}
    </select>

    <select id="list" resultType="User">
        select * from t_user
    </select>
</mapper>

src/jdbc.properties

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

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>
        <!--把edu.hhxy.btaisUser类都自动映射为User -->
        <typeAlias type="edu.hhxy.btais.User" alias="User" /> 
        <!-- 把edu.hhxy.btais所有类都自动映射 -->
        <package name="edu.hhxy.btais" />
    </typeAliases>
    <!-- 在properties之后加上typeAliases -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <!-- 配置mybatis的pooled的数据源 -->
            <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>
        <mapper resource="edu/hhxy/btais/User.xml" />
    </mappers>
</configuration>

FirstMybatisTest.java(JUNIT测试)

package edu.hhxy.btais;

import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import edu.hhxy.btais.util.MyBatisUtil;

public class FirstMybatisTest {
    @Test
    public void TestAll() {
        addTest();
        updateTest();
        deleteTest();
        loadTest();
        listTest();
    }

    @Test
    public void addTest() {
        SqlSession session = null;
        try {
            session = MyBatisUtil.createSeqSession();
            User u = new User();
            for (int i = 0; i < 10; i++) {
                u.setNickname("孙悟空");
                u.setPassword("123");
                u.setType(0);
                u.setUsername("wukong");
                session.insert("edu.hhxy.btais.User.add", u);
            }
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MyBatisUtil.closeSeqSession(session);
        }
    }

    @Test
    public void updateTest() {
        SqlSession session = null;
        try {
            session = MyBatisUtil.createSeqSession();
            User u = new User();
            u.setNickname("齐天大圣孙悟空");
            u.setPassword("123");
            u.setType(0);
            u.setId(106);
            u.setUsername("wukong");
            session.update("edu.hhxy.btais.User.update", u);
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MyBatisUtil.closeSeqSession(session);
        }
    }

    @Test
    public void deleteTest() {
        SqlSession session = null;
        try {
            session = MyBatisUtil.createSeqSession();
            User u = new User();
            u.setId(105);
            session.delete("edu.hhxy.btais.User.delete", u);
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MyBatisUtil.closeSeqSession(session);
        }
    }

    @Test
    public void loadTest() {
        SqlSession session = null;
        try {
            session = MyBatisUtil.createSeqSession();
            User u = (User) session.selectOne(User.class.getName() + ".load",
                    5);
            System.out.println(u.toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MyBatisUtil.closeSeqSession(session);
        }
    }

    @Test
    public void listTest() {
        SqlSession session = null;
        try {
            session = MyBatisUtil.createSeqSession();
            List<User> us = session.selectList(User.class.getName() + ".list",
                    null);
            System.out.println(us.size());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            MyBatisUtil.closeSeqSession(session);
        }
    }
}

运行FirstMybatisTest.java之前,数据库

 

运行junit

运行后数据库

源代码下载:http://download.csdn.net/detail/chenwei1510347223/7331529