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對象的各種方法進行增刪改查