MyBatis学习(一):简单的运行
1、准备工作
jar包:
mybatis-3.4.4.jar,下载地址:https://github.com/mybatis/ignite-cache/releases
mysql-connector-java-5.1.40-bin.jar,下载地址:https://dev.mysql.com/downloads/connector/j/
项目目录结构:
数据库建标语句
/*如果已经存在此数据库,先删除*/ drop database if exists sqltest ; /*创建并设置编码为UTF-8*/ create database sqltest default character set utf8 ; /*选择数据库*/ use sqltest ; /*删除已有的学生表*/ drop table if exists tb_student ; /*创建学生表*/ CREATE TABLE `tb_student` ( `id` int(11) NOT NULL AUTO_INCREMENT, `stuId` varchar(45) DEFAULT NULL, `name` varchar(45) DEFAULT NULL, `clsId` varchar(45) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*插入学生的数据*/ insert into tb_student (stuId,name,clsId) value ('1001','张三','201') ; insert into tb_student (stuId,name,clsId) value ('1002','李四','201') ; insert into tb_student (stuId,name,clsId) value ('1003','王五','201') ; insert into tb_student (stuId,name,clsId) value ('1004','赵六','202') ; insert into tb_student (stuId,name,clsId) value ('1005','巩发财','202') ; insert into tb_student (stuId,name,clsId) value ('1006','柏拉图','202') ; insert into tb_student (stuId,name,clsId) value ('1007','钱老虎','203') ; insert into tb_student (stuId,name,clsId) value ('1008','杨伟','203') ; insert into tb_student (stuId,name,clsId) value ('1009','陈海','203') ;
二、代码编写
实体类Student:
package org.yoki.edu.main.vo; public class Student { private Integer id; private String stuId; private String name; private String clsId; /*省略setter、getter方法*/ }
MyBatis的配置文件:
<?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> <!-- typeAliases必须写在environments和mappers前面,不然报错,这是dtd格式限制的 --> <typeAliases> <!-- 用于在实体类的映射文件进行使用student,而不用每次使用类的全名 --> <typeAlias type="org.yoki.edu.main.vo.Student" alias="student" /> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <!-- 数据库链接信息,注:分号改为&转义符,防止报错 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/sqltest?useUnicode=true&characterEncoding=UTF-8&useSSL=false" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> <mappers> <!-- 实体类的映射文件 --> <mapper resource="org/yoki/edu/main/vo/StudentMapper.xml" /> </mappers> </configuration>
实体类Student配置文件:
<?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"> <!-- namespace随意内容 --> <mapper namespace="this.is.student.mapper.namespace"> <!-- 方法一 --> <!-- type属性对应与在MyBatis配置文件中typeAliases标签下定义的引用 --> <resultMap id="studentMapper" type="student"> <!-- 属性名称<>列名 --> <id property="id" column="id" /> <result property="stuId" column="stuId" /> <result property="name" column="name" /> <result property="clsId" column="clsId" /> </resultMap> <!-- resultMap属性值对应 --> <select id="selectById" resultMap="studentMapper"> select * from tb_student where id = #{id} </select> <!-- 方法二 --> <!-- resultType可以使用类的全名,也可以使用MyBatis配置文件中typeAliases标签下定义的引用 --> <!-- <select id="selectById" resultType="org.yoki.edu.main.vo.Student"> --> <!-- select * from tb_student where id = #{id} --> <!-- </select> --> </mapper>
SessionUtils(用于初始化SqlSessionFactory和提供获取SqlSession的接口):
package org.yoki.edu.utils; import java.io.IOException; import java.io.InputStream; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class SessionUtils { private static SqlSessionFactory fa = null ; static{ /*静态代码块,在类加载后执行*/ String resource = "org/yoki/edu/utils/mybatis-config.xml" ; InputStream input; try { /*获取配置文件的输入流*/ input = Resources.getResourceAsStream(resource); /*根据输入流生成SqlSessionFactory*/ fa = new SqlSessionFactoryBuilder().build(input) ; int j = 0 ; } catch (IOException e) { e.printStackTrace(); } } public SqlSession getSqlSession(){ if(null == fa) return null; SqlSession session = fa.openSession() ; return session ; } }
StudentDao(这里偷懒没有使用接口):
package org.yoki.edu.main.dao; import org.apache.ibatis.session.SqlSession; import org.yoki.edu.main.vo.Student; import org.yoki.edu.utils.SessionUtils; public class StudentDao { private SessionUtils utils = new SessionUtils() ; public Student getById(Integer id){ SqlSession session = utils.getSqlSession() ; /*selectOne的第一个参数对应映射文件的namespace + '.' + (select、update、insert、delete)id*/ Student st = session.selectOne("this.is.student.mapper.namespace" + ".selectById", id) ; return st ; } }
测试类:
package org.yoki.edu.main; import org.yoki.edu.main.dao.StudentDao; import org.yoki.edu.main.vo.Student; public class MainRun { public static void main(String[] args) { StudentDao dao = new StudentDao() ; Student st = dao.getById(2) ; System.out.println(st); } }
结果: