mybatis -- helloworld

這裏寫圖片描述

加入jar包
加入mybatis核心包、依賴包、數據驅動包。
這裏寫圖片描述

log4j.properties
在classpath下創建log4j.properties如下:

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

mybatis默認使用log4j作爲輸出日誌信息。

SqlMapConfig.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>
    <!-- 和spring整合後 environments配置將廢除-->
    <environments default="development">
        <environment id="development">
        <!-- 使用jdbc事務管理-->
            <transactionManager type="JDBC" />
        <!-- 數據庫連接池-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=utf-8" />
                <property name="username" value="root" />
                <property name="password" value="111111" />
            </dataSource>
        </environment>
    </environments>

    <!-- 加載映射文件 -->
    <mappers>
        <mapper resource="sqlmap/Users.xml"/>
        <mapper resource="sqlmap/UserMapper.xml"/>
    </mappers>



</configuration>

po類

package cn.sjtu.mybatis;

import java.util.Date;

public class User {
    private int id;
    private String username;// 用戶姓名
    private String sex;// 性別
    private Date birthday;// 生日
    private String address;// 地址
    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 getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }

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

}

映射文件
在classpath下的sqlmap目錄下創建sql映射文件Users.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="test">
    <!-- 根據id獲取用戶信息 -->
    <select id="findUserById" parameterType="int" resultType="cn.sjtu.mybatis.User">
        select * from user where id = #{id}
    </select>
    <!-- 自定義條件查詢用戶列表 -->
    <select id="findUserByUsername" parameterType="java.lang.String" resultType="cn.sjtu.mybatis.User">
       select * from user where username like '%${value}%' 
    </select>

    <!-- 添加用戶 -->
    <insert id="insertUser" parameterType="cn.sjtu.mybatis.User">
    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
        select LAST_INSERT_ID() 
    </selectKey>
      insert into user(username,birthday,sex,address) 
      values(#{username},#{birthday},#{sex},#{address})
    </insert>

    <!-- 刪除用戶 -->
    <delete id="deleteUserById" parameterType="int">
        delete from user where id=#{id}
    </delete>

</mapper>

加載映射文件
mybatis框架需要加載映射文件,將Users.xml添加在SqlMapConfig.xml,如下:

<mappers>
        <mapper resource="sqlmap/User.xml"/>
</mappers>

測試程序

package cn.sjtu.mybatis.test;

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

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.Test;

import cn.sjtu.mybatis.User;

public class MybatisTest1 {

    // 根據 id查詢用戶信息
    @Test
    public void testFindUserById() throws IOException {
        // 配置文件
        String resource = "SqlMapConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);

        // 使用SqlSessionFactoryBuilder從xml配置文件中創建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                        .build(inputStream);

        // 數據庫會話實例
        SqlSession sqlSession = null;
        try {
            // 創建數據庫會話實例sqlSession
            sqlSession = sqlSessionFactory.openSession();
            // 查詢單個記錄,根據用戶id查詢用戶信息
            User user = sqlSession.selectOne("test.findUserById", 10);
            // 輸出用戶信息
            System.out.println(user);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }

    }

    // 根據用戶名稱模糊查詢用戶信息
    @Test
    public void testFindUserByUsername() throws IOException {

        // 配置文件
        String resource = "SqlMapConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);

        // 使用SqlSessionFactoryBuilder從xml配置文件中創建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                        .build(inputStream);
        // 數據庫會話實例
        SqlSession sqlSession = null;
        try {
            // 創建數據庫會話實例sqlSession
            sqlSession = sqlSessionFactory.openSession();
            // 查詢單個記錄,根據用戶id查詢用戶信息
            List<User> list = sqlSession.selectList("test.findUserByUsername", "張");
            System.out.println(list.size());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }

    }

    // 添加用戶信息
    @Test
    public void testInsert() throws IOException {
        // 配置文件
        String resource = "SqlMapConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);

        // 使用SqlSessionFactoryBuilder從xml配置文件中創建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                        .build(inputStream);

        // 數據庫會話實例
        SqlSession sqlSession = null;
        try {
            // 創建數據庫會話實例sqlSession
            sqlSession = sqlSessionFactory.openSession();
            // 添加用戶信息
            User user = new User();
            user.setUsername("張大");
            user.setAddress("河南鄭州");
            user.setSex("1");
            user.setBirthday(new Date());
            sqlSession.insert("test.insertUser", user);
            //提交事務
            sqlSession.commit();
            System.out.println(user.getId()); //獲取新增記錄的id值
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }


    // 根據id刪除用戶
    @Test
    public void testDelete() throws IOException {
        // 配置文件
        String resource = "SqlMapConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);

        // 使用SqlSessionFactoryBuilder從xml配置文件中創建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                        .build(inputStream);

        // 數據庫會話實例
        SqlSession sqlSession = null;
        try {
            // 創建數據庫會話實例sqlSession
            sqlSession = sqlSessionFactory.openSession();
            // 刪除用戶
            sqlSession.delete("test.deleteUserById",27);
            // 提交事務
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }
}

Mapper動態代理方式
Mapper接口開發方法只需要程序員編寫Mapper接口(相當於Dao接口),由Mybatis框架根據接口定義創建接口的動態代理對象,代理對象的方法體同上邊Dao接口實現類方法。
Mapper接口開發需要遵循以下規範:
1、 Mapper.xml文件中的namespace與mapper接口的類路徑相同。
2、 Mapper接口方法名和Mapper.xml中定義的每個statement的id相同
3、 Mapper接口方法的輸入參數類型和mapper.xml中定義的每個sql 的parameterType的類型相同
4、 Mapper接口方法的輸出參數類型和mapper.xml中定義的每個sql的resultType的類型相同

定義mapper映射文件UserMapper.xml
(內容同Users.xml),需要修改namespace的值爲 UserMapper接口路徑。

<?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="cn.sjtu.mybatis.UserMapper">
    <!-- 根據id獲取用戶信息 -->
    <select id="findUserById" parameterType="int" resultType="cn.sjtu.mybatis.User">
        select * from user where id = #{id}
    </select>
    <!-- 自定義條件查詢用戶列表 -->
    <select id="findUserByUsername" parameterType="java.lang.String" resultType="cn.sjtu.mybatis.User">
       select * from user where username like '%${value}%' 
    </select>

    <!-- 添加用戶 -->
    <insert id="insertUser" parameterType="cn.sjtu.mybatis.User">
    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
        select LAST_INSERT_ID() 
    </selectKey>
      insert into user(username,birthday,sex,address) 
      values(#{username},#{birthday},#{sex},#{address})
    </insert>

    <!-- 刪除用戶 -->
    <delete id="deleteUserById" parameterType="int">
        delete from user where id=#{id}
    </delete>

</mapper>

UserMapper.java(接口文件)

package cn.sjtu.mybatis;

import java.util.List;

public interface UserMapper {
    //根據用戶id查詢用戶信息
    public User findUserById(int id) throws Exception;
    //查詢用戶列表
    public List<User> findUserByUsername(String username) throws Exception;
    //添加用戶信息
    public void insertUser(User user) throws Exception; 

}

加載UserMapper.xml文件
修改SqlMapConfig.xml文件:

<!-- 加載映射文件 -->
    <mappers>
        <mapper resource="sqlmap/UserMapper.xml"/>
    </mappers>

測試

package cn.sjtu.mybatis.test;

import static org.junit.Assert.*;

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

import cn.sjtu.mybatis.User;

public class UserMapperTest {

    // 根據 id查詢用戶信息
    @Test
    public void testFindUserById() throws IOException {
        // 配置文件
        String resource = "SqlMapConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);

        // 使用SqlSessionFactoryBuilder從xml配置文件中創建SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                        .build(inputStream);

        // 數據庫會話實例
        SqlSession sqlSession = null;
        try {
            // 創建數據庫會話實例sqlSession
            sqlSession = sqlSessionFactory.openSession();
            // 查詢單個記錄,根據用戶id查詢用戶信息
            User user = sqlSession.selectOne("cn.sjtu.mybatis.UserMapper.findUserById", 10);
            // 輸出用戶信息
            System.out.println(user);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }

    }

}
發佈了227 篇原創文章 · 獲贊 24 · 訪問量 32萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章