mybatis入门——day01:通过xml来配置

1. 简介

mybatis入门——day01:通过xml来配置_第1张图片

  • 表现层:展示数据
  • 业务层:处理业务需求
  • 持久层:与数据库交互

mybatis官方地址:http://www.mybatis.org/mybatis-3/zh/getting-started.html

  • mybatis是一个持久层框架,封装了jdbc的细节,使我们只需关注sql语句本身,而无需关注注册驱动、创建连接等繁杂的过程。它使用了ORM思想
  • ORM(object relational mapping):对象关系映射。就是把数据库和实体类及实体类的属性对应起来,让我们可以操作实体类就实现操作数据库表

2. 配置一个简单案例的流程

整体结构如下:
mybatis入门——day01:通过xml来配置_第2张图片
① 创建maven工程,配置pom文件

    <packaging>jarpackaging>

    <dependencies>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.4.5version>
        dependency>

        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            
            
            
            <version>5.1.46version>
        dependency>

        
        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>1.2.12version>
        dependency>

        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
        dependency>
    dependencies>

② 创建实体类(User)

public class User {
    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 "com.itheima.domain.User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", birthday=" + birthday +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

③ 创建用户的持久层接口(IUserDao)

public interface IUserDao {

    //查询所有操作
    List<User> findAll();
}

④ 配置mybatis的主配置文件 (SqlMapConfig.xml)





<configuration>
    
    <environments default="mysql">
        
        <environment id="mysql">
            
            <transactionManager type="JDBC">transactionManager>
            
            <dataSource type="POOLED">
                
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://172.20.10.13:3306/dl?useSSL=false&useUnicode=true&characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="11250825"/>
            dataSource>
        environment>
    environments>

    
    <mappers>
        <mapper resource="com/itheima/dao/IUserDao.xml"/>
    mappers>
configuration>

mybatis的映射配置文件(IUserDao.xml)的位置必须和dao接口的包结构类似

⑤ 配置每个dao独立的配置文件,即映射配置文件(IUserDao.xml)





<mapper namespace="com.itheima.dao.IUserDao">
    
    
    <select id="findAll" resultType="com.itheima.domain.User">
        select * from user
    select>
mapper>

namespace表示方法findAll在哪个dao实现接口。
resultType表示要封装到哪里去。

映射配置文件的mapper标签里namespace属性的取值必须是dao接口的全限定类名
映射配置文件的操作配置(select等),id属性的取值必须是dao接口的方法名
遵从上面黄色底线的三点后,在开发中就无须再写dao的实现类了。


在映射配置文件(IUserDao.xml)中,需告知mybatis要封装到哪个实体类中。配置的方式是指定实体类的全限定类名。

<select id="findAll" resultType="com.itheima.domain.User">

⑥ 在resources中导入log4j.properties文件

# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

⑦ 在test - java 中创建测试类(MybatisTest)

/**
 * Mybatis 入门案例
 */
public class MybatisTest {
    public static void main(String[] args) throws IOException {
        //1.读取配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");

        //2.创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);

        //3.使用工厂生产SqlSession对象
        SqlSession session = factory.openSession();

        //4.创建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();
    }
}

上面程序的含义:
mybatis入门——day01:通过xml来配置_第3张图片
⑧ 配置mysql

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入门)