News-mapper.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">
<!-- 既是实体的映射文件。类似orm。同时又是dao的实现代码 -->
<mapper namespace="com.etc.dao.NewsDao">
<cache readOnly="true" size="100000"> <!-- 配置缓存-->
</cache>
<!-- 配置实体和数据表的映射关系 -->
<resultMap type="News" id="NewsResult">
<id column="id" property="id"/> <!-- 主键 -->
<result column="title" property="title"/>
<result column="content" property="content"/>
</resultMap>
<!-- 查询全部,实现findAll方法 -->
<select id="findAll" resultMap="NewsResult">
select * from news
</select>
<!-- 精确查询 ,实现findbyid的方法-->
<select id="findById" parameterType="java.lang.Integer" resultType="News">
select * from news where id=#{id}
</select>
<!-- 添加 -->
<insert id="add" parameterType="News" >
insert into news (title,content) values(#{title},#{content})
</insert>
<!-- 修改-->
<update id="update" parameterType="News" >
update news set title=#{title},content=#{content} where id=#{id}
</update>
<!-- 删除 -->
<delete id="delete" parameterType="java.lang.Integer">
delete from news where id=#{id}
</delete>
</mapper>
========================================================================
测试类: package com.etc.test; import java.util.List; import org.apache.ibatis.session.SqlSession;
import org.junit.Test; import com.etc.dao.NewsDao;
import com.etc.entity.News;
import com.etc.utils.MyBatisSessionFactory; public class TestNewsDao {
@Test
public void testLevel1()
{
// 1 获取连接
SqlSession session = MyBatisSessionFactory.getSession();
//2 执行查询
News n1 = session.getMapper(NewsDao.class).findById(1);
System.out.println(n1); session.clearCache();//删除全部的1级缓存
MyBatisSessionFactory.closeSession();
session = MyBatisSessionFactory.getSession();
News n2 = session.getMapper(NewsDao.class).findById(1);
System.out.println(n1==n2);
//3 关闭
MyBatisSessionFactory.closeSession();
} }
===================================================================

  

05-26 21:26