本篇文章介绍在IDEA工具下mybatis快速入门程序分为以下五步
1 添加依赖包
2 编写pojo对象
3 编写映射文件
4 编写核心配置文件
5 测试框架
详细如下
建立Module后
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 编写映射文件 代码如下
<?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.lijun.Users">
<select id="findAll" resultType="domain.Users">
SELECT * FROM users;
</select>
</mapper>
4 编写核心配置文件 代码如下
<?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/mybatis9501?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 测试框架 在test对应的包下建立 如图
代码如下
/**
* @author lijun
* @date 2019/6/28 11:44
*/
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.lijun.Dao.Users.findAll");
for(Object o :list){
System.out.println(o);
}
}
}