本文共 3054 字,大约阅读时间需要 10 分钟。
映射配置文件是 MyBatis 具体实现中最重要的部分,它定义了数据访问逻辑,包含SQL 操作和数据绑定映射关系。
在映射配置文件的 <mapper>
标签内,编写 SQL 语句实现通过 ID 查询一行记录的功能。
调用示例:
public void selectById() throws Exception { InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession sqlSession = sqlSessionFactory.openSession(); Student stu = sqlSession.selectOne("StudentMapper.selectById", 3); System.out.println(stu); sqlSession.close(); is.close();}
INSERT INTO student VALUES(#{sid}, #{name}, #{age}, #{birthday});
调用示例:
public void insert() throws Exception { InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession sqlSession = sqlSessionFactory.openSession(); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Student stu = new Student(5, "大王", 26, dateFormat.parse("1999-09-09")); int res = sqlSession.insert("StudentMapper.insert", stu); sqlSession.commit(); System.out.println(res); sqlSession.close(); is.close();}
UPDATE student SET name=#{name}, age=#{age}, birthday=#{birthday} WHERE sid=#{sid}
调用示例:
public void update() throws Exception { InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession sqlSession = sqlSessionFactory.openSession(); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Student stu = new Student(5, "大李", 21, dateFormat.parse("2000-01-01")); int res = sqlSession.update("StudentMapper.update", stu); sqlSession.commit(); if (res != 0) { System.out.println("修改成功!"); } sqlSession.close(); is.close();}
DELETE FROM student WHERE sid=#{sid}
调用示例:
public void delete() throws Exception { InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession sqlSession = sqlSessionFactory.openSession(); int res = sqlSession.delete("StudentMapper.delete", 5); sqlSession.commit(); if (res != 0) { System.out.println("删除成功!"); } sqlSession.close(); is.close();}
核心配置文件配置了 MyBatis 的核心设置,包括数据库环境、事务管理、连接池参数等。
MyBatis 内置了许多常用的别名,如:| 别名 | 对应 Java 类型 ||------------|----------------------------|| string | java.lang.String || long | java.lang.Long || int | java.lang.Integer || double | java.lang.Double || boolean | java.lang.Boolean |
MyBatis 的核心配置文件主要用于配置数据库环境和资源管理,确保应用程序能够正常连接数据库,并在多个环境下工作。
转载地址:http://upusz.baihongyu.com/