基于接口的方式,不需要写实现类
1.在dao中编写方法 2.在Mapper.xml中使用dao中定义好的方法名
dao中的编写
package dao;
import java.util.List;
import entity.Author;
import entity.AuthorVO;
/**
* 操作author表的dao接口
* dao 的实现类是由mybatis取代了JDBC
* 通过映射文件+框架
* @author Admin
*
*/
public interface AuthorDao {
public Author findById(int id);
public int insert(Author author);
public int delete(int id);
public int update(Author author);
//查询所有的用户
public List<Author> findAll();
//联查的实现
public List<AuthorVO> findBlog();
}
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">
<!--这个xml文件是通过接口的形式实现 -->
<mapper namespace="dao.AuthorDao">
<!--id名必须与dao中定义的方法名一致 -->
<select id="findById" parameterType="int" resultType="entity.Author">
select *from author where id=#{id}
</select>
<!-- 属性是一个对象的时候 -->
<insert id="insert" parameterType="entity.Author">
insert into author(id,userName,pwd,sex)values
(#{id},#{userName},#{password},#{sex})
</insert>
<!-- 当查询的结果为一个List的时候 会把查询的结果集映射为一个author对象,并且变成一个List-->
<!-- <select id="findAll" resultType="entity.Author">
select * from author
</select> -->
<!-- 当查询的列有别名的时候resultType的映射不能够进行匹配 -->
<!-- <select id="findAll" resultType="entity.Author">
select id,userName name,pwd pass,sex from author
</select> -->
<!--resultMap可以解决列有别名的问题 -->
<resultMap type="entity.Author" id="authorMap">
<result column="name" property="userName"/>
<result column="pass" property="pwd"/>
</resultMap>
<select id="findAll" resultMap="authorMap">
select id,userName name,pwd pass,sex from author
</select>
<select id="findBlog" resultType="entity.AuthorVO">
select author.userName,blog.title from author join blog on author.id=blog.author_id
</select>
</mapper>
编写测试类Test3
package test;
import java.io.InputStream;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import dao.AuthorDao;
import entity.Author;
import entity.AuthorVO;
/**
* 从此类开始,通过实现接口的方式得到连接
* 此类与AuthorMapper2.xml对应
* @author Admin
*
*/
public class Test3 {
public static void main(String[] args) {
// 1.读取配置文件,得到连接工厂
String resource = "SqlMapConfig.xml";
InputStream is = Test2.class.getClassLoader().getResourceAsStream(resource);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
// 2.从工厂中拿到真正的连接
SqlSession session = factory.openSession();
// 3.通过接口去实现数据库
//Mapper核心类:得到dao接口的代理类
AuthorDao dao=session.getMapper(AuthorDao.class);
/*Author author=dao.findById(10001);
System.out.println(author);*/
/*Author author2=new Author(10020, "sssuuuu", "1232sa", "male");
dao.insert(author2);*/
//查询所有
/*List<Author> list=dao.findAll();
System.out.println(list);*/
List<AuthorVO> blogList=dao.findBlog();
System.out.println(blogList);
//在进行增删改的时候一定进行提交
session.commit();
session.close();
}
}