mybatis多对一查询

4 篇文章 0 订阅
3 篇文章 0 订阅

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();
		}
		
		
	}
}










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值