1.1. Mybatis基础知识
1.2. 入门Demo搭建
1.2.1. 搭建Java工程
1.2.1.1.1. 创建Maven工程
1.2.1.1.2. 添加依赖
1.2.2. 编写代码
1.2.2.1.1. 编写主类
public static void main(String[] args) throws Exception {
Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/basetest/mybatis-config.xml"); // 加载配置文件
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); //创建sqlSessionFactory对象
SqlSession sqlSession = sqlSessionFactory.openSession(); // 获取sqlSession对象
Mapper mapper = sqlSession.getMapper(Mapper.class); // 获取映射接口
User user = mapper.getUser(1); // 调用接口方法
System.out.println(user); //
}
1.2.2.1.2. 编写实体对象
public class User {
private Integer id;
private String name;
1.2.2.1.3. 编写映射接口
public interface Mapper {
/**
* 根据用户主键ID获取用户独享
* @param id 主键ID
* @return
*/
User getUser(Integer id);
/**
* 保存用户对象
* @param user 用户对象
* @return
*/
void insertUser(User user);
}
1.2.2.1.4. 编写映射文件
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.apache.ibatis.submitted.basetest.Mapper">
<select id="getUser" resultType="org.apache.ibatis.submitted.basetest.User">
select * from users where id = #{id}
</select>
<insert id="insertUser">
insert into users values(#{id}, #{name})
</insert>
</mapper>
1.2.2.1.5. 编写配置文件
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC">
<property name="" value="" />
</transactionManager>
<dataSource type="UNPOOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper class="org.apache.ibatis.submitted.basetest.Mapper" />
</mappers>
</configuration>
1.2.2.1.6. 创建数据库表
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (`id`)
);
1.2.3. 运行程序
1.3. 创建SqlSessionFactory序列图