Mybatis的快速入门

MyBatis官网地址:http://www.mybatis.org/mybatis-3/

MyBatis开发步骤:

①添加MyBatis的坐标

②创建user数据表

③编写User实体类

④编写映射文件UserMapper.xml

⑤编写核心文件SqlMapConfig.xml

⑥编写测试类

1 导入MyBatis的坐标和其他相关坐标

<!--mybatis坐标-->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.5</version>
</dependency>
<!--mysql驱动坐标-->
<dependency>    
    <groupId>mysql</groupId>   
    <artifactId>mysql-connector-java</artifactId>    
    <version>5.1.6</version>    
    <scope>runtime</scope>
</dependency>
<!--单元测试坐标-->
<dependency>    
    <groupId>junit</groupId>    
    <artifactId>junit</artifactId>    
    <version>4.12</version>    
    <scope>test</scope>
</dependency>
<!--日志坐标-->
<dependency>    
    <groupId>log4j</groupId>    
    <artifactId>log4j</artifactId>    
    <version>1.2.12</version>
</dependency>

2 创建user数据表

3 编写User实体

public class User {    
    private int id;    
    private String username;    
    private String password;
    //省略get和set方法
}

4 编写UserMapper映射文件   UserMapper.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="findAll" resultType="com.juanxincai.domain.User">        
        select * from User    
    </select>
</mapper>

5 编写MyBatis核心文件    SqlMapConfig.xml

<!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:///test"/>                
                <property name="username" value="root"/>
                <property name="password" value="root"/>            
            </dataSource>        
        </environment>    
    </environments>    
    
    <mappers> 
        <mapper resource="com/juanxincai/mapper/UserMapper.xml"/> 
    </mappers>
</configuration>

6 编写测试代码   

//加载核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
//获得sqlSession工厂对象
SqlSessionFactory sqlSessionFactory = new            
                           SqlSessionFactoryBuilder().build(resourceAsStream);
//获得sqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//执行sql语句
List<User> userList = sqlSession.selectList("userMapper.findAll");
//打印结果
System.out.println(userList);
//释放资源
sqlSession.close();
posted @ 2019-12-16 16:11  卷心菜的奇妙历险  阅读(290)  评论(0编辑  收藏  举报