1. 程式人生 > >Mybaits總結--一對一查詢

Mybaits總結--一對一查詢

一、表結構

CREATE TABLE `class` (
  `c_id` int(2) NOT NULL AUTO_INCREMENT,
  `c_name` varchar(30) DEFAULT NULL,
  `teacher_id` int(2) DEFAULT NULL,
  PRIMARY KEY (`c_id`),
  KEY `t_id_fk` (`teacher_id`),
  CONSTRAINT `t_id_fk` FOREIGN KEY (`teacher_id`) REFERENCES `teacher` (`t_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

CREATE TABLE `teacher` (
  `t_id` int(2) NOT NULL AUTO_INCREMENT,
  `t_name` varchar(30) DEFAULT NULL,
  PRIMARY KEY (`t_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

二、表對應的實體

class表和teacher表是一對一的關係,所以,在class實體中存在teacher的實體,或者在teacher實體中存在一個class的實體

class實體

public class Classes {
    //省去getter和setter
	private Integer id;
	private String name;
	private Teacher teacher;
}

teacher

public class Teacher {
    //省去getter和setter
	private Integer id;
	private String name;
}

三、對映檔案

  1、使用<association>標籤代表對應的實體,指定實體表的欄位,Mybaits會將查詢出來的結果填充到實體中,一條Sql

<select id="getClass" parameterType="int" resultMap="ClassResultMap">
	  select * from class c, teacher t where c.teacher_id=t.t_id and  c.c_id=#{id}
</select>
<resultMap type="Classes" id="ClassResultMap">
		<id property="id" column="c_id"/>
		<result property="name" column="c_name"/>
		
		<association property="teacher" javaType="Teacher">
			<id property="id" column="t_id"/>
			<result property="name" column="t_name"/>
		</association>
</resultMap>
	

2、使用<association>標籤代表對應的實體,並且指定對應實體的查詢sql,2條sql,若查詢的是一對一的集合則是1+n條sql

<select id="getClass2" parameterType="int" resultMap="ClassResultMap2"> 
	    select * from class where c_id = #{id}
	</select>
	<resultMap type="Classes" id="ClassResultMap2">
		<id property="id" column="c_id"/>
		<result property="name" column="c_name"/>
		
		<association property="teacher" select="getTeacher" column="teacher_id">
			
		</association>
	</resultMap>
	
	<select id="getTeacher" resultType="Teacher" parameterType="int">
	  select t_id id, t_name name from teacher where t_id = #{id}
	</select>

四、呼叫

@Test
	public void test2(){
		SqlSessionFactory factory = MybaitsUtils.getFactory();
		SqlSession session = factory.openSession();
		
		String statement = "zhuojing.mybaits.onetoone.getclassMapper.getClass";
		Classes classes  = session.selectOne(statement,1);
		System.out.println(classes);
		
		session.close();
	}