mybatis中一对一详细配置解析

1.建表

create table cards(
  cid int(5) primary key,
  cnum varchar(10)
);

create table students(
  sid int(5) primary key,
  sname varchar(10),
  scid int(5),
  constraint scid_fk foreign key(scid) references cards(cid)
);

insert into cards(cid,cnum) values(1,'111');
insert into students(sid,sname,scid) values(1,'哈哈',1);

select * from cards;
select * from students;

2.Student

package cn.itcast.one2one;

public class Student {
	private Integer id;
	private String name;
	private Card card;
	
	public Student(){
		
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Card getCard() {
		return card;
	}
	public void setCard(Card card) {
		this.card = card;
	}
	
	

}

3.Card

package cn.itcast.one2one;
//身份证(单方)
public class Card {
	private Integer id;
	private String num;
	
	public Card(){
		
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getNum() {
		return num;
	}
	public void setNum(String num) {
		this.num = num;
	}
	
	

}

4.CardMapper.xml






   
      
      
      
   
  

5.StudentMapper.xml





   
      
      
      
      
      
   
   
   
   
   
   

6.StudentCardDao

package cn.itcast.one2one;

import org.apache.ibatis.session.SqlSession;

import cn.itcast.util.MybatisUtil;

public class StudentCardDao {
	
	public Student findById(int id) throws Exception{
		SqlSession sqlSession=null;
		try{
			sqlSession=MybatisUtil.getSqlSession();
			return sqlSession.selectOne("studentNamespace.findById", id);
		}catch(Exception e){
			e.printStackTrace();
			throw e;
		}finally{
			MybatisUtil.closeSqlSession();
		}
	}
	
	public Student findByName(String name) throws Exception{
		SqlSession sqlSession=null;
		try{
			sqlSession=MybatisUtil.getSqlSession();
			return sqlSession.selectOne("studentNamespace.findByName",name);
		}catch(Exception e){
			e.printStackTrace();
			throw e;
		}finally{
			MybatisUtil.closeSqlSession();
		}
	}
	
	public static void main(String[] args) throws Exception{
		StudentCardDao dao=new StudentCardDao();
		Student s=dao.findById(1);
		System.out.println(s.getId()+":"+s.getName()+":"+s.getCard().getId()+":"+s.getCard().getNum());
		System.out.println("----------------");
		
		s=dao.findByName("哈哈");
		System.out.println(s.getName()+"的身份证号码为:"+s.getCard().getNum());
	}

}


你可能感兴趣的:(mybatis)