Mybatis使用与入门案例

前置环境

创建数据库表并添加数据:

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
  `id` int(11) NOT NULL auto_increment,
  `username` varchar(32) NOT NULL COMMENT '用户名称',
  `birthday` datetime default NULL COMMENT '生日',
  `sex` char(1) default NULL COMMENT '性别',
  `address` varchar(256) default NULL COMMENT '地址',
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert  into `user`(`id`,`username`,`birthday`,`sex`,`address`) values 
(41,'老王','2018-02-27 17:47:08','男','北京'),
(42,'小二王','2018-03-02 15:09:37','女','北京金燕龙'),
(43,'小二王','2018-03-04 11:34:34','女','北京金燕龙'),
(45,'传智播客','2018-03-04 12:04:06','男','北京金燕龙'),
(46,'老王','2018-03-07 17:37:26','男','北京'),
(48,'小马宝莉','2018-03-08 11:44:00','女','北京修正');

项目结构

Mybatis使用与入门案例

配置文件

[db.properties]
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://192.168.91.1:3306/test?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
username=root
password=123456
[mybatis.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="db.properties"/>
    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    <typeAliases>
        <package name="com.rhett.domain"></package>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <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>
        <mapper resource="com/rhett/dao/IUserDao.xml"/>
    </mappers>
</configuration>

添加JavaBean

在domain下编写bean:

package com.rhett.domain;

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

public class User implements Serializable {
    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", birthday=" + birthday
                + ", sex=" + sex + ", address="
                + address + "]";
    }
}

编写Mapper

首先编写接口类IuserDao:

package com.rhett.dao;

import com.rhett.domain.User;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface IUserDao {
    /**
     * 查询所有操作
     */
    List<User> findAll();
}

然后在resources和包对应的相同文件夹下编写mapper的xml配置(IUserDao.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="com.rhett.dao.IUserDao">
    <!-- 配置查询所有操作 -->
    <select id="findAll" resultType="User">
    select * from user
    </select>
</mapper>

然后在mybatis.xml文件中配置mapper(见上面的配置,我用了包扫描)

编写测试类

package test;

import com.rhett.dao.IUserDao;
import com.rhett.domain.User;
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;
import java.util.List;

public class MybatisTest {

    public static void main(String[] args) throws IOException {
        // 1.读取配置文件
        InputStream in = Resources.getResourceAsStream("mybatis.xml");
        // 2.创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        // 3.使用工厂生成SqlSession对象
        SqlSession session = factory.openSession();
        // 4.使用SqlSession创建Dao接口的代理
        IUserDao userDao = session.getMapper(IUserDao.class);
        // 5.使用代理对象执行方法
        List<User> users = userDao.findAll();
        for(User user:users){
            System.out.println(user);
        }
        // 6.释放资源
        session.close();
        in.close();
    }
}

输出:

User [id=41, username=老王, birthday=Wed Feb 28 07:47:08 CST 2018, sex=男, address=北京]
User [id=42, username=小二王, birthday=Sat Mar 03 05:09:37 CST 2018, sex=女, address=北京金燕龙]
User [id=43, username=小二王, birthday=Mon Mar 05 01:34:34 CST 2018, sex=女, address=北京金燕龙]
User [id=45, username=传智播客, birthday=Mon Mar 05 02:04:06 CST 2018, sex=男, address=北京金燕龙]
User [id=46, username=老王, birthday=Thu Mar 08 07:37:26 CST 2018, sex=男, address=北京]
User [id=48, username=小马宝莉, birthday=Fri Mar 09 01:44:00 CST 2018, sex=女, address=北京修正]

补充:基于注解的修改方法

在编写接口的时候加上注解:

public interface IUserDao {
    /*
    * 查询所有用户
    */
    @Select("select * from user")
    List<User> findAll();
}

然后修改mybatis.xml

<!-- 告知 mybatis 映射配置的位置 -->
<mappers>
    <mapper class="com.itheima.dao.IUserDao"/>
</mappers>

就可以不用IUserDao.xml了。

原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/mybatis%e4%bd%bf%e7%94%a8%e4%b8%8e%e5%85%a5%e9%97%a8%e6%a1%88%e4%be%8b/

发表评论

电子邮件地址不会被公开。