Mybatis基础-完整CRUD操作

步骤一:mybatis基本配置

1)创建Java项目,在lib下导入mybatis所需要的Jar包,包括链接mysql的mysql-connector-java-5.1.7-bin.jar。

2)在src目录下新建一个mybatis的配置文件

mybatis_conf.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="db.properties"></properties>

    <!-- 启用别名 -->
    <typeAliases>
        <package name="com.feng.domain" />
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driverClass}" />
                <property name="url" value="${jdbc.jdbcUrl}" />
                <property name="username" value="${jdbc.user}" />
                <property name="password" value="${jdbc.password}" />
            </dataSource>
        </environment>
    </environments>
    <!-- 配置 自动扫描 包下的 sql映射文件-->
    <mappers>
        <package name="com.feng.dao" />
    </mappers>
</configuration>

 db.properties

jdbc.user = root
jdbc.password=123456
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://127.0.0.1:3306/mybatis0814?useUnicode=true&characterEncoding=utf-8

步骤二:

1)新建表t_user,因为Mybatis不会自动创建数据表,和hibernate不一样,只专注sql

2)定义表的实体类,必须一一对应,否则需要在映射里面设置resultMap结果集映射

User

package com.feng.domain;

import java.util.Date;

public class User
{
    // 和表中的字段一一对应,否则需要在对应的Mapper配置文件用到resultMap结果集映射。
    private Integer id;
    private String username;
    private int age;
    private Date registerDate;
    
    public User(){}

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Date getRegisterDate() {
        return registerDate;
    }

    public void setRegisterDate(Date registerDate) {
        this.registerDate = registerDate;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", age=" + age
                + ", registerDate=" + registerDate + "]";
    }

 3)在dao的包下,新建sql映射配置xml

UserMapper.xml   必须和实体类对应  格式:实体类+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">
<!-- 完整namespace,取包名+映射文件 -->
<mapper namespace="com.feng.dao.UserMapper">
<!-- 对应的id为映射接口的方法 ,parameterType 设置为入参的类型,因为我在配置文件中启用了别名,自动扫描domain包,所以不需要写包名,如果没有就是com.feng.domain.User
    resultType就是返回的结果集类型,如果是基本类型,mybaits已经封装好了,直接写类型就好;如果是实体类,就要写上实体类的类型,也是可以别名的。
    useGeneratedKeys="true" keyProperty="id"   :启用这段后,可以得到新增的数据的主键id
    #{}里面新增的实体属性值,用#{},也可以用${value};推荐用#{},因为会自动使用parperstatement,防止sql注入
-->
    <insert id="addUser" parameterType="User"  useGeneratedKeys="true" keyProperty="id">
        insert into t_user(username,age,registerDate)
        values(#{username},#{age},#{registerDate})
    </insert>
    <delete id = "deleteUser" parameterType="Integer"  >
        delete from t_user where id = #{id}
    </delete>
    <update id = "updateUser" parameterType="User" >
        update t_user 
        set 
            username = #{username},age=#{age},registerDate=#{registerDate}
        where 
             id = #{id}
    </update>
    <!-- 多个数据 和 单个 数据 ,他们的类型都是一样,都是User -->
    <select id = "getUserById" parameterType="Integer" resultType = "User">
        select * from t_user where id = #{id}
    </select>
    <select id = "getAllUser" resultType="User">
        select * from t_user
    </select>
    <select id = "getAllUser1" parameterType="map" resultType="User">
        select * from t_user where age > #{age} and username = #{username}
    </select>
</mapper>

这里注意一点,update、delete 返回值是:更新或删除的行数;无需指明resultClass;但如果有约束异常而删除失败,只能去捕捉异常。 

insert,返回值是:新插入行的主键(primary key);需要包含<selectKey>语句,才会返回主键,否则返回值为null。

4)操作接口

UserMapper.java

package com.feng.dao;



import java.util.List;
import java.util.Map;

import com.feng.domain.User;

public interface UserMapper 
{
    //增加一个用户
    public void addUser(User user);
    
    //删除一个用户
    public void deleteUser(Integer id);
    
    //修改用户信息
    public void updateUser(User user);
    
    //得到一个用户
    public User getUserById(Integer id);
    
    //得到所有用户
    public List<User> getAllUser();
    
    // 多入参情况下用map
    public List<User> getAllUser1(Map<String, Object> map);

}

步骤三

1)新建测试类Test_Crud.java

package com.feng.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;

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 org.junit.Before;
import org.junit.Test;

import com.feng.domain.User;

public class Test_Crud {

    private SqlSessionFactory sqlSessionFactory = null;

    @Before
    public void init() throws IOException {
        // 使用MyBatis提供的Resources类加载mybatis的配置文件(它也加载关联的映射文件)
        InputStream inputStream = Resources
                .getResourceAsStream("mybatis_conf.xml");
        // 创建SqlSessionFactory工厂
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    @Test
    public void addUser() {
        // 创建并且打开sqlsession
        SqlSession sqlSession = null;
        try {

            sqlSession = sqlSessionFactory.openSession();
            User user = new User();
            user.setAge(22);
            user.setRegisterDate(new Date());
            user.setUsername("feng");
            sqlSession.insert("com.feng.dao.UserMapper.addUser", user);
            sqlSession.commit();
            System.out.println(user.getId());

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

    @Test
    public void deleteUser() {
        // 创建并且打开sqlsession
        SqlSession sqlSession = null;
        try {

            sqlSession = sqlSessionFactory.openSession();
            sqlSession.delete("com.feng.dao.UserMapper.deleteUser", 2);
            sqlSession.commit();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

    @Test
    public void updateUser() {
        // 创建并且打开sqlsession
        SqlSession sqlSession = null;
        try {

            sqlSession = sqlSessionFactory.openSession();
            User user = new User();
            user.setAge(22);
            user.setId(1);
            user.setRegisterDate(new Date());
            user.setUsername("wei");
            sqlSession.update("com.feng.dao.UserMapper.updateUser", user);
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

    @Test
    public void getUserById() {
        // 创建并且打开sqlsession
        SqlSession sqlSession = null;
        try {
            sqlSession = sqlSessionFactory.openSession();

            User user = sqlSession.selectOne(
                    "com.feng.dao.UserMapper.getUserById", 1);
            System.out.println(user.toString());
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

    @Test
    public void getAllUser() {
        // 创建并且打开sqlsession
        SqlSession sqlSession = null;
        try {
            sqlSession = sqlSessionFactory.openSession();

            java.util.List<User> list = sqlSession
                    .selectList("com.feng.dao.UserMapper.getAllUser");
            for (User user : list) {
                System.out.println(user.toString());
            }
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

    @Test
    // 多入参情况下,用map
    public void getAllUser1() {
        // 创建并且打开sqlsession
        SqlSession sqlSession = null;
        try {
            sqlSession = sqlSessionFactory.openSession();
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("age", 20);
            map.put("username", "feng");

            java.util.List<User> list = sqlSession.selectList(
                    "com.feng.dao.UserMapper.getAllUser1", map);
            for (User user : list) {
                System.out.println(user.toString());
            }
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

}

最后的结构图如下

 

posted @ 2018-08-16 15:03  镜湖月色  阅读(250)  评论(0编辑  收藏  举报