MyBatis入门
MyBatis简介:
MyBatis的前身就是iBatis。它是一个数据持久层框架。
它是支持普通SQL查询、存储过程和高级映射的优秀持久层框架。消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。MyBatis使用简单的XML或注解用于配置和原始映射,将接口和Java的POJOs(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。
2010年6月16日,原iBatis开源项目由apache移到了google code,并改名为MyBatis。官方网址为:http://www.mybatis.org/
最新版本是3.1.1
MyBatis 完成CRUD
搭建开发环境
1、导入MyBatis的jar包
2、准备MyBatis的配置文件mybatis-config.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>
<properties resource="db.properties"/>
<typeAliases>
<typeAlias alias="Student" type="com.itheima.domain.Student" />
</typeAliases>
<environments default="default">
<environment id="default">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/itheima/domain/StudentMapper.xml" />
</mappers>
</configuration>
3、准备域对象的映射文件 StudentMapper.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="p1">
<!-- 查询一个对象 -->
<select id="selectOneStudent" parameterType="int" resultType="Student">
SELECT * FROM student WHERE id=#{id}
</select>
<!-- 查询多个对象 -->
<select id="selectAllStudents" resultType="Student">
SELECT * FROM student
</select>
<!-- 增加一条记录 -->
<insert id="insertStudent" parameterType="Student" flushCache="true" statementType="PREPARED">
INSERT INTO student (id,name,birthday) VALUES (#{id},#{name},#{birthday})
</insert>
<!-- 更新 -->
<update id="updateStudent" parameterType="Student">
UPDATE student set name=#{name},birthday=#{birthday} WHERE id=#{id}
</update>
<!-- 删除 -->
<delete id="deleteStudent" parameterType="int">
delete from student where id=#{id}
</delete>
</mapper>
4、创建SqlSession对象
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
SqlSession session = sqlSessionFactory.openSession();
5.调用SqlSession对象的各种方法进行增删改查