1 方式一
a) 接口中定义方法
User selByUP(String username, String password);
User selByUP(@Param("username") String username, @Param("password") String password);
int updUser(User user);
update t_user
id=#{id},
username=#{username},
password=#{password},
where id=#{id}
update t_user
username=#{username},
where id=#{id}
List selIn(@Param("list") List list);
id,username,password
create table t_class(
id int(3) primary key auto_increment,
name varchar(20) not null,
room varchar(20)
)
create table t_student(
id int(5) primary key auto_increment,
name varchar(30) not null,
age int(3),
gender char(3),
cid int(3) REFERENCES t_class (id)
)
select * from t_student s left join t_class c on s.cid=c.id;
public class StudentServiceImpl implements StudentService {
@Override
public List selAll() {
SqlSession session= MyBatisUtil.getSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
ClazzMapper clazzMapper=session.getMapper(ClazzMapper.class);
List list=studentMapper.selAll();
for(Student student:list){
student.setClazz(clazzMapper.selById(student.getCid()));
}
session.close();
return list;
}
}
public class testStudentAndClass {
public static void main(String[] args) {
StudentServiceImpl studentService=new StudentServiceImpl();
List list = studentService.selAll();
for(Student student:list){
System.out.println(student);
}
}
}
sql语句简单,但是组装麻烦
1 实体类
public List selAll2(){
SqlSession session= MyBatisUtil.getSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
List list=studentMapper.selAll2();
session.close();
return list;
}
上面的方式执行的sql语句很多,因此有了接下来的关联方式实现多表查询
1 mapper 层
public class ClazzServiceImpl implements ClazzSercive {
@Override
public List selAll() {
SqlSession session= MyBatisUtil.getSession();
ClazzMapper clazzMapper=session.getMapper(ClazzMapper.class);
List list=clazzMapper.selAll();
session.close();
return list;
}
}
1 CRUD 注解
public interface StudentMapper {
@Select("select * from t_student")
List selAll();
@Insert("insert into t_student values (default, #{name}, #{age}, #{gender}, #{cid})")
int insStu(Student student);
@Update("update t_student set age=#{1} where id=#{0}")
int updStu(int id, int age);
@Delete("delete from t_student where id=#{0}")
int delStu(int id);
}
2 其他注解
public interface StudentMapper {
@Select("select * from t_student")
@Results(value = {
@Result(column="id", property="id", id=true),
@Result(column="name", property="name"),
@Result(column="age", property="age"),
@Result(column="gender", property="gender"),
@Result(column="cid", property="cid"),
@Result(property="clazz",
one=@One(select="com.bjsxt.mapper.ClazzMapper.selById"),
column="cid")
})
List sel(); }
public interface ClazzMapper {
@Select("select * from t_class where id=#{0}")
Clazz selById(int id);
}
1 运行过程中涉及到的类或接口