2019独角兽企业重金招聘Python工程师标准>>>
1. MyBatis是什么?
MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。
iBATIS一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAO)
2. MyBatis quick start
2.1 如何获取MyBatis的支持
如果你还在用传统的方式开发程序那么你需要到mybatis官网上下载对应的jar包,对应官方网址为:http://blog.mybatis.org/
如果你是在使用maven管理你得项目,那么恭喜你,下面我们的例子就是使用maven构建项目。
在你的项目的pom.xml中添加dependency:
junit
junit
4.7
test
org.mybatis
mybatis
3.2.6
mysql
mysql-connector-java
5.1.30
log4j
log4j
1.2.17
2.2 MyBatis的simple CURD
首先我们需要建立一个数据库,创建测试表:
drop database bbs;
create database bbs character set utf8;
use bbs;
/*alter database bbs character set utf8;*/s
/*
Posts 发的帖子信息
Post_id 帖子的id int
Post_Title 帖子的标题 nvarchar
Post_BiBoid 帖子所属父版块id int
Post_SmBoid 帖子所属子版块id int
Post_admin 发帖者姓名 nvarchar
Post_createtime 发帖时间 datetime
Post_updatetime 更新时间 datetime
Post_content 帖子内容 nvarchar
Post_goodcount 帖子的好评数 int
Post_badcount 帖子的坏评数 int
Post_reward 帖子的总共悬赏分(吸引浏览) int
Post_score 帖子悬赏分所剩下的分数 int
Post_ispay 是否结贴 bit
Post_islocked 是否帖子被锁定 bit
*/
drop table posts;
create table posts(
id int primary key auto_increment,
title varchar(100),
biboid int,
smboid int,
admin varchar(50),
createtime datetime,
updatetime datetime,
context text,
goodcount int,
badcount int,
reward int,
score int,
ispay bit,
islocked bit
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
新建一个MyBatis的主配置文件:mybatis-config.xml
新建一个model类:Posts
package com.mscncn.batis.model;
import java.sql.Date;
/**
* 发的帖子信息
* @author king-pan
* @version 1.0
*
*/
public class Posts {
private int id;
private String title;
private int biboid;
private int smboid;
private Date createTime;
private Date updateTime;
private String context;
private int goodCount;
private int badCount;
private int reward;
private int score;
private boolean isPay;
private boolean isLocked;//自己提供getter,setter方法
public Posts(){}
public Posts(String title,String context){
this.title=title;
this.context=context;
}
public Posts(int id,String title,String context){
this.id=id;
this.title=title;
this.context=context;
}
}
新建一个PostMapper.java 定义对Posts表操作的接口:
package com.mscncn.batis.mapper;
import java.util.List;
import java.util.Map;
import com.mscncn.batis.model.Pager;
import com.mscncn.batis.model.Posts;
public interface PostsMapper{
public void addPosts(Posts posts);
public Posts getPostsById(int id);
public Posts getPostsByTitle(String title);
public void updatePosts(Posts posts);
public void deletePosts(int id);
public void batchUpdate(List list);
public List getList();
public List getListByPage(Pager pager);
public Posts getByParams(Posts posts);
public Posts getByChoose(Posts post);
public Posts trimTest(Posts posts);
public void update(Posts post);
public void updateArray(int[]ary);
public Posts getByMap(Map map);
}
SQL映射:
insert into posts(title,context) values(#{title},#{context})
update posts set context=#{context} where id=#{id}
update posts set badcount=3,goodcount=5 where id in
#{item.id}
MyBatisUtil代码如下:
package com.mscncn.batis.util;
import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisUtil {
private final static SqlSessionFactory sqlSessionFactory;
static {
String resource = "mybatis-config.xml";
Reader reader = null;
try {
reader = Resources.getResourceAsReader(resource);
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
}
public static SqlSessionFactory getSqlSessionFactory() {
return sqlSessionFactory;
}
}
测试代码如下:
package com.mscncn.batis;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;
import com.mscncn.batis.mapper.PostsMapper;
import com.mscncn.batis.model.Posts;
import com.mscncn.batis.util.MyBatisUtil;
public class PostsMapperTest {
static SqlSessionFactory sqlSessionFactory = null;
static {
sqlSessionFactory = MyBatisUtil.getSqlSessionFactory();
}
@Test
public void testAdd() {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
PostsMapper mapper = sqlSession.getMapper(PostsMapper.class);
Posts posts=new Posts("Spring test", "这是一个mybatis测试");
mapper.addPosts(posts);
sqlSession.commit();//这里一定要提交,不然数据进不去数据库中
} finally {
sqlSession.close();
}
}
@Test
public void getUser() {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
PostsMapper mapper = sqlSession.getMapper(PostsMapper.class);
Posts posts=mapper.getPostsById(1);
System.out.println(posts.getContext());
} finally {
sqlSession.close();
}
}
@Test
public void getUserByTitle() {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
PostsMapper mapper = sqlSession.getMapper(PostsMapper.class);
Posts posts=mapper.getPostsByTitle("Spring test");
System.out.println(posts.getContext());
} catch(Exception e){
e.printStackTrace();
}
finally {
sqlSession.close();
}
}
@Test
public void getListTest() {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
PostsMapper mapper = sqlSession.getMapper(PostsMapper.class);
List posts=mapper.getList();
System.out.println(posts.size());
System.out.println(posts.get(0).getId());
System.out.println(posts.get(1).getContext());
} catch(Exception e){
e.printStackTrace();
}
finally {
sqlSession.close();
}
}
@Test
public void updatePostsTest() {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
PostsMapper mapper = sqlSession.getMapper(PostsMapper.class);
Posts posts=new Posts(1, "22", "mybatis 跟新数据库操作");
mapper.updatePosts(posts);
sqlSession.commit();
} catch(Exception e){
e.printStackTrace();
}
finally {
sqlSession.close();
}
}
@Test
public void deletePostsTest() {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
PostsMapper mapper = sqlSession.getMapper(PostsMapper.class);
mapper.deletePosts(3);
sqlSession.commit();
} catch(Exception e){
e.printStackTrace();
}
finally {
sqlSession.close();
}
}
@Test
public void batchTest(){
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
PostsMapper mapper = sqlSession.getMapper(PostsMapper.class);
List list=mapper.getList();
int index=0;
for(Posts ps:list){
ps.setBadCount(++index);
ps.setGoodCount(index);
}
mapper.batchUpdate(list);
sqlSession.commit();
} catch(Exception e){
e.printStackTrace();
}
finally {
sqlSession.close();
}
}
}
注意: 在maven中测试时,一定要记得把相应的配置文件拷贝到src/test/resources目录下,不然在使用MyBatis框架时一直抱错,错误信息如下:
MyBatis could not find resource …..