Mybatis入门1

关于Mybatis的快速入门可以分为这样几步:

1.引入依赖或者引入jar包

 

2.编写全局配置文件(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>
      <!-- 加载外部配置文件 -->
      <properties resource="jdbc.properties"></properties>
      <settings>
      <!--开启驼峰命名法-->
         <setting name="mapUnderscoreToCamelCase" value="true"/>
     </settings>
     
   <environments default="development">
     <environment id="development">
       <transactionManager type="JDBC"/>
       <dataSource type="POOLED">
         <property name="driver" value="${jdbc.driver}"/>
         <property name="url" value="${jdbc.url}"/>
         <property name="username" value="${jdbc.username}"/>
         <property name="password" value="${jdbc.password}"/>
       </dataSource>
     </environment>
   </environments>
   
   <!-- 指定mapper的配置文件 -->
   <mappers>
     <mapper resource="mapper.xml"/>
   </mappers>
 </configuration>

属性文件:

 jdbc.driver=com.mysql.jdbc.Driver
 jdbc.url=jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
 jdbc.username=root
 jdbc.password=123

3.编写映射文件(mapper.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="userMapper">
   <select id="queryUserById" parameterType="java.lang.Long" resultType="cn.mybatis.pojo.User">
     select * from tb_user where id = #{id}
   </select>
 </mapper>

4.编写测试代码

  String resource = "mybatis-config.xml";
          InputStream inputStream;
          SqlSessionFactory sqlSessionFactory;
          SqlSession sqlSession;
          
          inputStream = Resources.getResourceAsStream(resource);
          
          sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
          
         sqlSession = sqlSessionFactory.openSession();
         
         User user = sqlSession.selectOne("userMapper.queryUserById", 1L);
         
         System.out.println(user);

 

posted on 2018-03-05 10:37  lichangyun  阅读(150)  评论(0编辑  收藏  举报