实例:一个班级可以有多个学生,一个学生只能属于一个班级。OneToManyTest:实现增删改查
1、创建两个表:tb_class、tb_student
tb_class:
tb_student:
2、实体类创建Clazz类与Student类分别映射 tb_clazz 和tb_student
Clazz :
public class Clazz {
private Integer id;
private String code;
private String name;
private List<Student> students;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
}
Student:
public class Student {
private Integer id;
private String name;
private String sex;
private Integer age;
private Clazz clazz;
private Integer clazz_id;
public Integer getClazz_id() {
return clazz_id;
}
public void setClazz_id(Integer clazz_id) {
this.clazz_id = clazz_id;
}
public Student(Integer id, String name, String sex, Integer age, Clazz clazz) {
super();
this.id = id;
this.name = name;
this.sex = sex;
this.age = age;
this.clazz = clazz;
}
public Student() {
super();
}
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 String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Clazz getClazz() {
return clazz;
}
public void setClazz(Clazz clazz) {
this.clazz = clazz;
}
}
3、dao层接口
ClazzDao:
public interface ClazzDao {
public Clazz selectClazzById(Integer id);
public void saveClazz(Clazz clazz);
public void deleteClazzById(Integer id);
//根据ID修改Clazz(修改Clazz的id)
public void updateClazzById(Integer id1,Integer id2);
//根据ID修改Clazz
public void updateClazzById1(Clazz clazz);
}
StudentDao:
public interface StudentDao {
public Student selectStudentByClazzId(Integer id);
public Student selectStudentById(Integer id);
public void saveStudent(Student student);
public void updateStudentById(Student student);
public void updateStudentById1(Student student);
}
4、映射文件
ClazzMapper:
clazzResultMap 中使用
fetchType:该属性的取值有eager和lazy,eager表示立即加载,即查询Clazz对象的时候,会立即执行关联的selectStudentByClazzId中定义的SQL语句去查询班级所有学生;lazy表示懒加载,其不会立即发送SQL语句去查询所有班级的学生。
懒加载需要在mybatis-config.xml中配置:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.my.dao.ClazzDao">
<!-- 查询 -->
<select id="selectClazzById" parameterType="int" resultMap="clazzResultMap">
select * from tb_class where id=#{id}
</select>
<resultMap type="com.my.bean.Clazz" id="clazzResultMap">
<id property="id" column="id"/>
<result property="code" column="code" />
<result property="name" column="name" />
<collection property="students" javaType="ArrayList"
column="id" ofType="com.my.bean.Student"
select="com.my.dao.StudentDao.selectStudentByClazzId" >
<id property="id" column="id"/>
<result property="name" column="name" />
<result property="sex" column="sex" />
<result property="age" column="age" />
</collection>
</resultMap>
<!-- 插入 -->
<insert id="saveClazz" parameterType="com.my.bean.Clazz" useGeneratedKeys="true" >
<!-- 获取刚插入的tb_clazz的自动生成的主键id;(用来插入tb_student表的clazz_id)-->
<selectKey keyProperty="id" resultType="int" order="AFTER">
SELECT LAST_INSERT_ID() AS ID
</selectKey>
insert into tb_class(code,name) values(#{code},#{name})
</insert>
<!-- 删除 :删除班级信息时,同时删除级联的学生信息,利用表的关联即可-->
<delete id="deleteClazzById" parameterType="int">
delete from tb_class where id=#{id}
</delete>
<!--修改: 同时修改班级信息与学生信息 -->
<update id="updateClazzById1" parameterType="com.my.vo.Clazz">
update tb_class set code=#{code},name=#{name} where id=#{id}
</update>
</mapper>
StudentMapper:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.my.dao.StudentDao">
<!-- 根据id查询学生信息 -->
<select id="selectStudentById" parameterType="int" resultMap="studentResultMapper">
select * from tb_class c,tb_student s
where where c.id=s.class_id
and s.id=#{id}
</select>
<!-- 根据班级id查询学生 -->
<select id="selectStudentByClazzId" parameterType="int" resultMap="studentResultMapper">
select * from tb_student where classid = 1
</select>
<resultMap type="com.my.bean.Student" id="studentResultMapper">
<id property="id" column="id" />
<result property="name" column="name" />
<result property="sex" column="sex" />
<result property="age" column="age" />
<!--多对一映射:association -->
<association property="clazz" javaType="com.my.bean.Clazz" >
<id property="id" column="id" />
<result property="code" column="code" />
<result property="name" column="name" />
</association>
</resultMap>
<!-- 插入 -->
<insert id="saveStudent" parameterType="com.my.bean.Student">
insert into tb_student(name,sex,age,classid) values(#{name},#{sex},#{age},#{clazz_id})
</insert>
<!--修改: 同时修改班级信息与学生信息 -->
<update id="updateStudentById1" parameterType="com.my.vo.Student">
update tb_student set name=#{name},sex=#{sex},age=#{age}, classid=#{clazz_id} where id=#{id}
</update>
</mapper>
5、工具类:MyBatisUtil
public class MyBatisUtil {
private static SqlSessionFactory factory;
public static SqlSession getSqlSession() {
try {
if(factory==null) {
InputStream inputStream;
inputStream = Resources.getResourceAsStream("mybatis.cfg.xml");
factory=new SqlSessionFactoryBuilder().build(inputStream);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return factory.openSession();
}
}
6、配置文件mybatis.cfg.xml
<?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>
<settings>
<setting name="logImpl" value="LOG4J" />
<!-- 设置懒加载 -->
</settings>
<!-- 配置mybatis运行环境 -->
<environments default="mysql">
<environment id="mysql">
<!-- type="JDBC" 代表使用JDBC的提交和回滚来管理事务 -->
<transactionManager type="JDBC" />
<!-- POOLED 表示支持JDBC数据源连接池 -->
<!-- UNPOOLED 表示不支持数据源连接池 -->
<!-- JNDI 表示支持外部数据源连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/db_user" />
<property name="username" value="root" />
<property name="password" value="123" />
</dataSource>
</environment>
</environments>
<mappers>
<!-- 告知映射文件方式1,一个一个的配置-->
<mapper resource="com/my/mapper/StudentMapper.xml"/>
<mapper resource="com/my/mapper/ClazzMapper.xml"/>
</mappers>
</configuration>
7、测试类:
public class Test {
public static SqlSession session;
private static ClazzDao dao;
private static StudentDao stuDao;
public static void main(String[] args) {
// TODO Auto-generated method stub
session=MyBatisUtil.getSqlSession();
dao=session.getMapper(ClazzDao.class);
stuDao=session.getMapper(StudentDao.class);
//查询测试
// Clazz clazz=dao.selectClazzById(1);
// //查看学生信息
// List stuList=clazz.getStudents();
// //迭代查询学生信息
// for(Student stu:stuList){
// System.out.println(stu.getId()+","+stu.getName()+","+stu.getSex()+","+stu.getAge());
// }
// session.commit();
// session.close();
//插入测试
Clazz c1=new Clazz();
c1.setName("一班");
c1.setCode("001");
dao.saveClazz(c1);
Student s1=new Student();
s1.setName("wang1");
s1.setSex("男");
s1.setAge(18);
s1.setClazz_id(c1.getId());
Student s2=new Student();
s2.setName("wang2");
s2.setSex("女");
s2.setAge(19);
s2.setClazz_id(c1.getId());
stuDao.saveStudent(s1);
stuDao.saveStudent(s2);
session.commit();
//删除测试
dao.deleteClazzById(9);
//修改:clazz_id与id 不修改
Clazz c3=new Clazz();
c3.setCode("008");
c3.setName("软件1611");
c3.setId(15);
dao.updateClazzById1(c3);
Student s1=new Student();
s1.setName("孙一");
s1.setSex("男");
s1.setId(15);
s1.setAge(22);
s1.setClazz_id(c3.getId());
Student s2=new Student();
s2.setName("孙二");
s2.setSex("女");
s2.setId(16);
s2.setAge(24);
s2.setClazz_id(c3.getId());
stuDao.updateStudentById1(s1);
stuDao.updateStudentById1(s2);
session.commit();
session.close();
}
}