MyBatis學習筆記(一)

1、搭建測試工程:java

1.建立maven工程,pom.xml文件中添加以下依賴:mysql

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
</dependency>

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.6</version>
</dependency>

2.編寫核心配置文件conf.xmlsql

<?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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <!-- 配置數據庫鏈接信息 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/mysql" />
                <property name="username" value="root" />
                <property name="password" value="mysql" />
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="mapper/UserMapper.xml" />
    </mappers>

</configuration>

3.編寫實體對象類User.java數據庫

public class User {

    private int id;
    private String name;
    private int age;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

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

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

4.編寫mapper接口UserMapper.javamybatis

public interface UserMapper {

    /**
     * 查詢全部
     *
     * @return
     */
    List<User> queryAll();

    /**
     * 查詢用戶
     *
     * @return
     */
    User getUser(int id);

    /**
     * 插入一個
     *
     * @param user
     * @return
     */
    int insetUser(User user);

    /**
     * 修更名稱
     *
     * @param id
     * @param name
     * @return
     */
    int updateUser(@Param("id") int id, @Param("name") String name);

    /**
     * 根據Id刪除
     *
     * @param id
     * @return
     */
    int deleteUser(int id);
}

5.編寫UserMapper.xml文件app

<?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="com.sysware.mapper.UserMapper">

    <resultMap id="user" type="com.sysware.domain.User">
        <id property="id" column="id" javaType="int" jdbcType="INTEGER"/>
        <result property="name" column="name" javaType="string" jdbcType="VARCHAR"/>
        <result property="age" column="age" javaType="int" jdbcType="INTEGER"/>
    </resultMap>

    <!-- 在select標籤中編寫查詢的SQL語句, 設置select標籤的id屬性爲getUser,id屬性值必須是惟一的,不可以重複
    使用parameterType屬性指明查詢時使用的參數類型,resultType屬性指明查詢返回的結果集類型
    resultType="com.sysware.domain.User"就表示將查詢結果封裝成一個User類的對象返回
    User類就是users表所對應的實體類
    -->
    <!--
        根據id查詢獲得一個user對象
     -->
    <select id="getUser" parameterType="int"
            resultType="com.sysware.domain.User">
        select * from users where id=#{id}
    </select>
</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">

<mapper namespace="cn.itcast.mybatis.domain.User">
    <sql id="cols">
        id,name,age,address
    </sql>
    <sql id="ucols">
        name=#{name},age=#{age},address=#{address}
    </sql>

    <!-- 查詢全部記錄 -->
    <select id="listAll" resultType="xUser">
        select <include refid="cols"/> from user_c
    </select>

    <!-- 按條件查詢 -->
    <select id="find" parameterType="xUser" resultType="xUser">
        select * from user_c
        <where>
            <if test="name!=null">
                and name like "%"#{name}"%"
            </if>
            <if test="age!=null">
                and age=#{age}
            </if>
        </where>
    </select>

    <!-- 查詢一個用戶 -->
    <select id="get" parameterType="string" resultType="xUser">
        select <include refid="cols"/> from user_c where id=#{id}
    </select>

    <!-- 新增 -->
    <insert id="create" parameterType="xUser">
        insert into user_c (id,name,age,address) values(#{id},#{name},#{age},#{address})
    </insert>

    <!-- 修改 -->
    <update id="update" parameterType="xUser">
        update user_c
        <set>
            <if test="name!=null">
                name=#{name},
            </if>
            <if test="age!=null">
                age=#{age},
            </if>
            <if test="address!=null">
                address=#{address},
            </if>
        </set>

        where id=#{id}
    </update>

    <!-- 刪除 -->
    <delete id="delete" parameterType="string">
        delete from user_c where id=#{id}
    </delete>
</mapper>

 

6.編寫UserTest.java文件dom

public class UserTest {

    public static SqlSessionFactory sqlSessionFactory;

    @Before
    public void beforeTest(){
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder =
                new SqlSessionFactoryBuilder();
        try{
            sqlSessionFactory = sqlSessionFactoryBuilder.build(
                    Resources.getResourceAsStream("conf.xml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @AfterClass
    public static void setAfter() {
        sqlSessionFactory = null;
    }

    @Test
    public void testQueryAll(){
        SqlSession sqlSession = null;
        try{
            sqlSession = sqlSessionFactory.openSession();
            UserMapper userpMapper = sqlSession.getMapper(UserMapper.class);
            //List<User> list = userpMapper.queryAll();
            User user = userpMapper.getUser(1);
//            Iterator<User> iterator = list.iterator();
//            while(iterator.hasNext()){
//                System.out.println(user);
//            }
            System.out.println(user.toString());
        }finally {
            if(sqlSession!=null){
                sqlSession.close();
            }
        }
    }
}

8。項目整體目錄結構以下:maven

其中 SqlSessionFactoryBuilder 是一個關鍵的入口類,其中承擔了mybatis配置文件的加載,解析,內部構建等職責。ide

相關文章
相關標籤/搜索