MyBatis框架

2.3 创建MyBatis的全局配置文件

  • 参考MyBatis的官网手册

<?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" />

 

                            <dataSource type="POOLED">

                                     <property name="driver" value="com.mysql.jdbc.Driver" />

                                     <property name="url" value="jdbc:mysql://localhost:3306/mybatis_1129" />

                                     <property name="username" value="root" />

                                     <property name="password" value="1234" />

                            </dataSource>

                   </environment>

         </environments>

         <!-- 引入SQL映射文件,Mapper映射文件 -->

         <mappers>

                   <mapper resource="EmployeeMapper.xml" />

         </mappers>

</configuration>

 

2.4 创建Mybatis的sql映射文件

  • 参考MyBatis的官方手册

<?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="suibian">

         <select id="selectEmployee" resultType="com.atguigu.myabtis.helloWorld.Employee">

                   select id ,last_name lastName ,email ,gender from tbl_employee where id = #{id}

                   <!-- select * from tbl_employee  where id = #{id} -->

         </select>

</mapper>

 

2.5 测试

  • 参考MyBatis的官方手册

@Test

         public void test() throws Exception {

                   String resource = "mybatis-config.xml";

                   InputStream inputStream = Resources.getResourceAsStream(resource);

                   SqlSessionFactory sqlSessionFactory =

                                               new SqlSessionFactoryBuilder().build(inputStream);

                   System.out.println(sqlSessionFactory);

 

                   SqlSession session  = sqlSessionFactory.openSession();

                   try {

                            Employee employee =

                                               session.selectOne("suibian.selectEmployee", 1001);

                            System.out.println(employee);

                   } finally {

                            session.close();

                   }

       }