MyBatis-01

MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Ordinary Java Object,普通的 Java对象)映射成数据库中的记录。

1.导入依赖
2.准备Mapper接口和MapperXML文件

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

<!--namespace = mapper接口的权限定符-->
<mapper namespace="com.dc.mapper.EmployeeMapper">
    <!--
    声明标签写sql语句
    mapper接口中方法不能重载
    -->
    <select id="queryById" resultType="com.dc.pojo.Employee">
        select emp_id empId,emp_name empName,emp_salary empSalary from t_emp where emp_id=#{id}
    </select>

    <delete id="deleteById">
        delete from t_emp where emp_id=#{id}
    </delete>
</mapper>

mybatis-config.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="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis-example"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <!--5.扫描mapper文件-->
    <mappers>
        <mapper resource="mappers/EmployeeMapper.xml"></mapper>
    </mappers>

</configuration>
        //1.读取外部配置文件
        InputStream ips = Resources.getResourceAsStream("mybatis-config.xml");

        //2.创建sqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(ips);

        //3.根据sqlSessionFactory创建sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //4.获取接口的代理对象
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
        Employee employee=mapper.queryById(1);
        System.out.println(employee);

        //5.提交事务和释放资源
        sqlSession.commit();
        sqlSession.close();

你可能感兴趣的:(mybatis)