本来只是想整理一下mybatis的源码的,不过突然发现很多基础的东西也需要回顾一下了,所以这里就从头开始整理一下mybatis。
Mybatis入门:
1、创建maven工程,引入mybatis相关依赖:
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.0</version>
</dependency>
<!-- 添加mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.12</version>
</dependency>
<!-- lombok包,非必须的 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.2</version>
<scope>provided</scope>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
其中mybatis包和mysql驱动包是必须要添加的,而lombok和junit测试包是非必须的。
2、配置mybatis,configuration.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://localhost:3306/zsmtest"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!-- 映射文件,mybatis精髓 -->
<mappers>
<mapper resource="cn/zsm/mybatis/ManMapper.xml"/>
</mappers>
</configuration>
zsmtest库中存在表man,并有几条测试数据:
3、编写mybatis应用代码
(1)Man实体:
import lombok.Data;
@Data
public class Man {
private String id;
private String name;
private String sex;
private Integer age;
}
(2)ManMapper接口
import org.apache.ibatis.annotations.Param;
public interface ManMapper {
Man selectMan(@Param("id") String id);
}
(3)ManMapper.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.zsm.mybatis.ManMapper">
<select id="selectMan" resultType="cn.zsm.mybatis.Man" >
select * from man where id = #{id}
</select>
</mapper>
注意,我这里使用的事Idea开发,由于Idea下的maven项目默认是不加载src目录下的*.xml文件的,所以需要在maven项目中添加如下配置:
否则会提示找不到对应的mapper.xml文件。
4、编写测试类
public class mybatisTest {
@Test
public void test() throws IOException {
String resource = "configuration.xml";
InputStream stream = Resources.getResourceAsStream(resource);
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(stream);
SqlSession sqlSession = build.openSession();
ManMapper mapper = sqlSession.getMapper(ManMapper.class);
Man man = mapper.selectMan("2");
System.out.println(man.toString());
}
}
输出结果: