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.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.2.6version>
        dependency>

        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
            <scope>testscope>
        dependency>

        <dependency>
            <groupId>c3p0groupId>
            <artifactId>c3p0artifactId>
            <version>0.9.1.2version>
        dependency>

        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>6.0.2version>
        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



<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 配置文件


<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 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();
        }

    }

}

项目代码下载:http://pan.baidu.com/s/1kUGD61D

你可能感兴趣的:(mybatis)