转载

mybatis入门教程(一)

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:  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.7</version>
      <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.2.6</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.30</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
2.2 MyBatis的simple CURD 首先我们需要建立一个数据库,创建测试表:  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?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
    <settings
        <!-- changes from the defaults for testing -->
        <setting name="cacheEnabled" value="false" /> 
        <setting name="useGeneratedKeys" value="true" /> 
        <setting name="defaultExecutorType" value="REUSE" /> 
    </settings
    <typeAliases
           <!-- 实体类的别名 -->
       <typeAlias alias="Posts" type="com.mscncn.batis.model.Posts"/> 
    </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://127.0.0.1:3306/bbs"/> 
              <property name="username" value="pwpw1218"/> 
              <property name="password" value="pwpw1218"/> 
           </dataSource
       </environment
    </environments
    <mappers
        <mapper resource="com/mscncn/batis/mapper/config/PostsMapper.xml" /> 
    </mappers
</configuration>
新建一个model类:Posts  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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表操作的接口:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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<Posts> list);
    public List<Posts> getList();
    public List<Posts> 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<String,Object> map);
}
  SQL映射:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?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.mscncn.batis.mapper.PostsMapper"
<!-- 这里namespace必须是PostsMapper接口的路径,不然要运行的时候要报错 “is not known to the MapperRegistry”-->
    <insert id="addPosts" parameterType="Posts"
       insert into posts(title,context) values(#{title},#{context}) 
       <!-- 这里sql结尾不能加分号,否则报“ORA-00911”的错误 -->
    </insert
 
    <!-- 这里的id必须和PostsMapper接口中的接口方法名相同,不然运行的时候也要报错 -->
    <select id="getPostsById" resultType="Posts" parameterType="int"
        select * from posts where id=#{id} 
    </select
   <select id="getPostsByTitle" resultType="Posts" parameterType="java.lang.String"
        select * from posts where title like #{title} 
   </select
   <!-- 如果方法没有参数,那么就不需要parameterType -->
   <select id="getList" resultMap="postList">
         select * from posts
   </select>
   <update id="updatePosts" parameterType="Posts">
         update posts set context=#{context} where id=#{id}
   </update>
   <delete id="deletePosts" parameterType="int">
         <![CDATA[
             delete from posts where id=#{id}
         ]]>
   </delete>
   <update id="batchUpdate" parameterType="java.util.List">
         update posts set  badcount=3,goodcount=5 where id in
         <foreach collection="list" item="item" open="(" close=")" index="index" separator=",">
                 #{item.id}
         </foreach>
   </update>
   <resultMap type="Posts" id="postList">
         <id column="id" property="id"/>
         <result column="title" property="title" />
         <result column="context" property="context" />
         
   </resultMap>
</mapper>
MyBatisUtil代码如下:  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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; 
    
}
测试代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
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> 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<Posts> 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 …..
正文到此结束
Loading...