创建实体与映射关系文件
配置实体与表的映射关系
<?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"> <!-- namespace属性是名称空间,必须唯一 --> <mapper namespace="cn.itcast.javaee.mybatis.app04.Student"> <!-- resultMap标签:映射实体与表 type属性:表示实体全路径名 id属性:为实体与表的映射取一个任意的唯一的名字 --> <resultMap type="student" id="studentMap"> <!-- id标签:映射主键属性 result标签:映射非主键属性 property属性:实体的属性名 column属性:表的字段名 --> <id property="id" column="id"/> <result property="name" column="name"/> <result property="sal" column="sal"/> </resultMap> </mapper>
现在我们已经有了Mybatis的配置文件和表与实体之前的映射文件了,因此我们要将配置文件和映射文件关联起来
<mappers> <mapper resource="StudentMapper.xml"/> </mappers>
在测试类上,我们是可以获取得到连接的
编写DAO
public class StudentDao { public void add(Student student) throws Exception { //得到连接对象 SqlSession sqlSession = MybatisUtil.getSqlSession(); sqlSession.insert(); } public static void main(String[] args) throws Exception { StudentDao studentDao = new StudentDao(); Student student = new Student(1, "zhongfucheng", 10000D); studentDao.add(student); } }
到现在为止,我们实体与表的映射文件仅仅映射了实体属性与表的字段的关系…
我们在Hibernate中如果想要插入数据什么的,只要调用save()方法就行了。Hibernate是自动化屏蔽掉了数据库的差异,而我们Mybatis是需要自己手动编写SQL代码的…
那么SQL代码是写在哪里的呢???明显地,我们作为一个框架,不可能在程序中写SQL,我们是在实体与表的映射文件中写的!
Mybatis实体与表的映射文件中提供了insert标签【SQL代码片段】供我们使用
//在JDBC中我们通常使用?号作为占位符,而在Mybatis中,我们是使用#{}作为占位符 //parameterType我们指定了传入参数的类型 //#{}实际上就是调用了Student属性的get方法 <insert id="add" parameterType="Student"> INSERT INTO ZHONGFUCHENG.STUDENTS (ID, NAME, SAL) VALUES (#{id},#{name},#{sal}); </insert>
在程序中调用映射文件的SQL代码片段
public void add(Student student) throws Exception { //得到连接对象 SqlSession sqlSession = MybatisUtil.getSqlSession(); try{ //映射文件的命名空间.SQL片段的ID,就可以调用对应的映射文件中的SQL sqlSession.insert("StudentID.add", student); sqlSession.commit(); }catch(Exception e){ e.printStackTrace(); sqlSession.rollback(); throw e; }finally{ MybatisUtil.closeSqlSession(); } }
值得注意的是:Mybatis中的事务是默认开启的,因此我们在完成操作以后,需要我们手动去提交事务!
Mybatis工作流程
- 通过Reader对象读取Mybatis配置文件
- 通过SqlSessionFactoryBuilder对象创建SqlSessionFactory对象
- 获取当前线程的SQLSession
- 事务默认开启
- 通过SQLSession读取映射文件中的操作编号,从而读取SQL语句
- 提交事务
- 关闭资源
完成CRUD操作
我们在上面中已经简单知道了Mybatis是怎么使用的以及工作流程了,这次我们使用Mybatis来完成CRUD的操作,再次巩固Mybatis的开发步骤以及一些细节
包与类之间的结构
增加学生
配置文件
<?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"/> <!-- 设置一个默认的连接环境信息 --> <environments default="mysql_developer"> <!-- 连接环境信息,取一个任意唯一的名字 --> <environment id="mysql_developer"> <!-- mybatis使用jdbc事务管理方式 --> <transactionManager type="jdbc"/> <!-- mybatis使用连接池方式来获取连接 --> <dataSource type="pooled"> <!-- 配置与数据库交互的4个必要属性 --> <property name="driver" value="${mysql.driver}"/> <property name="url" value="${mysql.url}"/> <property name="username" value="${mysql.username}"/> <property name="password" value="${mysql.password}"/> </dataSource> </environment> <!-- 连接环境信息,取一个任意唯一的名字 --> <environment id="oracle_developer"> <!-- mybatis使用jdbc事务管理方式 --> <transactionManager type="jdbc"/> <!-- mybatis使用连接池方式来获取连接 --> <dataSource type="pooled"> <!-- 配置与数据库交互的4个必要属性 --> <property name="driver" value="${oracle.driver}"/> <property name="url" value="${oracle.url}"/> <property name="username" value="${oracle.username}"/> <property name="password" value="${oracle.password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="zhongfucheng/StudentMapper.xml"/> </mappers> </configuration>
映射文件
<!-- namespace属性是名称空间,必须唯一 --> <mapper namespace="StudentID"> <!-- resultMap标签:映射实体与表 type属性:表示实体全路径名 id属性:为实体与表的映射取一个任意的唯一的名字 --> <resultMap type="zhongfucheng.Student" id="studentMap"> <!-- id标签:映射主键属性 result标签:映射非主键属性 property属性:实体的属性名 column属性:表的字段名 --> <id property="id" column="id"/> <result property="name" column="name"/> <result property="sal" column="sal"/> </resultMap> <insert id="add" parameterType="zhongfucheng.Student"> INSERT INTO ZHONGFUCHENG.STUDENTS (ID, NAME, SAL) VALUES (#{id},#{name},#{sal}); </insert> </mapper>
插入数据
public class StudentDao { public void add(Student student) throws Exception { //得到连接对象 SqlSession sqlSession = MybatisUtil.getSqlSession(); try{ //映射文件的命名空间.SQL片段的ID,就可以调用对应的映射文件中的SQL sqlSession.insert("StudentID.add", student); sqlSession.commit(); }catch(Exception e){ e.printStackTrace(); sqlSession.rollback(); throw e; }finally{ MybatisUtil.closeSqlSession(); } } public static void main(String[] args) throws Exception { StudentDao studentDao = new StudentDao(); Student student = new Student(3, "zhong3", 10000D); studentDao.add(student); } }
根据ID查询数据
增加select标签
<!-- 查询根据id resultMap这个属性代表是返回值类型,返回值的类型是Student,就是上面实体类型 --> <select id="findById" parameterType="int" resultMap="studentMap"> SELECT * FROM STUDENTS WHERE id = #{id}; </select>
查询出来的结果是一个Student对象,我们调用SelectOne方法
public Student findById(int id) throws Exception { //得到连接对象 SqlSession sqlSession = MybatisUtil.getSqlSession(); try{ //映射文件的命名空间.SQL片段的ID,就可以调用对应的映射文件中的SQL return sqlSession.selectOne("StudentID.findById",id); }catch(Exception e){ e.printStackTrace(); sqlSession.rollback(); throw e; }finally{ MybatisUtil.closeSqlSession(); } } public static void main(String[] args) throws Exception { StudentDao studentDao = new StudentDao(); Student student = studentDao.findById(1); System.out.println(student.getName()); }