【MyBtis】配置和映射
MyBatis 的真正强大之外在于它的映射语句,这也是它的魅力所在。由于它的异常强大,映射器的XML文件就显得相对简单。如果将其与具有相同功能的 JDBC 代码进行对比,会立即发现其省掉了将近 95% 的代码。MyBatis 就是针对 SQL 构建的并且比普通的方法效果更好。
(1)实现表数据的增、删、改、查;
(2)MyBatis主配置文件;
(3)XML映射文件;
(4)高级结果映射。
11.1 示例:实现表数据的增、删、改、查
1.创建工程mybatis_DML demo
在 idea 中创建 Maven Project,如图11-1所示,“GroupID“ 选项中输入 “com.mialab” ,在 “ArtifactId” 选项输入“student”最终完成的 student 工程目录和 student 初始表数据如图11-1和图11-2所示。
图11-1 mybatisDML_demo 工程目录结构
图11-2student表中的数据
2.创建数据库操作的工具类:DBOperatorMgr.java
在MyBatis 使用中,如果每个方法执行时都需要读取配置文件,并根据配置文件的信息构建SqlSessionFactory对象,然后创建SqlSession 对象,这会导致类大量的重复代码。为了简化开发,需要将重复代码封装到一个工具类中。如下:
public class DBOperatorMgr { static Logger logger = Logger.getLogger(DBOperatorMgr.class.getName()); private static DBOperatorMgr dbMgr; private SqlSessionFactory sqlSessionFactory; private DBOperatorMgr() { String resource = "mybatis-config.xml"; InputStream inputStream; try { inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (Exception e) { logger.error(e.toString()); } } public static DBOperatorMgr getInstance() { if (dbMgr == null) { dbMgr = new DBOperatorMgr(); } return dbMgr; } public SqlSessionFactory getSqlSessionFactory() { return sqlSessionFactory; } }
3.创建映射接口
public interface StudentMapper { public Student getStudent(String sno); public int addStudent(Student student); public List<Student> getSudentAll(); public int updateStudent(Student student); public int deleteStudent(String sno); }
4.创建XML映射文件
在包com.mialab.mybatis_DML_demomapper 中创建 StudentMapper.xml文件。
<mapper namespace="com.mialab.mybatis_DML_demo.mapper.StudentMapper"> <select id="getStudent" resultType="com.mialab.mybatis_DML_demo.domain.Student"> select * from student where sno = #{sno} </select> <insert id="addStudent" parameterType="student"> insert into student(sno,name,sex,age,dept_no) values(#{sno},#{name},#{sex},#{age},#{dept_no}) </insert> <resultMap id="studentResultMap" type="student"> <id property="sno" column="sno" /> <result property="name" column="name" /> <result property="sex" column="sex" /> <result property="age" column="age" /> <result property="dept_no" column="dept_no" /> </resultMap> <select id="getSudentAll" resultMap="studentResultMap"> select * from student </select> <update id="updateStudent" parameterType="student"> update student set name = #{name}, sex = #{sex}, age = #{age}, dept_no = #{dept_no} where sno = #{sno} </update> <delete id="deleteStudent" parameterType="String"> delete from student where sno = #{sno} </delete> </mapper>
5.测试
如图11-1所示,在src/main/java 中创建 Package“com.mialab.mybatis_DML demo.main”。在此包中创建测试类DML_Mainjava,主要代码:
public class DML_Main { public static void main(String[] args) { //testInsert(); //testSelectAll(); testSelect("20171509"); //testUpdate(); // testDelete("20171622"); } private static void testDelete(String sno) { Logger log = Logger.getLogger(DML_Main.class); SqlSession session = null; try { session = DBOperatorMgr.getInstance().getSqlSessionFactory().openSession(); StudentMapper mapper = session.getMapper(StudentMapper.class); mapper.deleteStudent(sno); session.commit(); } catch(Exception ex) { session.rollback(); ex.printStackTrace(); } finally { if (session != null) { session.close(); } } } private static void testSelectAll() { Logger log = Logger.getLogger(DML_Main.class); SqlSession session = null; try { session = DBOperatorMgr.getInstance().getSqlSessionFactory().openSession(); StudentMapper mapper = session.getMapper(StudentMapper.class); List<Student> stu_list = mapper.getSudentAll(); for(Student stu:stu_list) { //System.out.println(stu); log.info(stu); } } finally { if (session != null) { session.close(); } } } private static void testInsert() { Logger log = Logger.getLogger(DML_Main.class); SqlSession session = null; try { session = DBOperatorMgr.getInstance().getSqlSessionFactory().openSession(); StudentMapper mapper = session.getMapper(StudentMapper.class); Student student = new Student(); student.setSno("20171622"); student.setName("李白"); student.setAge(88); student.setSex("男"); student.setDept_no("2609"); log.info(student); mapper.addStudent(student); session.commit(); } catch(Exception ex) { session.rollback(); ex.printStackTrace(); } finally { if (session != null) { session.close(); } } } private static void testSelect(String sno) { Logger log = Logger.getLogger(DML_Main.class); SqlSession session = null; try { session = DBOperatorMgr.getInstance().getSqlSessionFactory().openSession(); StudentMapper mapper = session.getMapper(StudentMapper.class); Student student = mapper.getStudent(sno); //System.out.println(student); log.info(student); } finally { if (session != null) { session.close(); } } } private static void testUpdate() { Logger log = Logger.getLogger(DML_Main.class); SqlSession session = null; try { session = DBOperatorMgr.getInstance().getSqlSessionFactory().openSession(); StudentMapper mapper = session.getMapper(StudentMapper.class); Student student = new Student(); student.setSno("20171622"); student.setName("苏东坡"); student.setAge(68); student.setSex("女"); student.setDept_no("2612"); log.info(student); mapper.updateStudent(student); session.commit(); } catch(Exception ex) { session.rollback(); ex.printStackTrace(); } finally { if (session != null) { session.close(); } } } }
先测试 testSelectA11() 方法。如图 11-1 所示,右击comm.ialab.mybatis _DML_demo.main包中的DML_Main.java,在弹出的快捷菜单中选择“Run DML_Main.java”选项,在控制台中可以得到以下的结果:
INFO [main] - Student [sno=20171508, name=李勇, sex=男, age=20, dept_no=2601] INFO [main] - Student [sno=20171509, name=刘娟, sex=女, age=19, dept_no=2602] INFO [main] - Student [sno=20171622, name=李白, sex=男, age=88, dept_no=2609]
可分别对增、删、改、查的方法testInsert()、testUpdate()等进行测试。