之前进行了SqlSessionFactory工具类优化
本节对Class表进行数据添加
步骤与Teacher数据添加完全一致
纠正3-1的目录结构 Dao文件都是放在dao目录下 mapper文件只放dao.xml文件
记得在mybatis-config.xml的mappers标签中添加xml文件映射
<mappers>
<mapperresource="com/teikin/mybatis/dao/mapper/MyBatisTeacherDao.xml"></mapper>
<mapperresource="com/teikin/mybatis/dao/mapper/MyBatisClassDao.xml"></mapper>
</mappers>
如果熟悉掌握了3-1,其实完全可以直接写出对class表的数据添加。
但为了让教程更详细,还是把完整代码在此贴出。(无注释)
与class表对应的实体类
package com.teikin.mybatis.dao.entity;
public class MyBatisClass {
private Long classId;
private String className;
private Long teacherId;
public Long getClassId() {
return classId;
}
public void setClassId(Long classId) {
this.classId = classId;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public Long getTeacherId() {
return teacherId;
}
public void setTeacherId(Long teacherId) {
this.teacherId = teacherId;
}
@Override
public String toString() {
return "MyBatisClass{" +
"classId=" + classId +
", className='" + className + '\'' +
", teacherId=" + teacherId +
'}';
}
}
MyBatisClassDao(MyBatisSqlSessionFactory是之前创建的优化工具类噢)
package com.teikin.mybatis.dao;
import com.teikin.mybatis.util.MyBatisSqlSessionFactory;
import org.apache.ibatis.session.SqlSession;
public class MyBatisClassDao {
private SqlSession sqlSession=null;
public int addClass(){
sqlSession= MyBatisSqlSessionFactory.getSqlSession();
int rowCount=sqlSession.insert("com.teikin.mybatis.dao.mapper.MyBatisClassDao.addClass");
sqlSession.commit();
sqlSession.close();
return rowCount;
}
}
MyBatisClassDao.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.teikin.mybatis.dao.mapper.MyBatisClassDao">
<insert id="addClass">
insert into Class set class_name="终极一班",teacher_id="1"
</insert>
</mapper>
Test类
package com.teikin.mybatis.dao;
import org.junit.Test;
public class MyBatisClassDaoTest {
private MyBatisClassDao classdao=null;
@Test
public void testAddClass(){
classdao=new MyBatisClassDao();
int rowCount=classdao.addClass();
System.out.println("addClass影响的行数:"+rowCount);
}
}
运行成功后,数据库中的class表就会新增“终极一班”这个班级。