1. 程式人生 > >Mybatis第一個專案嘗試(附程式碼)

Mybatis第一個專案嘗試(附程式碼)

一、專案佈局如下:

我在mysql資料庫建立的資料庫名為:mybatis

在mybatis建立了一個表,名為users

二、sql檔案users.sql內容如下:

DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
  `uid` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`uid`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

INSERT INTO `users` VALUES ('1', 'zhangsan', '123456');
INSERT INTO `users` VALUES ('2', 'lisi', '123456');
INSERT INTO `users` VALUES ('3', 'wangwu', '123456');
INSERT INTO `users` VALUES ('4', 'zhaoliiu', '123456');
INSERT INTO `users` VALUES ('5', 'zhuqi', '123456');

三、專案原始碼(mybatis 與jdbc     jar 包請自己下載)

1、mybatis主配置檔案  mybatisConfig.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>
    <typeAliases>
        <typeAlias type="entity.User" alias="users" />
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver" />
                <!-- ?useUnicode=true&amp;characterEncoding=utf8為了支援中文資料的寫入 -->
                <property name="url"
                    value="jdbc:mysql://127.0.0.1:3306/mybatis?useSSL=FALSE&amp;serverTimezone=UTC&amp;useUnicode=true&amp;characterEncoding=utf8" />
                <property name="username" value="root" />
                <property name="password" value="luhe19971011" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/userMapper.xml" />
    </mappers>
</configuration>

2、對映檔案userMapper.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="User">
    <resultMap type="entity.User" id="UserResult">
    <id column="uid" javaType="Integer" property="uid"></id>
    <result column="username" jdbcType="VARCHAR" property="username"></result>
    <result column="password" jdbcType="VARCHAR" property="password"></result>
    </resultMap>
    <select id="queryAllUser" resultMap="UserResult">
        select uid, username,password from users where 1=1
    </select>
</mapper>

3、資料庫訪問連結類 dbUtil.java如下

package dbUtil;

import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class dbUtil {
    private static final String CONFIG_PATH = "config/mybatisConfig.xml";

    /*
     * 獲取資料庫訪問連結
     */
    public static SqlSession getSqlSession() {
        SqlSession session = null;
        try {
            InputStream stream = Resources.getResourceAsStream(CONFIG_PATH);
            // 可以根據配置的相應環境讀取相應的資料庫環境
            // SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(
            // stream, "development");
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(stream);
            session = factory.openSession();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return session;
    }

    /*
     * 獲取資料庫訪問連結
     */
    public static void closeSession(SqlSession session) {
        session.close();
    }
}
4、實體類User.java內容如下:

package entity;

public class User {
    private int uid;
    private String username;
    private String password;
    public int getUid() {
        return uid;
    }
    public void setUid(int uid) {
        this.uid = uid;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    @Override
    public String toString() {
        return "User [uid=" + uid + ", username=" + username + ", password=" + password + "]";
    }
    
    
}
5、測試類testMybatis.java

package test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import entity.User;
import org.apache.ibatis.session.SqlSession;

import dbUtil.dbUtil;

public class testMybatis {

    public static void main(String[] args) throws IOException {
        SqlSession session=null;
        List<User> list=new ArrayList<User>();
        session=dbUtil.getSqlSession();
        list=session.selectList("User.queryAllUser");
        for(User user:list) {
            System.out.println(user);
        }
    }
}
四、測試類執行結果如下: