MyBatis 简单入门
添加maven 依赖
<dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.17</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> </plugins> </build>
配置文件
<?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>
<properties resource="db.properties"/>
<!--配置enviroments环境-->
<environments default="mysql">
<environment id="mysql">
<!--指定事务管理的类型,这里简单使用Java的JDBC的提交和回滚设置-->
<transactionManager type="JDBC"/>
<!--dataSource 指连接源配置,POOLED是JDBC连接对象的数据源连接池的实现-->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/userMapper.xml"/>
</mappers>
</configuration>
mapper
<?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.qin.mapper.userMapper"> <select id="selectall" resultType="cn.qin.entity.user"> select * from user; </select> </mapper>
接口
public interface userMapper { public List<user> selectall(); }
测试
public class TestUser { private SqlSessionFactory sqlSessionFactory; @Test public void test() throws IOException { InputStream inputStream= Resources.getResourceAsStream("mybatis-config.xml"); //读取mybatis 配置文件创建sqlsessionFactory SqlSessionFactory sqlSessionFactory= new SqlSessionFactoryBuilder().build(inputStream); inputStream.close(); //获取sqlsession SqlSession sqlSession=sqlSessionFactory.openSession(); //获取对应mapper userMapper mapper=sqlSession.getMapper(userMapper.class); //执行并返回结果 List<user> list=mapper.selectall(); for (user u: list) { System.out.println(u.toString()); } } }