Mybatis注解开发单表、多表操作的实现代码
一.Mybatis注解开发单表操作***
1.1MyBatis的常用注解
之前我们在Mapper映射文件中编写的sql语句已经各种配置,其实是比较麻烦的
而这几年来注解开发越来越流行,Mybatis也可以使用注解开发方式,这样我们就可以减少编写Mapper映射文件了
常用注解
@Select(“查询的SQL语句”):执行查询操作注解
@Insert(“查询的SQL语句”):执行新增操作注解
@Update(“查询的SQL语句”):执行修改操作注解
@Delete(“查询的SQL语句”):执行删除操作注解
1.2注解实现查询操作
表:我们还是用db1中的student表
新建mybatis04项目
- 导入所需要的包
- 配置相关的几个配置文件(配置文件的内容与之前项目都一致,这里就不在罗列)
- 新建所需要的包
javabean
packagecom.itheima.bean; publicclassStudent{ privateIntegerid; privateStringname; privateIntegerage; publicStudent(){ } publicStudent(Integerid,Stringname,Integerage){ this.id=id; this.name=name; this.age=age; } publicIntegergetId(){ returnid; } publicvoidsetId(Integerid){ this.id=id; } publicStringgetName(){ returnname; } publicvoidsetName(Stringname){ this.name=name; } publicIntegergetAge(){ returnage; } publicvoidsetAge(Integerage){ this.age=age; } @Override publicStringtoString(){ return"Student{"+ "id="+id+ ",name='"+name+'\''+ ",age="+age+ '}'; } }
创建mapper接口
packagecom.itheima.mapper; importcom.itheima.bean.Student; importorg.apache.ibatis.annotations.Select; importjava.util.List; publicinterfaceStudentMapper{ //查询全部 @Select("SELECT*FROMstudent") publicabstractListselectAll(); }
配置MyBatisConfig.xml
测试类:com.itheima.test.Test01
@Test publicvoidselectAll()throwsException{ //1.加载核心配置文件 InputStreamis=Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactorysqlSessionFactory=newSqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取SqlSession对象 SqlSessionsqlSession=sqlSessionFactory.openSession(true); //4.获取StudentMapper接口的实现类对象 StudentMappermapper=sqlSession.getMapper(StudentMapper.class); //5.调用实现类对象中的方法,接收结果 Listlist=mapper.selectAll(); //6.处理结果 for(Studentstudent:list){ System.out.println(student); } }
注意:
修改MyBatis的核心配置文件,我们使用了注解替代的映射文件,所以我们只需要加载使用了注解的Mapper接口即可
或者指定扫描包含映射关系的接口所在的包也可以
1.3注解实现新增操作
StudentMapper新增接口方法
//新增操作:sql的参数与之前的写法一致,从insert方法的参数中获取对应属性值 @Insert("INSERTINTOstudentVALUES(#{id},#{name},#{age})") publicabstractIntegerinsert(Studentstu);
测试方法
@Test publicvoidinsert()throwsException{ //1.加载核心配置文件 InputStreamis=Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactorysqlSessionFactory=newSqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取SqlSession对象 SqlSessionsqlSession=sqlSessionFactory.openSession(true); //4.获取StudentMapper接口的实现类对象 StudentMappermapper=sqlSession.getMapper(StudentMapper.class); //5.调用实现类对象中的方法,接收结果 Studentstu=newStudent(4,"赵六",26); Integerresult=mapper.insert(stu); //6.处理结果 System.out.println(result); //7.释放资源 sqlSession.close(); is.close(); }
返回自动增长主键
介绍
代码
- 在insert注解之上添加Options注解
- 指定主键列为id,主键属性为id(意味会将注解列id最终的自增结果返回,并且赋值给stu的id属性)
测试
在mapper.insert(stu)之后,会将操作结果返回,并且也会对stu本身的id进行赋值
结果
1.4注解实现修改操作
StudentMapper新增接口方法
//修改操作 @Update("UPDATEstudentSETname=#{name},age=#{age}WHEREid=#{id}") publicabstractIntegerupdate(Studentstu);
测试方法
@Test publicvoidupdate()throwsException{ //1.加载核心配置文件 InputStreamis=Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactorysqlSessionFactory=newSqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取SqlSession对象 SqlSessionsqlSession=sqlSessionFactory.openSession(true); //4.获取StudentMapper接口的实现类对象 StudentMappermapper=sqlSession.getMapper(StudentMapper.class); //5.调用实现类对象中的方法,接收结果 Studentstu=newStudent(4,"赵六",36); Integerresult=mapper.update(stu); //6.处理结果 System.out.println(result); //7.释放资源 sqlSession.close(); is.close(); }
1.5注解实现删除操作
StudentMapper新增接口方法
//删除操作 @Delete("DELETEFROMstudentWHEREid=#{id}") publicabstractIntegerdelete(Integerid);
测试方法
@Test publicvoiddelete()throwsException{ //1.加载核心配置文件 InputStreamis=Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactorysqlSessionFactory=newSqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取SqlSession对象 SqlSessionsqlSession=sqlSessionFactory.openSession(true); //4.获取StudentMapper接口的实现类对象 StudentMappermapper=sqlSession.getMapper(StudentMapper.class); //5.调用实现类对象中的方法,接收结果 Integerresult=mapper.delete(4); //6.处理结果 System.out.println(result); //7.释放资源 sqlSession.close(); is.close(); }
1.6注解开发总结
注解可以简化开发操作,省略映射配置文件的编写
常用注解
@Select(“查询的SQL语句”):执行查询操作注解
@Insert(“查询的SQL语句”):执行新增操作注解
@Update(“查询的SQL语句”):执行修改操作注解
@Delete(“查询的SQL语句”):执行删除操作注解
配置映射关系
二.MyBatis注解开发的多表操作
2.1MyBatis的注解实现复杂映射开发
- 实现复杂关系映射之前我们可以在映射文件中通过配置
来实现, - 使用注解开发后,我们可以使用@Results注解,@Result注解,@One注解,@Many注解组合完成复杂关系的配置
2.2一对一查询
2.2.0准备工作
创建项目:mybatis05
javabean-card
packagecom.itheima.bean; publicclassCard{ privateIntegerid;//主键id privateStringnumber;//身份证号 privatePersonp;//所属人的对象 publicCard(){ } publicCard(Integerid,Stringnumber,Personp){ this.id=id; this.number=number; this.p=p; } publicIntegergetId(){ returnid; } publicvoidsetId(Integerid){ this.id=id; } publicStringgetNumber(){ returnnumber; } publicvoidsetNumber(Stringnumber){ this.number=number; } publicPersongetP(){ returnp; } publicvoidsetP(Personp){ this.p=p; } @Override publicStringtoString(){ return"Card{"+ "id="+id+ ",number='"+number+'\''+ ",p="+p+ '}'; } }
javabean-person
packagecom.itheima.bean; publicclassPerson{ privateIntegerid;//主键id privateStringname;//人的姓名 privateIntegerage;//人的年龄 publicPerson(){ } publicPerson(Integerid,Stringname,Integerage){ this.id=id; this.name=name; this.age=age; } publicIntegergetId(){ returnid; } publicvoidsetId(Integerid){ this.id=id; } publicStringgetName(){ returnname; } publicvoidsetName(Stringname){ this.name=name; } publicIntegergetAge(){ returnage; } publicvoidsetAge(Integerage){ this.age=age; } @Override publicStringtoString(){ return"Person{"+ "id="+id+ ",name='"+name+'\''+ ",age="+age+ '}'; } }
cardMapper接口:我们的核心就是要在Card中做一些处理,实现一对一的查询
packagecom.itheima.one_to_one; importcom.itheima.bean.Card; importjava.util.List; publicinterfaceCardMapper{ //查询全部 publicabstractListselectAll(); }
2.2.1一对一查询的模型
一对一查询的需求:查询一个用户信息,与此同时查询出该用户对应的身份证信息
2.2.2一对一查询的语句
对应的sql语句:
SELECT*FROMcard;--只根据这个sql语句只能查询出来card的数据 SELECT*FROMpersonWHEREid=#{id};--需要根据card表中查询出来的pid,再次查询person数据才能将person数据也查询出来
2.2.3创建PersonMapper接口
publicinterfacePersonMapper{ //根据id查询 @Select("SELECT*FROMpersonWHEREid=#{id}") publicabstractPersonselectById(Integerid); }
2.2.4使用注解配置CardMapper
publicinterfaceCardMapper{ //查询全部 @Select("SELECT*FROMcard") @Results({ @Result(column="id",property="id"), @Result(column="number",property="number"), @Result( property="p",//被包含对象的变量名 javaType=Person.class,//被包含对象的实际数据类型 column="pid",//根据查询出的card表中的pid字段来查询person表 /* one、@One一对一固定写法 select属性:指定调用哪个接口中的哪个方法 */ one=@One(select="com.itheima.one_to_one.PersonMapper.selectById") ) }) publicabstractListselectAll(); }
2.2.5测试类
packagecom.itheima.one_to_one; importcom.itheima.bean.Card; importorg.apache.ibatis.io.Resources; importorg.apache.ibatis.session.SqlSession; importorg.apache.ibatis.session.SqlSessionFactory; importorg.apache.ibatis.session.SqlSessionFactoryBuilder; importorg.junit.Test; importjava.io.InputStream; importjava.util.List; publicclassTest01{ @Test publicvoidselectAll()throwsException{ //1.加载核心配置文件 InputStreamis=Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactorysqlSessionFactory=newSqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取SqlSession对象 SqlSessionsqlSession=sqlSessionFactory.openSession(true); //4.获取CardMapper接口的实现类对象 CardMappermapper=sqlSession.getMapper(CardMapper.class); //5.调用实现类对象中的方法,接收结果 Listlist=mapper.selectAll(); //6.处理结果 for(Cardcard:list){ System.out.println(card); } //7.释放资源 sqlSession.close(); is.close(); } }
结果
2.2.6一对一配置总结
@Results:封装映射关系的父注解。 Result[]value():定义了Result数组 @Result:封装映射关系的子注解。 column属性:查询出的表中字段名称 property属性:实体对象中的属性名称 javaType属性:被包含对象的数据类型 one属性:一对一查询固定属性 @One:一对一查询的注解。 select属性:指定调用某个接口中的方法
2.2.7分析
2.3一对多查询
2.3.1一对多查询的模型
一对多查询的需求:查询一个课程,与此同时查询出该该课程对应的学生信息
2.3.2一对多查询的语句
对应的sql语句:
SELECT*FROMclasses SELECT*FROMstudentWHEREcid=#{cid}
2.3.3创建StudentMapper接口
publicinterfaceStudentMapper{ //根据cid查询student表 @Select("SELECT*FROMstudentWHEREcid=#{cid}") publicabstractListselectByCid(Integercid); }
2.3.4使用注解配置Mapper
publicinterfaceClassesMapper{ //查询全部 @Select("SELECT*FROMclasses") @Results({ @Result(column="id",property="id"), @Result(column="name",property="name"), @Result( property="students",//被包含对象的变量名 javaType=List.class,//被包含对象的实际数据类型 column="id",//根据查询出的classes表的id字段来查询student表 /* many、@Many一对多查询的固定写法 select属性:指定调用哪个接口中的哪个查询方法 */ many=@Many(select="com.itheima.one_to_many.StudentMapper.selectByCid") ) }) publicabstractListselectAll(); }
2.3.5测试类
publicclassTest01{ @Test publicvoidselectAll()throwsException{ //1.加载核心配置文件 InputStreamis=Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactorysqlSessionFactory=newSqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取SqlSession对象 SqlSessionsqlSession=sqlSessionFactory.openSession(true); //4.获取ClassesMapper接口的实现类对象 ClassesMappermapper=sqlSession.getMapper(ClassesMapper.class); //5.调用实现类对象中的方法,接收结果 Listlist=mapper.selectAll(); //6.处理结果 for(Classescls:list){ System.out.println(cls.getId()+","+cls.getName()); List students=cls.getStudents(); for(Studentstudent:students){ System.out.println("\t"+student); } } //7.释放资源 sqlSession.close(); is.close(); } }
2.3.6一对多配置总结
@Results:封装映射关系的父注解。 Result[]value():定义了Result数组 @Result:封装映射关系的子注解。 column属性:查询出的表中字段名称 property属性:实体对象中的属性名称 javaType属性:被包含对象的数据类型 many属性:一对多查询固定属性 @Many:一对多查询的注解。 select属性:指定调用某个接口中的方法
2.3.7分析
2.4多对多查询
2.4.1多对多查询的模型
多对多查询的需求:查询学生以及所对应的课程信息
2.4.2多对多查询的语句
对应的sql语句:
SELECTDISTINCTs.id,s.name,s.ageFROMstudents,stu_crscWHEREsc.sid=s.id SELECTc.id,c.nameFROMstu_crsc,coursecWHEREsc.cid=c.idANDsc.sid=#{id}
2.4.3添加CourseMapper接口方法
publicinterfaceCourseMapper{ //根据学生id查询所选课程 @Select("SELECTc.id,c.nameFROMstu_crsc,coursecWHEREsc.cid=c.idANDsc.sid=#{id}") publicabstractListselectBySid(Integerid); }
2.4.4使用注解配置Mapper
publicinterfaceStudentMapper{ //查询全部 @Select("SELECTDISTINCTs.id,s.name,s.ageFROMstudents,stu_crscWHEREsc.sid=s.id") @Results({ @Result(column="id",property="id"), @Result(column="name",property="name"), @Result(column="age",property="age"), @Result( property="courses",//被包含对象的变量名 javaType=List.class,//被包含对象的实际数据类型 column="id",//根据查询出student表的id来作为关联条件,去查询中间表和课程表 /* many、@Many一对多查询的固定写法 select属性:指定调用哪个接口中的哪个查询方法 */ many=@Many(select="com.itheima.many_to_many.CourseMapper.selectBySid") ) }) publicabstractListselectAll(); }
2.4.5测试类
publicclassTest01{ @Test publicvoidselectAll()throwsException{ //1.加载核心配置文件 InputStreamis=Resources.getResourceAsStream("MyBatisConfig.xml"); //2.获取SqlSession工厂对象 SqlSessionFactorysqlSessionFactory=newSqlSessionFactoryBuilder().build(is); //3.通过工厂对象获取SqlSession对象 SqlSessionsqlSession=sqlSessionFactory.openSession(true); //4.获取StudentMapper接口的实现类对象 StudentMappermapper=sqlSession.getMapper(StudentMapper.class); //5.调用实现类对象中的方法,接收结果 Listlist=mapper.selectAll(); //6.处理结果 for(Studentstudent:list){ System.out.println(student.getId()+","+student.getName()+","+student.getAge()); List courses=student.getCourses(); for(Coursecours:courses){ System.out.println("\t"+cours); } } //7.释放资源 sqlSession.close(); is.close(); } }
2.4.6多对多配置总结
@Results:封装映射关系的父注解。 Result[]value():定义了Result数组 @Result:封装映射关系的子注解。 column属性:查询出的表中字段名称 property属性:实体对象中的属性名称 javaType属性:被包含对象的数据类型 many属性:一对多查询固定属性 @Many:一对多查询的注解。 select属性:指定调用某个接口中的方法
2.4.7分析
三.构建sql
3.1SQL构建对象介绍
我们之前通过注解开发时,相关SQL语句都是自己直接拼写的。一些关键字写起来比较麻烦、而且容易出错。
MyBatis给我们提供了org.apache.ibatis.jdbc.SQL功能类,专门用于构建SQL语句
创建项目:将之前的注解的所有相关代码,配置文件拿过来
新建测试类:com.itheima.sql.SqlTest
packagecom.itheima.sql; publicclassSqlTest{ publicstaticvoidmain(String[]args){ Stringsql=getSql(); System.out.println(sql); } //定义方法,获取查询student表的sql语句 publicstaticStringgetSql(){ Stringsql="SELECT*FROMstudent"; returnsql; } }
如果sql语句比较长,sql中的关键字较多时,就可能会写错
修改代码:使用SQL类通过的方法来编写sql语句
packagecom.itheima.sql; importorg.apache.ibatis.jdbc.SQL; publicclassSqlTest{ publicstaticvoidmain(String[]args){ Stringsql=getSql(); System.out.println(sql); } //定义方法,获取查询student表的sql语句 /*publicstaticStringgetSql(){ Stringsql="SELECT*FROMstudent"; returnsql; }*/ publicstaticStringgetSql(){ Stringsql=newSQL(){//通过SQL类提供的方法来实现sql语句的编写 { SELECT("*"); FROM("student"); } }.toString(); returnsql; } }
结果
3.2查询功能的实现
定义功能类并提供获取查询的SQL语句的方法
新建类:com.itheima.sql.ReturnSql,定义获取sql语句的方法
packagecom.itheima.sql; importorg.apache.ibatis.jdbc.SQL; publicclassReturnSql{ //定义方法,返回查询的sql语句 publicStringgetSelectAll(){ returnnewSQL(){ { SELECT("*"); FROM("student"); } }.toString(); //以上代码说明:内层的花括号是一个构造代码块,在实例化一个对象时会先于构造方法执行,编译时会将构造代码块移入构造方法中 //如果上述不理解,可以使用以下方式:Builder风格 Stringsql=newSQL() .SELECT("*") .FROM("student") .toString(); returnsql; } }
- 那么如何获取这个提供了sql语句的方法呢?
- 之前是在Mapper接口中直接通过注解(@Select,@Insert等)来设置的sql
- 现在有提供了sql语句的方法,如何获取呢?
- 通过@SelectProvider注解来获取
@SelectProvider:生成查询用的SQL语句注解(调用提供sql语句的方法,获取到查询的sql语句)
type属性:用于指定生成SQL语句功能的类对象
method属性:用于指定类中要执行获取sql语句的方法(指定方法名,不加小括号)
修改StudentMapper
//查询全部 //@Select("SELECT*FROMstudent") //注意:method只是指定一个方法的名字,SelectProvider内部会自己调用 @SelectProvider(type=ReturnSql.class,method="getSelectAll") publicabstractListselectAll();
运行test包中的Test01的selectAll方法,能查询出数据即可
3.3新增功能的实现
定义功能类并提供获取新增的SQL语句的方法,在ReturnSql中增加如下方法:
//定义方法,返回新增的sql语句 publicStringgetInsert(Studentstu){ returnnewSQL(){ { INSERT_INTO("student"); INTO_VALUES("#{id},#{name},#{age}"); } }.toString(); }
@InsertProvider:生成新增用的SQL语句注解(调用提供sql语句的方法,获取到新增的sql语句)
type属性:生成SQL语句功能类对象
method属性:指定调用方法
修改StudentMapper
//新增功能 //@Insert("INSERTINTOstudentVALUES(#{id},#{name},#{age})") @InsertProvider(type=ReturnSql.class,method="getInsert") publicabstractIntegerinsert(Studentstu);
运行test包中的Test01的insert方法,能插入数据即可
3.4修改功能的实现
定义功能类并提供获取修改的SQL语句的方法
//定义方法,返回修改的sql语句 publicStringgetUpdate(Studentstu){ returnnewSQL(){ { UPDATE("student"); SET("name=#{name}","age=#{age}"); WHERE("id=#{id}"); } }.toString(); }
@UpdateProvider:生成修改用的SQL语句注解(调用提供sql语句的方法,获取到更新的sql语句)
type属性:生成SQL语句功能类对象
method属性:指定调用方法
修改StudentMapper
//修改功能 //@Update("UPDATEstudentSETname=#{name},age=#{age}WHEREid=#{id}") @UpdateProvider(type=ReturnSql.class,method="getUpdate") publicabstractIntegerupdate(Studentstu);
运行test包中的Test01的update方法,能更新数据即可
3.5删除功能的实现
定义功能类并提供获取删除的SQL语句的方法
//定义方法,返回删除的sql语句 publicStringgetDelete(Integerid){ returnnewSQL(){ { DELETE_FROM("student"); WHERE("id=#{id}"); } }.toString(); }
@DeleteProvider:生成删除用的SQL语句注解(调用提供sql语句的方法,获取到删除的sql语句)
type属性:生成SQL语句功能类对象
method属性:指定调用方法
修改StudentMapper
//删除功能 //@Delete("DELETEFROMstudentWHEREid=#{id}") @DeleteProvider(type=ReturnSql.class,method="getDelete") publicabstractIntegerdelete(Integerid);
运行test包中的Test01的delete方法,能删除数据即可
四.综合案例***
4.1系统介绍
我们之前在做学生管理系统时,使用的是原始JDBC操作数据库的,操作非常麻烦,现在我们使用MyBatis操作数据库,简化Dao的开发。
4.2环境搭建
创建数据库
--创建db3数据库 CREATEDATABASEdb3; --使用db3数据库 USEdb3; --创建用户表 CREATETABLEUSER( uidVARCHAR(50)PRIMARYKEY, --用户id ucodeVARCHAR(50), --用户标识 loginnameVARCHAR(100), --登录用户名 PASSWORDVARCHAR(100), --登录密码 usernameVARCHAR(100), --用户名 genderVARCHAR(10), --用户性别 birthdayDATE, --出生日期 dutydateDATE--入职日期 ); --添加一条测试数据 INSERTINTOUSERVALUES('11111111','zhangsan001','zhangsan','1234','张三','男','2008-10-28','2018-10-28'); --创建student表 CREATETABLEstudent( sidINTPRIMARYKEYAUTO_INCREMENT, --学生id NAMEVARCHAR(20), --学生姓名 ageINT, --学生年龄 birthdayDATE --学生生日 ); --添加数据 INSERTINTOstudentVALUES(NULL,'张三',23,'1999-09-23'),(NULL,'李四',24,'1998-08-10'), (NULL,'王五',25,'1996-06-06'),(NULL,'赵六',26,'1994-10-20');
将之前的“JDBC基础网页版”项目copy过来
运行起来:注意这个项目的虚拟目录必须是/,因为界面中的链接写死了
输入zhangsan,1234,登陆进去,我们现在要处理的是在校学生管理:
在这里,可以对学生进行增删改查,之前是通过jdbc实现的这些功能,现在我们需要通过mybatis来实现
增加jar包:
复制相关的配置文件:log4j和MyBatisConfig
修改config.properties(这个其实就是jdbc配置文件)
driver=com.mysql.jdbc.Driver url=jdbc:mysql://192.168.59.143:3306/db3 username=root password=itheima
修改MyBatisConfig主配置文件:
起别名的配置删掉
删除StudentDaoImpl,我们不需要实现类,我们会通过接口代理的方式来实现
修改StudentDao,给接口方法通过注解的方式配置sql语句
packagecom.itheima.dao; importcom.itheima.domain.Student; importorg.apache.ibatis.annotations.Delete; importorg.apache.ibatis.annotations.Insert; importorg.apache.ibatis.annotations.Select; importorg.apache.ibatis.annotations.Update; importjava.util.ArrayList; /* Dao层接口 */ publicinterfaceStudentDao{ //查询所有学生信息 @Select("SELECT*FROMstudent") publicabstractArrayListfindAll(); //条件查询,根据id获取学生信息 @Select("SELECT*FROMstudentWHEREsid=#{sid}") publicabstractStudentfindById(Integersid); //新增学生信息 @Insert("INSERTINTOstudentVALUES(#{sid},#{name},#{age},#{birthday})") publicabstractintinsert(Studentstu); //修改学生信息 @Update("UPDATEstudentSETname=#{name},age=#{age},birthday=#{birthday}WHEREsid=#{sid}") publicabstractintupdate(Studentstu); //删除学生信息 @Delete("DELETEFROMstudentWHEREsid=#{sid}") publicabstractintdelete(Integersid); }
修改StudentServiceImpl,删除之前的DaoImpl的逻辑
packagecom.itheima.service.impl; importcom.itheima.domain.Student; importcom.itheima.service.StudentService; importjava.util.List; /** *学生的业务层实现类 *@author黑马程序员 *@Companyhttp://www.itheima.com */ publicclassStudentServiceImplimplementsStudentService{ @Override publicListfindAll(){ } @Override publicStudentfindById(Integersid){ } @Override publicvoidsave(Studentstudent){ } @Override publicvoidupdate(Studentstudent){ } @Override publicvoiddelete(Integersid){ } }
4.3代码改造
我们主要是将原来的jdbc实现的方式改为mybatis实现
新建com.itheima.utils.MyBatisUtils.java
packagecom.itheima.utils; importorg.apache.ibatis.io.Resources; importorg.apache.ibatis.session.SqlSession; importorg.apache.ibatis.session.SqlSessionFactory; importorg.apache.ibatis.session.SqlSessionFactoryBuilder; importjava.io.IOException; /* 工具类 */ publicclassMyBatisUtils{ //私有构造方法 privateMyBatisUtils(){} //声明连接工厂对象 privatestaticSqlSessionFactorysqlSessionFactory; //静态代码块,读取核心配置文件并工厂对象赋值 static{ try{ sqlSessionFactory=newSqlSessionFactoryBuilder().build(Resources.getResourceAsStream("MyBatisConfig.xml")); }catch(IOExceptione){ e.printStackTrace(); } } //提供静态方法,返回SqlSession对象 publicstaticSqlSessiongetSqlSession(){ returnsqlSessionFactory.openSession(true); } }
修改StudentServiceImpl代码
packagecom.itheima.service.impl; importcom.itheima.dao.StudentDao; importcom.itheima.domain.Student; importcom.itheima.service.StudentService; importcom.itheima.utils.MyBatisUtils; importorg.apache.ibatis.session.SqlSession; importjava.util.ArrayList; importjava.util.List; /** *学生的业务层实现类 *@author黑马程序员 *@Companyhttp://www.itheima.com */ publicclassStudentServiceImplimplementsStudentService{ @Override publicListfindAll(){ //获取SqlSession对象 SqlSessionsqlSession=MyBatisUtils.getSqlSession(); //获取StudentDao接口的实现类对象 StudentDaomapper=sqlSession.getMapper(StudentDao.class); //调用实现类对象相应的功能 ArrayList list=mapper.findAll(); //释放资源 sqlSession.close(); //返回结果 returnlist; } @Override publicStudentfindById(Integersid){ //获取SqlSession对象 SqlSessionsqlSession=MyBatisUtils.getSqlSession(); //获取StudentDao接口的实现类对象 StudentDaomapper=sqlSession.getMapper(StudentDao.class); //调用实现类对象相应的功能 Studentstu=mapper.findById(sid); //释放资源 sqlSession.close(); //返回结果 returnstu; } @Override publicvoidsave(Studentstudent){ //获取SqlSession对象 SqlSessionsqlSession=MyBatisUtils.getSqlSession(); //获取StudentDao接口的实现类对象 StudentDaomapper=sqlSession.getMapper(StudentDao.class); //调用实现类对象相应的功能 mapper.insert(student); //释放资源 sqlSession.close(); } @Override publicvoidupdate(Studentstudent){ //获取SqlSession对象 SqlSessionsqlSession=MyBatisUtils.getSqlSession(); //获取StudentDao接口的实现类对象 StudentDaomapper=sqlSession.getMapper(StudentDao.class); //调用实现类对象相应的功能 mapper.update(student); //释放资源 sqlSession.close(); } @Override publicvoiddelete(Integersid){ //获取SqlSession对象 SqlSessionsqlSession=MyBatisUtils.getSqlSession(); //获取StudentDao接口的实现类对象 StudentDaomapper=sqlSession.getMapper(StudentDao.class); //调用实现类对象相应的功能 mapper.delete(sid); //释放资源 sqlSession.close(); } } packagecom.itheima.service.impl; importcom.itheima.dao.StudentDao; importcom.itheima.domain.Student; importcom.itheima.service.StudentService; importcom.itheima.utils.MyBatisUtils; importorg.apache.ibatis.session.SqlSession; importjava.util.ArrayList; importjava.util.List; /** *学生的业务层实现类 *@author黑马程序员 *@Companyhttp://www.itheima.com */ publicclassStudentServiceImplimplementsStudentService{ @Override publicList findAll(){ //获取SqlSession对象 SqlSessionsqlSession=MyBatisUtils.getSqlSession(); //获取StudentDao接口的实现类对象 StudentDaomapper=sqlSession.getMapper(StudentDao.class); //调用实现类对象相应的功能 ArrayList list=mapper.findAll(); //释放资源 sqlSession.close(); //返回结果 returnlist; } @Override publicStudentfindById(Integersid){ //获取SqlSession对象 SqlSessionsqlSession=MyBatisUtils.getSqlSession(); //获取StudentDao接口的实现类对象 StudentDaomapper=sqlSession.getMapper(StudentDao.class); //调用实现类对象相应的功能 Studentstu=mapper.findById(sid); //释放资源 sqlSession.close(); //返回结果 returnstu; } @Override publicvoidsave(Studentstudent){ //获取SqlSession对象 SqlSessionsqlSession=MyBatisUtils.getSqlSession(); //获取StudentDao接口的实现类对象 StudentDaomapper=sqlSession.getMapper(StudentDao.class); //调用实现类对象相应的功能 mapper.insert(student); //释放资源 sqlSession.close(); } @Override publicvoidupdate(Studentstudent){ //获取SqlSession对象 SqlSessionsqlSession=MyBatisUtils.getSqlSession(); //获取StudentDao接口的实现类对象 StudentDaomapper=sqlSession.getMapper(StudentDao.class); //调用实现类对象相应的功能 mapper.update(student); //释放资源 sqlSession.close(); } @Override publicvoiddelete(Integersid){ //获取SqlSession对象 SqlSessionsqlSession=MyBatisUtils.getSqlSession(); //获取StudentDao接口的实现类对象 StudentDaomapper=sqlSession.getMapper(StudentDao.class); //调用实现类对象相应的功能 mapper.delete(sid); //释放资源 sqlSession.close(); } }
员工管理也有增删改查,大家可以作为课下作业
到此这篇关于Mybatis注解开发单表、多表操作的实现代码的文章就介绍到这了,更多相关Mybatis注解开发内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。