MyBatis学习总结(二)---实例
为了对MyBatis有个初步了解,现做一个简单的增、删、改、查实例。了解涉及的文件与相关作用。
MySql创建friends表,以下是表的sql语句
DROP TABLE IF EXISTS `friend`; CREATE TABLE `friend` (
`id` bigint(20) NOT NULL,
`friendName` varchar(50) NOT NULL,
`sex` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
创建一个MyBatisDemo工程
本人使用IDEA 2017创建该工程,也可以使用Eclipse创建。创建工程后,新增相关Package,导入相关的jar包。

目录说明:
com.yiming.demo,存放主类main,暂无写代码。
com.yiming.mapper,存放定义Mapper接口及映射文件,如:FriendMapper文件,friendMapper.xml文件。
com.yiming.pojo,存放实体类。
com.yiming.test,存放测试类,主要用于测试CRUD的方法。
com.yiming.untils,存放工具类,本工程只有:SqlSessionFactoryUntils
db.properties,为数据库属性文件。
mybatis-config.xml,为mybatis主要配置文件。
创建及配置db.properties,mybatis-config.xml二个文件
db.properties文件
database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/test
database.username=root
database.password=123456
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>
<!--数据库配置文件-->
<properties resource="db.properties"/>
<!--别名-->
<typeAliases>
<typeAlias alias="friend" type="com.yiming.pojo.Friend"/>
</typeAliases>
<!--数据库环境-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${database.driver}"/>
<property name="url" value="${database.url}"/>
<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}"/>
</dataSource>
</environment>
</environments>
<!--映射文件-->
<mappers>
<mapper resource="com/yiming/mapper/friendMapper.xml"/>
</mappers>
</configuration>
创建friend表的实体类
Friend实体类
package com.yiming.pojo;
public class Friend {
private long id;
private String friendName;
private String sex;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFriendName() {
return friendName;
}
public void setFriendName(String friendName) {
this.friendName = friendName;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
创建FriendMapper文件及friendMapper.xml文件
FriendMapper文件
package com.yiming.mapper;
import com.yiming.pojo.Friend;
import java.util.List;
public interface FriendMapper {
int inertFriend(Friend friend);
int updateFriend(Friend friend);
int deleteFriend(Friend friend);
Friend getFriend(long id);
List<Friend> getAllFrined(String friendName);
}
friendMapper.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="com.yiming.mapper.FriendMapper"> <insert id="inertFriend" parameterType="friend">
insert into friend(id,friendName, sex) values(#{id},#{friendName}, #{sex})
</insert> <delete id="deleteFriend" parameterType="long">
delete from friend where id= #{id}
</delete> <update id="updateFriend" parameterType="friend">
update friend set friendName = #{friendName}, sex = #{sex} where id= #{id}
</update> <select id="getFriend" parameterType="long" resultType="friend">
select id,friendName, sex from friend where id = #{id}
</select> <select id="getAllFrined" parameterType="string" resultType="friend">
select id, friendName, sex from friend
where friendName like concat('%', #{friendName}, '%')
</select>
</mapper>
创建SqlSessionFactoryUtils类
SqlSessionFactoryUtils类文件
package com.yiming.untils; import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException;
import java.io.InputStream; public class SqlSessionFactoryUtils {
private final static Class<SqlSessionFactoryUtils> LOCK = SqlSessionFactoryUtils.class; private static SqlSessionFactory sqlSessionFactory = null; private SqlSessionFactoryUtils() {
} public static SqlSessionFactory getSqlSessionFactory() {
synchronized (LOCK) {
if (sqlSessionFactory != null) {
return sqlSessionFactory;
}
String resource = "mybatis-config.xml";
InputStream inputStream;
try {
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
return null;
}
return sqlSessionFactory;
}
} public static SqlSession openSqlSession() {
if (sqlSessionFactory == null) {
getSqlSessionFactory();
}
return sqlSessionFactory.openSession();
}
}
创建FriendCRUD测试类
FriendCRUD
package com.yiming.test; import com.yiming.mapper.FriendMapper;
import com.yiming.pojo.Friend;
import com.yiming.untils.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test; import java.util.List; public class FriendCRUD {
SqlSession session =null;
//插入一对象测试
@Test
public void insertFriend( ){
session = SqlSessionFactoryUtils.openSqlSession();
Friend friend =new Friend();
friend.setId(1L);
friend.setFriendName("zhangsan");
friend.setSex("man");
try{
FriendMapper friendMapper = session.getMapper(FriendMapper.class);
friendMapper.inertFriend(friend);
session.commit();
}finally {
if(session !=null){
session.close();
}
}
}
@Test
public void updateFriend(){
session = SqlSessionFactoryUtils.openSqlSession();
Friend friend = new Friend();
friend.setId(1L);
friend.setFriendName("zhangsanfeng");
friend.setSex("man");
try{
FriendMapper friendMapper = session.getMapper(FriendMapper.class);
friendMapper.updateFriend(friend);
session.commit();
}finally {
if(session !=null){
session.close();
}
}
} @Test
public void getFriend(){
session = SqlSessionFactoryUtils.openSqlSession();
try{
FriendMapper friendMapper = session.getMapper(FriendMapper.class);
Friend friend = friendMapper.getFriend(1L);
System.out.print(friend.getFriendName());
}finally {
if(session !=null){
session.close();
}
}
}
@Test
public void getAllFriend(){
session = SqlSessionFactoryUtils.openSqlSession();
try{
FriendMapper friendMapper = session.getMapper(FriendMapper.class);
List<Friend> friendList = friendMapper.getAllFrined("zhangsanfeng");
for(Friend friend : friendList){
System.out.println(friend);
}
}finally {
if(session !=null){
session.close();
}
}
}
@Test
public void deleteFriend(){
session = SqlSessionFactoryUtils.openSqlSession();
try{
FriendMapper friendMapper = session.getMapper(FriendMapper.class);
friendMapper.deleteFriend(1L);
session.commit();
}finally {
if(session !=null){
session.close();
}
}
}
}
MyBatis学习总结(二)---实例的更多相关文章
- MyBatis学习 之 二、SQL语句映射文件(2)增删改查、参数、缓存
目录(?)[-] 二SQL语句映射文件2增删改查参数缓存 select insert updatedelete sql parameters 基本类型参数 Java实体类型参数 Map参数 多参数的实 ...
- MyBatis学习系列二——增删改查
目录 MyBatis学习系列一之环境搭建 MyBatis学习系列二——增删改查 MyBatis学习系列三——结合Spring 数据库的经典操作:增删改查. 在这一章我们主要说明一下简单的查询和增删改, ...
- MyBatis学习 之 二、SQL语句映射文件(1)resultMap
目录(?)[-] 二SQL语句映射文件1resultMap resultMap idresult constructor association联合 使用select实现联合 使用resultMap实 ...
- 【转】MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作
[转]MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作 上一篇博文MyBatis学习总结(一)——MyBatis快速入门中我们讲了如何使用Mybatis查询users表中的数据, ...
- MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作(转载)
本文转载自:http://www.cnblogs.com/jpf-java/p/6013540.html 上一篇博文MyBatis学习总结(一)--MyBatis快速入门中我们讲了如何使用Mybati ...
- MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作
上一篇博文MyBatis学习总结(一)——MyBatis快速入门中我们讲了如何使用Mybatis查询users表中的数据,算是对MyBatis有一个初步的入门了,今天讲解一下如何使用MyBatis对u ...
- Mybatis学习笔记二
本篇内容,紧接上一篇内容Mybatis学习笔记一 输入映射和输出映射 传递简单类型和pojo类型上篇已介绍过,下面介绍一下包装类型. 传递pojo包装对象 开发中通过可以使用pojo传递查询条件.查询 ...
- MyBatis学习笔记(二)——使用MyBatis对表执行CRUD操作
转自孤傲苍狼的博客:http://www.cnblogs.com/xdp-gacl/p/4262895.html 上一篇博文MyBatis学习总结(一)——MyBatis快速入门中我们讲了如何使用My ...
- 二:MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作
上一篇博文MyBatis学习总结(一)——MyBatis快速入门中我们讲了如何使用Mybatis查询users表中的数据,算是对MyBatis有一个初步的入门了,今天讲解一下如何使用MyBatis对u ...
- mybatis学习笔记(二)-- 使用mybatisUtil工具类体验基于xml和注解实现
项目结构 基础入门可参考:mybatis学习笔记(一)-- 简单入门(附测试Demo详细过程) 开始体验 1.新建项目,新建类MybatisUtil.java,路径:src/util/Mybatis ...
随机推荐
- 构建基于虚拟用户的vsftpd服务器
安装: [root@server ~]# yum install -y vsftpd [root@server ~]# rpm -ql vsftpd /etc/logrotate.d/vsftpd / ...
- SHOI2001化工厂装箱员——记忆化搜索
题目:https://www.luogu.org/problemnew/show/P2530 太弱了不会用DP,于是暴搜: 每次传进一个数组c记录当前状态各种物品有多少个,枚举取哪种物品,返回最小值, ...
- PowerShell自动部署网站—(1)、安装IIS[添加角色和角色服务]
#------添加角色/角色服务------ Import-Module servermanager $features = get-windowsfeature Net-*,Telnet-*,Web ...
- zk 09之:Curator之二:Path Cache监控zookeeper的node和path的状态
在实际应用开发中,当某个ZNode发生变化后我们需要得到通知并做一些后续处理,Curator Recipes提供了Path Cache 来帮助我们轻松实现watch ZNode. Path Cache ...
- win7 64位搭建Mantis 缺陷管理系统(2)
建立Bug数据库 1. 右键Windows托盘的图标,选择“Local Web”,(或者在IE地址中输入“http://127.0.0.1/”)可看到如下页面: 2. 点击选择“mantis”,进入页 ...
- 《Java多线程编程核心技术》读后感(十八)
线程中出现异常的处理 package Seven; public class MyThread extends Thread { @Override public void run() { Strin ...
- Beetl使用注意事项
1.如果表达式跟定界符或者占位符有冲突,可以在用 “\” 符号 @for(user in users){ email is ${user.name}\@163.com @} ${[1,2,3]} // ...
- 一些unity资源
雨凇解包 http://www.xuanyusong.com/archives/3618 http://www.cnblogs.com/lixiang-share/p/5840444.html u3d ...
- linux mysql 简单记录
mysql 1.linux下启动mysql的命令:mysqladmin start/ect/init.d/mysql start (前面为mysql的安装路径) 2.linux下重启mysql的命令: ...
- 洛谷P2759 奇怪的函数
P2759 奇怪的函数 题目描述 使得 x^x 达到或超过 n 位数字的最小正整数 x 是多少? 输入输出格式 输入格式: 一个正整数 n 输出格式: 使得 x^x 达到 n 位数字的最小正整数 x ...