码迷,mamicode.com
首页 > 其他好文 > 详细

mybatis入门

时间:2019-07-22 20:11:30      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:group   工具   aaa   stc   dea   map   puts   out   input   

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入门

标签:group   工具   aaa   stc   dea   map   puts   out   input   

原文地址:https://www.cnblogs.com/-jian/p/11227963.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!