1. 程式人生 > >MyBatis 入門(一)--建立資料庫連線及基本操作

MyBatis 入門(一)--建立資料庫連線及基本操作

一、 資料庫建表

CREATE TABLE `user` (
  `userId` int(11) NOT NULL AUTO_INCREMENT,
  `UserName` varchar(45) NOT NULL,
  `UserEmail` varchar(200) NOT NULL,
  PRIMARY KEY (`userId`),
  UNIQUE KEY `userId_UNIQUE` (`userId`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

二、maven配置

     <dependencies
>
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.6</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId
>
junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version
>
</dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.2</version> </dependency> </dependencies>

三、mybasit 配置

  1. jdbc.properties 配置 資料連線
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8&useSSL=true&serverTimezone=UTC
username=mybatis
password=mybatis
maxActive= 50
  1. mybatis-config.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="jdbc.properties" />   

    <environments default="dev">
        <environment id="dev">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${driver}" />
                <property name="url" value="${url}" />
                <property name="username" value="${username}" />
                <property name="password" value="${password}" />
            </dataSource>
        </environment>
    </environments>
    <mappers>

    </mappers>
</configuration>

四、建立User的POJO

package com.elements.user.model;

public class User {

    public int getUserId() {
        return userId;
    }
    public void setUserId(int userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return UserName;
    }
    public void setUserName(String userName) {
        UserName = userName;
    }
    public String getUserEmail() {
        return UserEmail;
    }
    public void setUserEmail(String userEmail) {
        UserEmail = userEmail;
    }
    private int userId;
    private String UserName;
    private String UserEmail;


    @Override
    public String toString() {
        return "User [userId=" + userId + ", UserName=" + UserName
                + ", UserEmail=" + UserEmail + "]";
    }


}

五、 UserMapper配置檔案

  • 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="com.elements.user.mapper">

  <resultMap type="com.elements.user.model.User" id="usermap">
        <id column="userId" property="userId"/>
        <result column="UserName" property="UserName"/>
        <result column="UserEmail" property="UserEmail"/>
    </resultMap>


    <select id="getAllUser" resultMap="usermap">
        select * from mybatis.user
    </select>

    <select id="getUserById" resultMap="usermap" parameterType="String">
        select * from mybatis.user where userId= #{userId}
    </select>


    <insert id="insert" parameterType="com.elements.user.model.User">
     insert into mybatis.user (UserName, UserEmail) values (
          #{UserName}, #{UserEmail}
     )
    </insert>

    <update id="update" parameterType="com.elements.user.model.User">
     update mybatis.user set UserName=#{UserName},
     UserEmail=#{UserEmail}
     where userId= #{userId}
    </update>

    <delete id="delete" parameterType="String">
     delete mybatis.user where userId= #{userId}
    </delete>

</mapper>
  • 將配置檔案加入mybatis-config.xml的 mappers中
    <mappers>

    <mapper resource="com/elements/user/mapper/UserMapper.xml" />

    </mappers>

六、 建立測試類

public class TestUser {

    @Test
    public void TestSelectAll() throws IOException {
        //
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                .build(inputStream);

        SqlSession session = sqlSessionFactory.openSession();
        try {

            List<User> userlist = session
                    .selectList("com.elements.user.mapper.getAllUser");

            System.out.print(userlist);

        }catch(Exception e){
            System.out.print(e);
        }
        finally {
            session.close();
        }

    }

    @Test
    public void TestSelect() throws IOException {
        //
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                .build(inputStream);

        SqlSession session = sqlSessionFactory.openSession();
        try {
            User user = (User) session.selectOne(
                    "com.elements.user.mapper.getUserById", "1");

            System.out.print(user);

        } finally {
            session.close();
        }

    }

    @Test
    public void TestInsert() throws IOException {

        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                .build(inputStream);

        SqlSession session = sqlSessionFactory.openSession();
        try {
            User user = new User();
            user.setUserName("abc");
            user.setUserEmail("aaaaa");

            session.update("com.elements.user.mapper.insert", user);

            session.commit();

        } finally {
            session.close();
        }

    }

    @Test
    public void TestUpdate() throws IOException {

        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                .build(inputStream);

        SqlSession session = sqlSessionFactory.openSession();
        try {
            User user = new User();
            user.setUserId(7);
            user.setUserName("aaaaa");
            user.setUserEmail("aaaaa");

            session.update("com.elements.user.mapper.update", user);

            session.commit();

        } finally {
            session.close();
        }

    }

}