第一个Mybatis程序示例 Mybatis简介(一)
- 要求通过xml或注解的方式将要执行的各种statement(statement、preparedStatemnt、CallableStatement)配置起来
- 并通过java对象和statement中的sql进行映射生成最终执行的sql语句
- mybatis框架执行sql并将结果映射成java对象并返回。
第一个Mybatis程序
1.新建项目
2.包获取与导入
3.数据库准备
CREATE TABLE `student` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL DEFAULT '默认姓名' COMMENT '姓名', `age` int(11) DEFAULT '1', `sex` varchar(255) DEFAULT NULL, `random` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4.配置文件设置
5.SQL映射文件设置
6.调整配置文件
7.创建实体类Student
8.修改myMapper.xml文件
9.测试
初识Mybatis
- 要从哪个数据库进行操作?
- 要操作的SQL在哪里?
- 执行哪个SQL?通过层级的命名标识符定位
- 执行SQL的细节信息有哪些?SQL内容,参数内容,返回类型等
- 配置信息搭建了Mybatis应用框架
- 映射设置了一次执行的所需信息
<mappers> <package name="org.mybatis.builder"/> </mappers>
附录:完整代码
CREATE TABLE `student` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL DEFAULT '默认姓名' COMMENT '姓名', `age` int(11) DEFAULT '1', `sex` varchar(255) DEFAULT NULL, `random` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
项目结构
mybatis-config.xml
<?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> <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/sampledb?useUnicode=true&characterEncoding=utf-8"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <mapper resource="mapper/myMapper.xml"/> </mappers> </configuration>
myMapper.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="mapper.myMapper"> <select id="selectStudent" resultType="first.Student"> select * from student where id = #{id} </select> </mapper>
Student
package first; public class Student { private Long id; private String name; private Integer age; private String sex; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } @Override public String toString() { final StringBuilder sb = new StringBuilder("Student{"); sb.append("id=").append(id); sb.append(", name='").append(name).append('\''); sb.append(", age=").append(age); sb.append(", sex='").append(sex).append('\''); sb.append('}'); return sb.toString(); } }
测试代码
package first; 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 Test { public static void main(String[] args) throws Exception { /* * 每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为中心的。 * SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。 * 而 SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先定制的 Configuration 的实例构建出 SqlSessionFactory 的实例。 * */ String resource = "config/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); /* * 从 SqlSessionFactory 中获取 SqlSession * */ SqlSession session = sqlSessionFactory.openSession(); try { Student student = (Student) session.selectOne("mapper.myMapper.selectStudent", 2); System.out.println(student); } finally { session.close(); } } }
接口应用
package first; public interface MyMapper { Student selectStudent(Integer id); }
<?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="first.MyMapper"> <select id="selectStudent" resultType="first.Student"> select * from student where id = #{id} </select> </mapper>
package first; 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 Test2 { public static void main(String[] args) throws Exception { /* * 每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为中心的。 * SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。 * 而 SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先定制的 Configuration 的实例构建出 SqlSessionFactory 的实例。 * */ String resource = "config/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream,"development"); /* * 从 SqlSessionFactory 中获取 SqlSession * */ SqlSession session = sqlSessionFactory.openSession(); try { MyMapper mapper = session.getMapper(MyMapper.class); Student student = mapper.selectStudent(2); System.out.println(student); } finally { session.close(); } } }
MyMapper mapper = session.getMapper(MyMapper.class); Student student = mapper.selectStudent(2);