mybatis基礎之一

露水上的青蛙發表於2017-09-01

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/spring?characterEncoding=utf-8" />
                <property name="username" value="root" />
                <property name="password" value="123456" />
            </dataSource>
        </environment>
    </environments>
    <!-- 載入對映檔案 -->
    <mappers>
       <mapper resource="sqlmap/Uers.xml"/>
    </mappers>
</configuration>

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">
<!-- namespace名稱空間,就是對sql進行分類化管理 理解sql隔離 -->
<mapper namespace="test">
   <!-- 在對映檔案中配置sql語句 -->
   <!-- 通過ID查詢sql記錄 -->
   <!-- 通過select來執行查詢
   id: 標識對映檔案中的sql 稱為statement的id
           將sql語句封裝到mappedStatement中
   parameterType:指定輸入引數的型別 ,這裡指定int型
   #{}表示一個佔位符
   #{id} 表示接收輸入的引數  id就是輸入的引數名稱
   resultTypeL: 指定sql輸出結果的javadui型別
     -->
   <select id="findUserById" parameterType="int" resultType="com.liu.mybatis.po.User">
      SELECT * FROM USER WHERE id = #{id}
   </select>
   <!-- ${}是一個拼接符號 -->
   <select id="findUserByName" parameterType="java.lang.String" resultType="com.liu.mybatis.po.User">
      SELECT * FROM USER WHERE username like '%${value}%'
   </select>
   
   <!-- selectkey獲取自增主鍵 -->
   <insert id="insertUser" parameterType="com.liu.mybatis.po.User">
      <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
        SELECT LAST_INSERT_ID()
      </selectKey>
      insert into user(username,birthday,sex,address) value(#{username},#{birthday},#{sex},#{address})
   </insert>
   <delete id="deleteUser" parameterType="java.lang.Integer">
      delete from user where id = #{id}
   </delete>
   <update id="updateUser" parameterType="com.liu.mybatis.po.User">
      update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}
   </update>
</mapper>

User.java

package com.liu.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 + ", sex=" + sex
                + ", birthday=" + birthday + ", address=" + address + "]";
    }
}

MybatisFirst.java

package com.liu.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 com.liu.mybatis.po.User;

public class MybatisFirst {
    
    @Test
    public void findUserByIdTest() throws IOException{
        //得到mybatis配置檔案
        
        String resource = "SqlMapConfig.xml";
        //得到配置檔案流
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //建立會話工廠
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        
        //通過工廠得到sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        
        //通過sqlSession運算元據庫
        User user = sqlSession.selectOne("test.findUserById", 1);
        System.out.println(user);
        
        List<User> list = sqlSession.selectList("test.findUserByName", "明");
        System.out.println(list);
        
        User user2 = new User();
        user2.setId(28);
        user2.setUsername("王曉春三個混蛋");
        user2.setBirthday(new Date());
        user2.setSex("男");
        user2.setAddress("安微合肥");
        
        /*sqlSession.insert("test.insertUser", user2);*/
        sqlSession.update("test.updateUser", user2);
        /*sqlSession.delete("test.deleteUser", user2);*/
        
        sqlSession.commit();
        sqlSession.close();
    }
}

 

相關文章