SQL极简教程 · MySQL · MyBatis · JPA 技术笔记 教程 总结

Mybatis搭建环境(2)

2018-08-30  本文已影响6人  LeaveStyle

内容接上一篇文章:Mybatis入门学习(1)

1. 数据库准备(Mysql)

CREATE DATABASE mybatis_test;
USE mybatis_test;
DROP TABLE IF EXISTS user;
CREATE TABLE user (
    id INT(11) NOT NULL AUTO_INCREMENT,
    username VARCHAR(120) COLLATE utf8_bin DEFAULT NULL,
    password VARCHAR(50) COLLATE utf8_bin DEFAULT NULL,
    gender VARCHAR(5) COLLATE utf8_bin DEFAULT NULL,
    email VARCHAR(100) COLLATE utf8_bin DEFAULT NULL,
    province VARCHAR(50) COLLATE utf8_bin DEFAULT NULL,
    city VARCHAR(50) COLLATE utf8_bin DEFAULT NULL,
    birthday DATE DEFAULT NULL,
    PRIMARY KEY (id)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

INSERT INTO user (id, username, password, gender, email, province, city, birthday) values
(1, '张三', '111', '男', '1111@126.com', '河南省', '郑州市', '1991-04-23'),
(2, '李四', '222', '男', '2222@126.com', '河北省', '邯郸市', '1989-10-13'),
(3, '刘丽', '333', '女', '3333@126.com', '江苏省', '苏州市', '1994-06-09'),
(4, '李丽', '444', '女', '4444@126.com', '四川省', '成都市', '1992-11-07');

user数据表信息.png

2. 新建web工程和配置

使用Intelij idea新建web项目流程
MyBatis和数据库驱动等各种的jar包自行下载。 jar包下载集中地

依赖的jar包.png
工程目录结构图.png

3. 编写日志输出环境配置文件

在log4j.properties文件中编写以下信息

# Global logging configuration
# 在开发环境下日志级别要设成DEBUG,生产环境设为INFO或ERROR
log4j.rootLogger = DEBUG, stdout
# Console output...
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %5p [%t] - %m%n

4. 编写数据库连接池配置文件(例子为:SqlMapConfig.xml)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    <!--和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/mybatis_test?characterEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

     <mappers>
        <mapper resource="classpath:mapper/UserMapper.xml"/>
    </mappers>
</configuration>

5. 编写SQL映射配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybtis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="test">
    <select id="findUserById" parameterType="int" resultType="cn.com.mybatis.po.User">
        SELECT * FROM USER WHERE id=#{id}
    </select>
</mapper>

此时我这里老是id报错,提示找不到该id,所以在这里添加一个dao层,cn.com.mybatis.dao包,用来存放dao层接口。

package cn.com.mybatis.dao;

import cn.com.mybatis.po.User;
public interface UserDao {
    User findUserById(int id);
}

在MyBatis中,Mapper中的namespace用于绑定Dao接口的,即面向接口编程。
它的好处在于当使用了namespace之后就可以不用写接口实现类,业务逻辑会直接通过这个绑定寻找到相对应的SQL语句进行对应的数据处理。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybtis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="cn.com.mybatis.dao">
    <select id="findUserById" parameterType="int" resultType="cn.com.mybatis.po.User">
        SELECT * FROM USER WHERE id=#{id}
    </select>
</mapper>

在SqlMapConfig.xml配置文件中添加映射

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

6. 编写数据交互类和测试用例

package cn.com.mybatis.po;

import java.io.Serializable;
import java.util.Date;

public class User implements Serializable{
    private int id;
    private String username;
    private String password;
    private String gender;
    private String email;
    private String province;
    private String city;
    private Date birthday;

    public User(){
    }

    public User(int id, String username, String password, String gender, String email, String province, String city, Date birthday){
        super();
        this.id = id;
        this.username = username;
        this.password = password;
        this.gender = gender;
        this.email = email;
        this.province = province;
        this.city = city;
        this.birthday = birthday;
    }

    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 getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
}

在cn.com.mybatis.datasource包中创建DataConnection.java类, 通过Resource资源加载类加载SqlMapConfig.xml配置文件,然后获取SQL会话工厂SqlSessionFactory,之后使用会话工厂创建可以与数据库交互的sqlSession类的实例对象。

package cn.com.mybatis.datasource;

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 java.io.IOException;
import java.io.InputStream;

public class DataConnection {
    //配置文件
    private String resource = "SqlMapConfig.xml";
    private SqlSessionFactory sqlSessionFactory;
    private SqlSession sqlSession;

    public SqlSession getSqlSession() throws IOException{
        InputStream inputStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
    }
}

下面编写测试用例,该类需要从数据库中取出id为1的用户的数据,并在控制台中打印出来,这里命名该测试类为MyBatisTest,相关代码如下:

package cn.com.mybatis.test;

import cn.com.mybatis.datasource.DataConnection;
import cn.com.mybatis.po.User;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;
import java.text.SimpleDateFormat;

public class MyBatisTest {

    public DataConnection dataConn = new DataConnection();

    @Test
    public void TestSelect() throws IOException{
        SqlSession sqlSession = dataConn.getSqlSession();
        //sqlSession.selectOne最终结果与映射文件中所匹配的resultType类型
        User user= sqlSession.selectOne("cn.com.mybatis.dao.findUserById",1);


        System.out.println("姓名:"+user.getUsername());
        System.out.println("性别:"+user.getGender());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println("生日:"+sdf.format(user.getBirthday()));
        System.out.println("所在地:"+user.getProvince()+user.getCity());

        sqlSession.close();;
    }
}

然后执行Junit单元测试,得到理想结果。


结果.png
上一篇下一篇

猜你喜欢

热点阅读