1.SQL语句建表
1 CREATE TABLE teacher( 2 t_id INT PRIMARY KEY AUTO_INCREMENT, t_name VARCHAR(20) 3 ); 4 CREATE TABLE class( 5 c_id INT PRIMARY KEY AUTO_INCREMENT, c_name VARCHAR(20), 6 teacher_id INT 7 ); 8 ALTER TABLE class ADD CONSTRAINT fk_teacher_id FOREIGN KEY (teacher_id) REFERENCES teacher(t_id); 9 INSERT INTO teacher(t_name) VALUES('LS1'); INSERT INTO teacher(t_name) VALUES('LS2');10 INSERT INTO class(c_name, teacher_id) VALUES('bj_a', 1); INSERT INTO class(c_name, teacher_id) VALUES('bj_b', 2);
2.实体类
1 package com.zhengbin.entity; 2 3 public class Teacher { 4 private int id; 5 private String name; 6 public int getId() { 7 return id; 8 } 9 public void setId(int id) {10 this.id = id;11 }12 public String getName() {13 return name;14 }15 public void setName(String name) {16 this.name = name;17 }18 @Override19 public String toString() {20 return "Teacher [id=" + id + ", name=" + name + "]";21 }22 public Teacher(int id, String name) {23 super();24 this.id = id;25 this.name = name;26 }27 public Teacher() {28 super();29 // TODO Auto-generated constructor stub30 }31 }
1 package com.zhengbin.entity; 2 3 public class Classes { 4 private int id; 5 private String name; 6 private Teacher teacher; 7 @Override 8 public String toString() { 9 return "Classes [id=" + id + ", name=" + name + ", teacher=" + teacher + "]";10 }11 public Classes() {12 super();13 }14 public int getId() {15 return id;16 }17 public void setId(int id) {18 this.id = id;19 }20 public String getName() {21 return name;22 }23 public void setName(String name) {24 this.name = name;25 }26 public Teacher getTeacher() {27 return teacher;28 }29 public void setTeacher(Teacher teacher) {30 this.teacher = teacher;31 }32 }
3.实体类映射文件
两种方式:
1. 联表查询
关键是返回值的设置
2. 执行两次查询
关键是返回值的设置,和第二次查询所需参数的传递
1 2 3 45 6 7 8 12 15 16 23 29 32 3517 18 19 2220 21 36 4037 38 39
4.测试类
1 package com.zhengbin.test; 2 3 import org.apache.ibatis.session.SqlSession; 4 import org.apache.ibatis.session.SqlSessionFactory; 5 6 import com.zhengbin.entity.Classes; 7 import com.zhengbin.util.MyBatisUtils; 8 9 public class Test3 {10 @org.junit.Test11 public void getTeacher(){12 SqlSessionFactory sessionFactory = MyBatisUtils.getFactory();13 // 参数为TRUE,相当于session.commit();14 SqlSession session = sessionFactory.openSession(true);15 // 读取映射文件16 String statement = "com.zhengbin.entity.classMapper" + ".getClass";17 // String statement = "com.zhengbin.entity.classMapper" + ".getClass2";18 Classes c = session.selectOne(statement,1);19 System.out.println(c);20 session.close();21 }22 }
5.几个关键的属性
association : 用于一对一的关联查询property : 对象属性的名称javaType : 对象属性的类型column : 所对应的外键字段名称select : 使用另一个查询封装的结果