lichangyun

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

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

 

2.编写全局配置文件(Mybatis-config.xml)

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration
 3   PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 4   "http://mybatis.org/dtd/mybatis-3-config.dtd">
 5 <configuration>
 6     <!-- 加载外部配置文件 -->
 7     <properties resource="jdbc.properties"></properties>
 8     <settings>
 9     <!--开启驼峰命名法-->
10         <setting name="mapUnderscoreToCamelCase" value="true"/>
11     </settings>
12     
13   <environments default="development">
14     <environment id="development">
15       <transactionManager type="JDBC"/>
16       <dataSource type="POOLED">
17         <property name="driver" value="${jdbc.driver}"/>
18         <property name="url" value="${jdbc.url}"/>
19         <property name="username" value="${jdbc.username}"/>
20         <property name="password" value="${jdbc.password}"/>
21       </dataSource>
22     </environment>
23   </environments>
24   
25   <!-- 指定mapper的配置文件 -->
26   <mappers>
27     <mapper resource="mapper.xml"/>
28   </mappers>
29 </configuration>
View Code

属性文件:

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

3.编写映射文件(mapper.xml)

1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE mapper
3   PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
4   "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
5 <mapper namespace="userMapper">
6   <select id="queryUserById" parameterType="java.lang.Long" resultType="cn.itcast.mybatis.pojo.User">
7     select * from tb_user where id = #{id}
8   </select>
9 </mapper>
View Code

4.编写测试代码

 1 String resource = "mybatis-config.xml";
 2         InputStream inputStream;
 3         SqlSessionFactory sqlSessionFactory;
 4         SqlSession sqlSession;
 5         
 6         inputStream = Resources.getResourceAsStream(resource);
 7         
 8         sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
 9         
10         sqlSession = sqlSessionFactory.openSession();
11         
12         User user = sqlSession.selectOne("userMapper.queryUserById", 1L);
13         
14         System.out.println(user);
View Code

 

相关文章:

  • 2022-02-10
  • 2018-04-16
  • 2022-12-23
  • 2021-10-11
  • 2021-09-03
  • 2021-07-01
  • 2021-07-20
猜你喜欢
  • 2021-11-21
  • 2021-06-02
  • 2021-09-15
  • 2021-10-17
  • 2021-11-15
  • 2021-09-03
  • 2021-09-25
相关资源
相似解决方案