首页 > 代码库 > 初始mybatis

初始mybatis

1.
   MyBatis 本是的apache一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,
   并且改名为MyBatis 。
   iBATIS一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps
   和Data Access Objects(DAO)
2.
    ① 首先你需要的工具是eclipse和安装了mysql服务器的机器
    ② 需要jar包,包括mybatis-3.2.6.jarmysql-connector-java-5.1.7-bin.jar
  ③ 由于进行的简单的测试,因此只需这两jar就够了。
    ④ 由于是持久化层,所以建一个 java project 即可
3.
1)数据库文件(数据库名为mc,表名为user)
CREATE TABLE user (
`userId`  bigint(20) NOT NULL AUTO_INCREMENT ,
`userName`  varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
`password`  varchar(80) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
`comment`  varchar(250) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,
PRIMARY KEY (`userId`),
UNIQUE INDEX `UQ_User_userName` (`userName`) USING BTREE
)
View Code

采用如下的命令查看表的结构

2)创建一个实体类

 1 package com.baba.miao.test;
 2 
 3 public class User {
 4     private int userId;
 5     private String userName;
 6     private String password;
 7     private String comment;
 8 
 9     public int getUserId() {
10         return userId;
11     }
12 
13     public void setUserId(int userId) {
14         this.userId = userId;
15     }
16 
17     public String getUserName() {
18         return userName;
19     }
20 
21     public void setUserName(String userName) {
22         this.userName = userName;
23     }
24 
25     public String getPassword() {
26         return password;
27     }
28 
29     public void setPassword(String password) {
30         this.password = password;
31     }
32 
33     public String getComment() {
34         return comment;
35     }
36 
37     public void setComment(String comment) {
38         this.comment = comment;
39     }
40 
41     public User(int userId, String userName, String password, String comment) {
42         super();
43         this.userId = userId;
44         this.userName = userName;
45         this.password = password;
46         this.comment = comment;
47     }
48 
49     public User() {
50 
51     }
52 
53     public String toString() {
54         return "User [userId=" + userId + ", userName=" + userName
55                 + ", password=" + password + ", comment=" + comment + "]";
56     }
57 
58 }
View Code

3)创建DAO层

 1 package com.baba.miao.test;
 2 
 3 import java.util.List;
 4 
 5 public interface UserDao {
 6 
 7     public int insert(User user);
 8 
 9     public int update(User user);
10 
11     public int delete(String userName);
12 
13     public List<User> selectAll();
14 
15     public int countAll();
16 
17     public User findByUserName(String userName);
18 }
View Code

4)创建实体类的映射文件

<?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.baba.miao.test.UserDao">
    <select id="countAll" resultType="int">
        select count(*) c from user;
    </select>
    
    <select id="selectAll" resultType="com.baba.miao.test.User">
        select * from user order by userName asc
    </select>
    
    <insert id="insert" parameterType="com.baba.miao.test.User">
        insert into user(userName,password,comment) values(#{userName},#{password},#{comment})
    </insert>
    
    <update id="update" parameterType="com.baba.miao.test.User">
        update user set userName=#{userName},password=#{password},comment=#{comment} where userName=#{userName}
    </update>
    
    <delete id="delete" parameterType="int">
        delete from user where userName=#{userName}
    </delete>
    
    <select id="findByUserName" parameterType="String" resultType="com.baba.miao.test.User">
        select * from user where userName=#{userName}
    </select>
</mapper>
View Code

5)创建mybatis-config配置文件

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 3 "http://mybatis.org/dtd/mybatis-3-config.dtd">
 4 <configuration>
 5     <properties resource="jdbc.properties" />
 6     <typeAliases>
 7         <package name="com.baba.miao.test"/>
 8     </typeAliases>
 9     <environments default="development">
10         <environment id="development">
11             <transactionManager type="JDBC" />
12             <dataSource type="POOLED">
13                 <property name="driver" value="${driver}" />
14                 <property name="url" value="${url}" />
15                 <property name="username" value="${username}" />
16                 <property name="password" value="${password}" />
17             </dataSource>
18         </environment>
19     </environments>
20     <mappers>
21         <mapper resource="com/baba/miao/test/UserDaoMapper.xml" />
22     </mappers>
23 </configuration>
View Code

6) 创建jdbc.properties连接数据库文件

1 username=root
2 password=mmmm
3 url=jdbc:mysql://localhost:3306/mc
4 driver=com.mysql.jdbc.Driver
View Code

7)编辑单元测试文件UserDaoTest

 1 package com.baba.miao.test;
 2 
 3 import java.io.IOException;
 4 import java.io.Reader;
 5 import java.util.Iterator;
 6 import java.util.List;
 7 
 8 import org.apache.ibatis.io.Resources;
 9 import org.apache.ibatis.session.SqlSession;
10 import org.apache.ibatis.session.SqlSessionFactory;
11 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
12 import org.junit.Test;
13 
14 public class UserDaoTest {
15     @Test
16     public void userDaoTest() throws IOException {
17         String resource = "mybatis-config.xml";
18         Reader reader = Resources.getResourceAsReader(resource);
19         SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
20         SqlSessionFactory factory = builder.build(reader);
21 
22         SqlSession session = factory.openSession();
23         UserDao userDao = session.getMapper(UserDao.class);
24 
25         User user = new User();
26         user.setUserId(1);
27         user.setUserName("miaochuang");
28         user.setPassword("123456");
29         user.setComment("我爱你");
30 
31         userDao.insert(user);
32         System.out.println("记录条数:" + userDao.countAll());
33 
34         List<User> users = userDao.selectAll();
35         Iterator<User> iter = users.iterator();
36         while (iter.hasNext()) {
37             User u = iter.next();
38             System.out.println("用户名:" + u.getUserName() + "密码:"
39                     + u.getPassword());
40         }
41         session.commit();
42         session.close();
43     }
44 }
View Code

 

参考目录结构:

 

                        技术总结:

                        mybatis持久化技术

                        EL表达式

                        单元测试