mybatis入门

Posted -jian

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis入门相关的知识,希望对你有一定的参考价值。

IDEA工具下的mybatis快速入门

1、添加依赖(在pox.xml文件下添加)

<properties>
  <maven.coppiler.source>1.9</maven.coppiler.source>
  <maven.coppiler.target>1.9</maven.coppiler.target>
</properties>
<dependencies>
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
  </dependency>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
  </dependency>
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.5</version>
    </dependency>
</dependencies>

  

2、编写pojo对象(即表中的实体类)

 

3、编写映射文件(xxxMapper.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="cn.aaa.Users">
    <select id="findAll" resultType="domain.Users">
        SELECT * FROM users;
    </select>
</mapper>

  

4、编写核心配置文件(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="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?characterEncoding=utf8" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>
    <!--映射文件路径-->
   <mappers>
      <mapper resource="cn/lijun/UsersMapper.xml"></mapper>
    </mappers>
</configuration>    

  

5、测试框架

public class TestCusom 
    @Test
    public void test()
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("SqlMapConfig.xml");
        //  创建工厂对象
        //System.out.println(inputStream);
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder= new SqlSessionFactoryBuilder();
        //System.out.println(sqlSessionFactoryBuilder);
        SqlSessionFactory sessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        SqlSession sqlSession = sessionFactory.openSession();
        //System.out.println(sqlSession);
        List<Object> list = sqlSession.selectList("cn.aaa.Dao.Users.findAll");
        for(Object o :list)
           System.out.println(o);
        
    

  

 

以上是关于mybatis入门的主要内容,如果未能解决你的问题,请参考以下文章

MyBatis入门基础

mybatis入门_mybatis基本原理以及入门程序

MyBatis从入门到精通:MyBatis入门

Mybatis入门

MyBatis学习总结-MyBatis快速入门的系列教程

Mybatis框架mybatis入门