Mybatis的入门

1、什么是框架?
它是我们软件开发中的一套解决方案,不同的框架解决的问题是不同;
使用框架的好处:
框架封装了很多的细节,是开发者可以使用极简单的方式实现功能,大大提高开发效率
2、三层框架
表现层:用于展示数据
业务层:用于处理业务需求
持久层:用于和而数据库的交互
3、持久层技术解决方案
JDBC:
connection
PrepareStatement
ResultSet
Spring的JDBCTemplate:
spring的JDBCTemplate相似,也是对jdbc的简单封装
以上这些都不是框架,其中JDBC是规范,Spring的jdbcTemplate和apache的DBUtils都只是工具类
4、mybatis的概述
mybatis是一个持久层框架,用Java代码实现的,它封装了jdbc操作的很多细节,使开发者只需要关心sql语句的本身,而无需关注注册驱动类,创建联接等复杂的操作
ORM:Object Relational Mapping对象映射,简单来说,就是把数据库和实体属性对应起来,让我们可以操作实体类就是操作数据库表;
5、mybatis的入门
mybatis的环境搭建:
第一步:创建maven工程并导入坐标
第二步:创建实体类和dao的接口
第三步:创建mybatis的著配置文件:SqlMapConfig.xml
第四步:创建映射配置文件:IUserDao.xml
环境搭建注意事项:
1)mybatis的映射文件位置必须和dao接口的包接口保持一致;
2)映射配置文件的mapper标签namespace属性的取值必须是dao接口的全限定类名;
3)映射配置文件的操作配置(select),id属性的取值必须是dao接口的方法名.
遵从以上三点之后,在开发中就无需再写dao的实现类;
具体的实现
本地数据库
在这里插入图片描述
java中的配置文件;
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.songlin.dao.IUserDao">
    <!--配置查询所有-->
    <select resultType="com.songlin.domain.User" id="findAll">
        select * from user
    </select>
</mapper>

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:/log_java/mybatis_xis.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

SqlMapConfig.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>
    <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://localhost:3306/test01"/>
                <property name="username" value="root"/>
                <property name="password" value="hadoop"/>
            </dataSource>
        </environment>
    </environments>

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

编写接口 IUserDao

package com.songlin.dao;

import com.songlin.domain.User;

import java.util.List;

/**
 * @author Joe
 * @create 2020-10-08 20:31
 */
public interface IUserDao {
    List<User> findAll();
}

编写java类User

package com.songlin.domain;

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

/**
 * @author Joe
 * @create 2020-10-08 20:28
 */
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 + '\'' +
                '}';
    }
}

编写测试类,检查运行是否正常

package com.songlin.test;

import com.songlin.dao.IUserDao;
import com.songlin.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.InputStream;
import java.util.List;

/**
 * @author Joe
 * @create 2020-10-11 9:20
 * mybatis的入门案例
 */
public class MybatisTest {
    public static void main(String[] args) throws Exception {
        //1、读取配置文件
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2、创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(inputStream);
        //3、使用工厂生产SqlSession对象
        SqlSession session = factory.openSession();
        //4、使用SqlSession创建Dao接口的代理对象
        IUserDao iuserDao = session.getMapper(IUserDao.class);
        //5、使用代理对象执行方法
        List<User> users = iuserDao.findAll();
        for (User user:users){
            System.out.println(user);
        }
        //6、释放资源
        session.close();
        inputStream.close();
    }
}

运行结果:

2020-10-11 11:24:22,707 0      [           main] DEBUG ache.ibatis.logging.LogFactory  - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
2020-10-11 11:24:22,820 113    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-10-11 11:24:22,820 113    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-10-11 11:24:22,820 113    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-10-11 11:24:22,820 113    [           main] DEBUG source.pooled.PooledDataSource  - PooledDataSource forcefully closed/removed all connections.
2020-10-11 11:24:22,893 186    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Opening JDBC Connection
2020-10-11 11:24:23,090 383    [           main] DEBUG source.pooled.PooledDataSource  - Created connection 1447689627.
2020-10-11 11:24:23,090 383    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@5649fd9b]
2020-10-11 11:24:23,092 385    [           main] DEBUG m.songlin.dao.IUserDao.findAll  - ==>  Preparing: select * from user 
2020-10-11 11:24:23,109 402    [           main] DEBUG m.songlin.dao.IUserDao.findAll  - ==> Parameters: 
2020-10-11 11:24:23,128 421    [           main] DEBUG m.songlin.dao.IUserDao.findAll  - <==      Total: 6
User{id=41, username='张三', birthday=Tue Feb 27 17:47:08 CST 2018, sex='男', address='北京'}
User{id=42, username='李四', birthday=Fri Mar 02 15:09:37 CST 2018, sex='女', address='陕西'}
User{id=43, username='王五', birthday=Sun Mar 04 11:34:34 CST 2018, sex='女', address='湖北'}
User{id=45, username='小二', birthday=Sun Mar 04 12:04:06 CST 2018, sex='男', address='内蒙古'}
User{id=46, username='老辛', birthday=Wed Mar 07 17:37:26 CST 2018, sex='男', address='武汉'}
User{id=48, username='周三', birthday=Thu Mar 08 11:44:00 CST 2018, sex='女', address='山东'}
2020-10-11 11:24:23,133 426    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@5649fd9b]
2020-10-11 11:24:23,134 427    [           main] DEBUG ansaction.jdbc.JdbcTransaction  - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@5649fd9b]
2020-10-11 11:24:23,134 427    [           main] DEBUG source.pooled.PooledDataSource  - Returned connection 1447689627 to pool.

Process finished with exit code 0

注意SqlMapConfig.xml文件的填写,里面的信息需要与本地的数据库信息一致,否者会连接失败,无法查询具体的信息。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值