1. BlogDao.java
package pht.mybatis.dao;
import java.util.List;
import pht.mybatis.pojo.Blog;
public interface BlogDao {
public List getBlog(int id);//查询多个数据时候,返回类型应该是List
public void addBlog(Blog b);
}
2. BlogDao.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="pht.mybatis.dao.BlogDao">
<resultMap type="Blog" id="blog">
<association property="user" select="getUser" column="user" javaType="Person"></association>
</resultMap>
<select id="getBlog" resultMap="blog">
select * from blog where user = #{bid}
</select>
<select id="getUser" resultType="Person">
select * from person where personid=#{bid}
</select>
</mapper>
3.pojo
package pht.mybatis.pojo; public class Blog { private int bid; private String title; private Person user; //这里体现了实体类的关系 public int getBid() { return bid; } public void setBid(int bid) { this.bid = bid; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Person getUser() { return user; } public void setUser(Person user) { this.user = user; } }
4. 测试类
package pht.mybatis.test; import java.io.IOException; import java.io.Reader; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import pht.mybatis.dao.*; import pht.mybatis.pojo.*; import pht.mybatis.sessionfactory.Sessionfactory; /** * myBatis数据库连接测试 * */ public class MyBatisTest { private static SqlSession sqlSession; public static void main(String[] args) { sqlSession=Sessionfactory.SQLSESSIONFACTORY.getSessionFactory().openSession(); MyBatisTest test=new MyBatisTest(); try{ BlogDao blogdao=sqlSession.getMapper(BlogDao.class); List blogs=blogdao.getBlog(4); for(Iterator it=blogs.iterator();it.hasNext();){ Blog blog=(Blog) it.next(); System.out.println(blog.getTitle()+":"+blog.getUser().getName()); } }catch (Exception e) { // TODO: handle exception }finally{ sqlSession.close(); } } }