第一个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 '',
`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 '',
`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);
第一个Mybatis程序示例 Mybatis简介(一)的更多相关文章
- 第一个Java程序示例——Hello World!【转】
本文转载自: 跟随世界潮流,第一个Java程序输出“Hell World!”. 通过Eclipse运行程序 启动Eclipse,在菜单中选择“文件 --> 新建 --> Java项目”,弹 ...
- iOS 5 :一个UIPageViewController程序示例
原文:http://www.techotopia.com/index.php/An_Example_iOS_5_iPhone_UIPageViewController_Application 在Xco ...
- 我的第一个Java程序和Java简介
public calss HelloWorld{ public static void main(String[] args){ System.out.println("Hello Worl ...
- 我的第一个Mybatis程序
第一个Mybatis程序 在JDBC小结中(可以参阅本人JDBC系列文章),介绍到了ORM,其中Mybatis就是一个不错的ORM框架 MyBatis由iBatis演化而来 iBATIS一词来源于“i ...
- MyBatis(一):第一个MyBatis程序
本文是按照狂神说的教学视频学习的笔记,强力推荐,教学深入浅出1便就懂!b站搜索狂神说即可 https://space.bilibili.com/95256449?spm_id_from=333.788 ...
- Mybatis入门及第一个Mybatis程序
Mybatis笔记整理 所需要的基础知识 JDBC Mysql Java基础 Maven Junit 框架:是有配置文件的.最好的方式:看官网文档 1.简介 1.1.什么是MyBatis 简介 什么是 ...
- 创建一个简单MyBatis程序
文章目录 MyBatis基础 MyBatis 简介 创建一个MyBatis程序 1. 创建Java项目 2. 加载MyBatis包 3. 编写POJO类和映射文件 4.创建mybatis-config ...
- 第一个MyBatis程序(博客初写者)
第一个Mybatis程序 一.环境: 1.JDK1.8 2.MYSQL5.7 3.IDEA 4.MAVEN 3.63 二.Mybatis认识: 1.查看官方文档 https://mybatis.org ...
- MyBatis-02-第一个Mybatis程序
2.第一个Mybatis程序 思路:搭建环境-->导入Mybatis-->编写代码-->测试! 2.1.搭建环境 搭建数据库 CREATE DATABASE `mybatis`; u ...
随机推荐
- timesten报错:error while loading shared libraries: libaio.so.1: cannot open shared object file : No such file or directory
我遇到的这个错是因为缺少依赖:libaio 直接yum -y install libaio 然后重新安装就OK了
- java课程之团队开发冲刺阶段1.7
一.总结昨天进度 1.昨天学习了对数据库增删改查的基本操作,并且可以使用代码实现操作 二.遇到的问题 1.由于是学习阶段,没有遇到太大阻碍,但是最终需要实现的是联网进行数据库的读写或者是对本地数据库的 ...
- Httpclient代码
/// <summary> /// 显示 /// </summary> /// <returns></returns> public ActionRes ...
- Spring源码学习-容器BeanFactory(三) BeanDefinition的创建-解析Spring的默认标签
写在前面 上文Spring源码学习-容器BeanFactory(二) BeanDefinition的创建-解析前BeanDefinition的前置操作中Spring对XML解析后创建了对应的Docum ...
- java points[复习]
1 - & 与 && 的区别: &:不管左边是true还是false,右端都会进行运算: &&:当左端为false时,右端不再进行运算: 即在与运算时, ...
- koa2学习(二) 中间件router
中间件 koa-router 安装 npm install --save koa-router 使用 const Koa = require('koa'); const Router = requir ...
- Mesos源码分析(14): DockerContainerier运行一个Task
DockerContainerizer的实现在文件src/slave/containerizer/docker.cpp中 Future<bool> DockerContainerize ...
- vs2017开发Node.js控制台程序
1,新建项目 NodejsConsoleApp1 2,在项目的根目录下,添加 sayModule.js 文件 //sayModule.js function Say1Module() { this. ...
- 10倍速!一招儿解决因googleapis被墙导致的许多国外网站访问速度慢的问题
1x.com 是我非常喜欢的一家国外的摄影网站.但,打开它的首页要1分多钟!点击小图看大图的二级页面根本打不开.看着写着“Nude content”的小图却点不开大图的心情你们造吗?!很多国外网站访问 ...
- [Swift]LeetCode330. 按要求补齐数组 | Patching Array
Given a sorted positive integer array nums and an integer n, add/patch elements to the array such th ...