Mybatis入門程序

2016-11-18_235500.png

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事務(wù)管理-->
            <transactionManager type="JDBC" />
        <!-- 數(shù)據(jù)庫連接池-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:8010/test?characterEncoding=utf-8" />
                <property name="username" value="root" />
                <property name="password" value="wazl2012" />
            </dataSource>
        </environment>
    </environments>
    <!-- 加載映射文件 -->
    <mappers>
        <mapper resource="sqlmap/User.xml"/>
    </mappers>
</configuration>

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="test">
    <!-- 
          需求:根據(jù)id獲取用戶信息
         id:表示表示映射文件中的sql,將sql語句封裝到mappedStatement對(duì)象中,將id稱為Statement的 id
         parameterType:指定出入?yún)?shù)類型
         resultType:指定輸出參數(shù)類型
         #{}表示一個(gè)占位符
         #{id}接收輸入?yún)?shù),參數(shù)名為id,如果輸入的是簡單類型,#{}中的參數(shù)名可以任意
    -->
    <select id="findUserById" parameterType="int" resultType="cn.ztc.mybatis.po.User">
        select * from user where id = #{id}
    </select>
    
    <!-- 
        需求:自定義條件查詢用戶列表 ,可能返回多條數(shù)據(jù)
        resultType:指定的就是單條記錄所使用的java對(duì)象類型
        ${}表示拼接sql串,將接收到的參數(shù)不加任何修飾拼接在sql串中
        使用${}可能會(huì)引起sqk注入
        ${value}接收輸入?yún)?shù),如果輸入的是簡單類型,#{}中的參數(shù)名只能是value
    -->
    <select id="findUserByName" parameterType="java.lang.String" resultType="cn.ztc.mybatis.po.User">
        select * from user where username like '%${value}%'
    </select>
    
    <!-- 
        添加用戶
        parameterType:輸入?yún)?shù)類型是pojo
        #{}中指定pojo的屬性名
     -->
    <insert id="insertUser" parameterType="cn.ztc.mybatis.po.User">
        <!-- 
            將插入數(shù)據(jù)庫的主鍵返回到對(duì)象中
            select LAST_INSERT_ID():得到insert記錄的主鍵值,只適用于自增主鍵
            keyProperty:將查詢到的主鍵值設(shè)置到parameterType指定對(duì)象的某個(gè)屬性
            order:相對(duì)于insert語句來說,select LAST_INSERT_ID()的執(zhí)行順序
         -->
        <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})
        <!-- 
            使用mysql的uuid生成主鍵
            執(zhí)行過程:
            首先用過uuid()得到主鍵,將主鍵設(shè)置到user對(duì)象的id屬性中
            其次在執(zhí)行insert,從user對(duì)象中取出id屬性值
         -->
         <!-- <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String">
            select uuid()
        </selectKey>
        insert into user (id,username,birthday,sex,address) values (#{id},#{username},#{birthday},#{sex},#{address}) -->
    </insert>
    
    <!-- 刪除用戶 -->
    <delete id="deleteUser" parameterType="java.lang.Integer">
        delete from user where id=#{id}
    </delete>
    
    <!-- 
        更新用戶 
        #{id}:對(duì)應(yīng)pojo的屬性值
    -->
    <update id="updateUser" parameterType="cn.ztc.mybatis.po.User">
        update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id = #{id}
    </update>
</mapper>

User.java

package cn.ztc.mybatis.po;

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 + "]";
    }
    
}

MybatisFirst.java

package cn.ztc.mybatis.first;

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.ztc.mybatis.po.User;

public class MybatisFirst {

    @Test
    public void findUserByIdTest() throws IOException{
        String resource = "SqlMapConfig.xml";
        //得到配置文件流
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //創(chuàng)建會(huì)化工廠
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //通過sqlSession操作數(shù)據(jù)庫
        //第一個(gè)參數(shù):映射文件中的[namespace].[statement id]
        //第二個(gè)參數(shù):映射文件中匹配的resultType類型的對(duì)象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //selectOne:查一條記錄
        User user = sqlSession.selectOne("test.findUserById", 1);
        
        System.out.println(user);
        
        sqlSession.close();
    }
    
    @Test
    public void findUserByNameTest() throws IOException {
        String resource = "SqlMapConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        List<User> list = sqlSession.selectList("test.findUserByName", "小明");
        System.out.println(list);
        sqlSession.close();
    }
    
    @Test
    public void insertUserTest() throws IOException {
        String resource = "SqlMapConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        User user = new User();
        user.setUsername("王小軍");
        user.setBirthday(new Date());
        user.setSex("1");
        user.setAddress("上海");
        sqlSession.insert("test.insertUser", user);
        
        sqlSession.commit();
        System.out.println(user.getId());
        sqlSession.close();
    }
    
    @Test
    public void deleteUserTest() throws IOException {
        String resource = "SqlMapConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        
        sqlSession.delete("test.deleteUser", 27);
        
        sqlSession.commit();
        sqlSession.close();
    }
    
    @Test
    public void updateUserTest() throws IOException {
        String resource = "SqlMapConfig.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        User user = new User();
        user.setId(24);
        user.setUsername("張四豐");
        user.setBirthday(new Date());
        user.setSex("1");
        user.setAddress("上海");
        sqlSession.update("test.updateUser", user);
        
        sqlSession.commit();
        sqlSession.close();
    }

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容