案例:基于MyBatis注解的学生管理程序
【任务目标】
现有一个学生表s_student和一个班级表c_class,其中,班级表c_class和学生表s_student是一对多的关系。学生表s_student和班级表c_class如表1和表2所示。
表1 学生表(s_student)
学生id id | 学生姓名 name | 学生年龄 age | 所属班级 cid |
1 | 张三 | 18 | 1 |
2 | 李四 | 18 | 2 |
3 | 王五 | 19 | 2 |
4 | 赵六 | 20 | 1 |
表2 班级表(c_class)
班级id id | 班级名称 classname |
1 | 一班 |
2 | 二班 |
请使用MyBatis注解完成以下几个要求:
- MyBatis注解实现查询操作
根据表1和表2在数据库分别创建一个学生表s_student和一个班级表c_class, 并查询id为2的学生的信息。
2.MyBatis注解实现修改操作
修改id为4的学生的姓名修改为李雷,年龄修改为21.
3. Mybatis注解实现一对多查询
查询出二班所有学生的信息。
【实现步骤】:MyBatis注解实现查询操作
USE mybatis;
# 创建一个名称为c_class的表
CREATE TABLE c_class (
id int(32) PRIMARY KEY AUTO_INCREMENT,
classname varchar(40)
);
# 插入2条数据
INSERT INTO c_class VALUES (1, '一班');
INSERT INTO c_class VALUES (2, '二班');
# 创建一个名称为s_student的表
CREATE TABLE s_student (
id int(32) PRIMARY KEY AUTO_INCREMENT,
name varchar(40),
age int,
cid int(32) NOT NULL,
FOREIGN KEY(cid) REFERENCES c_class(id)
);
# 插入4条数据
INSERT INTO s_student VALUES (1, '张三', 18,1);
INSERT INTO s_student VALUES (2, '李四', 18,2);
INSERT INTO s_student VALUES (3, '王五', 19,2);
INSERT INTO s_student VALUES (4, '赵六', 20,1);
创建实体类
public class IClass {
private Integer id;
private String classname;
private List<IStudent> studentList;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getClassname() {
return classname;
}
public void setClassname(String classname) {
this.classname = classname;
}
public List<IStudent> getStudentList() {
return studentList;
}
public void setStudentList(List<IStudent> studentList) {
this.studentList = studentList;
}
@Override
public String toString() {
return "IClass{" +
"id=" + id +
", classname='" + classname + '\'' +
", studentList=" + studentList +
'}';
}
}
public class IStudent {
private Integer id;
private String name;
private int age;
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "IStudent{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
创建Mapper接口
public interface IClassMapper {
@Select("select * from c_class where id = #{id}")
@Results({@Result(id = true, column = "id", property = "id"),
@Result(column = "classname", property = "classname"),
@Result(column = "id", property = "studentList", many = @Many(select = "com.wzy.dao.IStudentMapper.selectStudentByCid"))})
IClass selectClassById(int id);
}
public interface IStudentMapper {
@Select("select * from s_student where id = #{id}")
IStudent selectStudent(int id);
@Update("update s_student set name = #{name},age = #{age}")
int updateStudent(IStudent student);
@Select("select * from s_student where cid =#{id} ")
@Results({@Result(id = true, column = "id", property = "id"),
@Result(column = "classname", property = "classname")})
List<IStudent> selectStudentByCid(int cid);
}
修改mybatis-config.xml核心配置文件
在核心配置文件mybatis-config.xml中的<mappers>元素下引入IStudentMapper接口,将IStudentMapper接口加载到核心配置文件中,具体代码如下所示。
<mapper class="com.wzy.dao.IStudentMapper"/>
编写MyBatisUtils工具类
在项目src/main/java目录下创建com.wzy.utils包,在com.wzy.utils包下创建MyBatisUtils工具类,该类用于封装读取配置文件信息的代码。具体代码如下所示。
/**
8 * 工具类
9 */
10 public class MyBatisUtils {
11 private static SqlSessionFactory sqlSessionFactory = null;
12 // 初始化SqlSessionFactory对象
13 static {
14 try {
15 // 使用MyBatis提供的Resources类加载MyBatis的配置文件
16 Reader reader =
17 Resources.getResourceAsReader("mybatis-config.xml");
18 // 构建SqlSessionFactory工厂
19 sqlSessionFactory =
20 new SqlSessionFactoryBuilder().build(reader);
21 } catch (Exception e) {
22 e.printStackTrace();
23 }
24 }
25 // 获取SqlSession对象的静态方法
26 public static SqlSession getSession() {
27 return sqlSessionFactory.openSession();
28 }
29 }
目录结构
编写测试方法
public class findIStudentByIdTest {
@Test
public void findIStudentByIdTest() {
String resources = "mybatis-config.xml";
Reader reader = null;
try {
reader = Resources.getResourceAsReader(resources);
} catch (IOException e) {
e.printStackTrace();
}
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = sqlSessionFactory.openSession();
IStudentMapper mapper = sqlSession.getMapper(IStudentMapper.class);
IStudent student= mapper.selectStudent(2);
System.out.println("学号: 201164212" + " " + "姓名: 刘艺星");
System.out.println(student.toString());
sqlSession.close();
}
@Test
public void updateIStudentTest() {
String resources = "mybatis-config.xml";
Reader reader = null;
try {
reader = Resources.getResourceAsReader(resources);
} catch (IOException e) {
e.printStackTrace();
}
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = sqlSessionFactory.openSession();
IStudentMapper mapper = sqlSession.getMapper(IStudentMapper.class);
IStudent iStudent = new IStudent();
iStudent.setId(4);
iStudent.setName("小红");
iStudent.setAge(21);
IStudentMapper iStudentMapper = sqlSession.getMapper(IStudentMapper.class);
int result = mapper.updateStudent(iStudent);
if(result > 0) {
System.out.println("成功更新" + result + "条数据");
}else {
System.out.println("更新失败");
}
System.out.println("学号: 201164212" + " " + "姓名: 刘艺星");
System.out.println(iStudent.toString());
sqlSession.close();
}
}
public class SelectByClassTest {
@Test
public void selectByClassTest() {
String resources = "mybatis-config.xml";
Reader reader = null;
try {
reader = Resources.getResourceAsReader(resources);
} catch (IOException e) {
e.printStackTrace();
}
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = sqlSessionFactory.openSession();
IClassMapper classMapper = sqlSession.getMapper(IClassMapper.class);
IClass iClass = classMapper.selectClassById(2);
System.out.println("学号: 201164212" + " " + "姓名: 刘艺星");
System.out.println(iClass.toString());
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 环境配置 -->
<!-- 加载类路径下的属性文件 -->
<properties resource="db.properties"/>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<!-- 数据库连接相关配置 ,db.properties文件中的内容-->
<dataSource type="POOLED">
<property name="driver" value="${mysql.driver}"/>
<property name="url" value="${mysql.url}"/>
<property name="username" value="${mysql.username}"/>
<property name="password" value="${mysql.password}"/>
</dataSource>
</environment>
</environments>
<!-- mapping文件路径配置 -->
<mappers>
<mapper class="com.wzy.dao.IStudentMapper"/>
<mapper class="com.wzy.dao.IClassMapper"/>
</mappers>
</configuration>
注意mybatis-config.xml里的mapper文件路径配置,执行完第一个程序后,不能删掉IStudentMappper