一、Mybatis優缺點html
優勢: Mybatis實現了對Dao層的封裝,隔離了SQL語句,便於管理,避免了像JDBC那樣操做數據集,便於擴展等等。java
缺點: Mybatis屬於?半自動「ORM」,比Hibernate的工做作得要多不少,對象參數傳遞比較麻煩,沒有Hibernate對象操做的概念。mysql
二、Mybatis的實現方式web
Mybatis提供兩種應用實現:XML配置和註解。sql
2.1配置主要依賴實體對象的xml文件,將對象以<resultMap>形式注入,並提供給<insert > <delete > <select> <update> 語句引用。數據庫
2.2使用註解來的比配置XML文件要簡單得多。只須要在接口上添加相應的註解並附上SQL語句就好了,如:apache
插入語句:@insert(" insert into table_user ..")瀏覽器
修改語句: @update(" update table_user set ....")服務器
刪除語句:@delete(" delete from table_user .....")session
查詢語句:@select(" select * from table_user .....")
三、下載mybatis的jar包:mybatis-3.1.1-bundle.zip?,網址:http://code.google.com/p/mybatis/
Maven的pom.xml依賴配置以下:
- <dependency>
- <groupId>org.mybatis</groupId>
- <artifactId>mybatis</artifactId>
- <version>3.1.1</version>
- </dependency>
依賴倉庫配置:
- <repository>
- <id>mybatis-snapshot</id>
- <name>MyBatis Snapshot Repository</name>
- <url>https://oss.sonatype.org/content/repositories/snapshots</url>
- </repository>
四、構建本身的mybatis項目,如圖所示:
展開文件展現:
五、mybatis-config.xml:配置數據源和隱射文件
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE configuration PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-config.dtd">
- <configuration>
- <environments default="environment">
- <environment id="environment">
- <transactionManager type="JDBC" />
- <dataSource type="POOLED">
- <property name="driver" value="com.mysql.jdbc.Driver" />
- <property name="url"
- value="jdbc:mysql://localhost:3306/mybatis?characterEncoding =UTF-8" />
- <property name="username" value="root" />
- <property name="password" value="root" />
- </dataSource>
- </environment>
- </environments>
-
- </configuration>
注:<!-- <mappers> <mapper resource="mybatis/User.xml"/> </mappers> -->是使用實體配置的實現,若是使用註解則不須要添加。
六、使用註解實現CRUD操做-此處以實現用戶管理爲例
6.1編寫接口(interface):實際上就是官方文檔所述的Mapper
- public interface UserService {
- @Insert(" insert into users (id,username,password) values (#{id},#{username},#{password})")
- void add(@Param("id")String id,@Param("username") String username,@Param("password")String password);
-
- @Delete(" delete from users where id=#{id}")
- void delete(String id);
-
- @Update(" update users set username=#{username},password=#{password} where id=#{id}")
- int update(@Param("username") String username,@Param("password")String password,@Param("id")String id);
-
- @Select(" select * from users where id=#{id}")
- User getUser(String id);
-
- @Select(" select * from users order by id asc ")
- List<User> getUsers();
-
- @Select(" select * from users order by id asc limit #{pageSize} offset #{offset} ")
- List<User> getUsersByPage(@Param("offset")int offset,@Param("pageSize") int pageSize);
- }
注:使用註解時接口的方法不能重載,否者會產生Mapped Statements collection does not contain value for 異常,另外還應儘可能避免配置和註解混合使用的狀況。
6.2獲取數據源
- public class GetSqlSessionFactory
- {
- private static SqlSessionFactory sqlSessionFactory = null;
-
- private static GetSqlSessionFactory getSqlSessionFactory = null;
-
- private GetSqlSessionFactory()
- {
- String rs = "mybatis-config.xml";
- Reader reader = null;
- try
- {
- reader = Resources.getResourceAsReader(rs);
- } catch (IOException e)
- {
- e.printStackTrace();
- }
- sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
-
- sqlSessionFactory.getConfiguration().addMapper(UserService.class);
- }
-
- public static GetSqlSessionFactory getInstance()
- {
- if (getSqlSessionFactory == null)
- getSqlSessionFactory = new GetSqlSessionFactory();
- return getSqlSessionFactory;
- }
-
- public static SqlSessionFactory getSqlSessionFactory()
- {
- return sqlSessionFactory;
- }
-
- }
6.3DAO層:數據訪問
- public class UserDao
- {
- @SuppressWarnings("static-access")
- public void add(String id, String username, String password)
- {
- SqlSession session = GetSqlSessionFactory.getInstance().getSqlSessionFactory().openSession();
- try
- {
- session.getMapper(UserService.class).add(id, username, password);
- session.commit();
- } catch (Exception e)
- {
- e.printStackTrace();
- } finally
- {
- session.close();
- }
- }
-
- @SuppressWarnings("static-access")
- public void delete(String id)
- {
- SqlSession session = GetSqlSessionFactory.getInstance().getSqlSessionFactory().openSession();
- try
- {
- session.getMapper(UserService.class).delete(id);
- session.commit();
- } catch (Exception e)
- {
- e.printStackTrace();
- } finally
- {
- session.close();
- }
- }
-
- @SuppressWarnings("static-access")
- public int update(String username, String password, String id)
- {
- int count = 0;
- SqlSession session = GetSqlSessionFactory.getInstance().getSqlSessionFactory().openSession();
- try
- {
-
-
-
-
- count = session.getMapper(UserService.class).update(username, password, id);
- session.commit();
- } catch (Exception e)
- {
- count = 0;
- e.printStackTrace();
- } finally
- {
- session.close();
- }
- return count;
- }
-
- @SuppressWarnings("static-access")
- public List<User> getUsers(int offset, int pageSize)
- {
- List<User> users = new ArrayList<User>();
- SqlSession session = GetSqlSessionFactory.getInstance().getSqlSessionFactory().openSession();
- try
- {
-
-
-
- users = session.getMapper(UserService.class).getUsersByPage(offset, pageSize);
- } catch (Exception e)
- {
- e.printStackTrace();
- } finally
- {
- session.close();
- }
- return users;
- }
- }
6.4servlet實現數據跳轉訪問
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
- {
- response.setContentType("text/html;charset=utf-8");
- UserService userService = new UserServiceImpl();
- PrintWriter out = response.getWriter();
- String method = request.getParameter("method");
- String returnString = "";
-
- if (method.equals("users"))
- {
- returnString = new JsonUtil<User>().getJsonByListObj(userService.getUsers());
- } else if (method.equals("user"))
- {
- String id = request.getParameter("id");
- returnString = new JsonUtil<User>().getJsonByEntity(userService.getUser(id));
- } else if (method.equals("delete"))
- {
- String id = request.getParameter("id");
- Map<String, Object> map = new HashMap<String, Object>();
- map.put("event", method);
- map.put("param", id);
- returnString = new JsonUtil<User>().getJsonByObject(map);
- } else if (method.equals("update"))
- {
- String id = request.getParameter("id");
- String username = request.getParameter("username");
- String password = request.getParameter("password");
- Map<String, Object> map = new HashMap<String, Object>();
- int count = userService.update(username, password, id);
- map.put("status", count == 0 ? false : true);
- map.put("event", method);
- map.put("param", id);
- returnString = new JsonUtil<User>().getJsonByObject(map);
- } else if (method.equals("paginate"))
- {
- int limit = Integer.valueOf(request.getParameter("pageSize"));
- int offset = Integer.valueOf(request.getParameter("offset"));
- returnString = new JsonUtil<User>().getJsonByListObj(userService.getUsersByPage(offset, limit));
- }
-
- out.print(returnString);
- out.flush();
- out.close();
- }
至此,註解方式的實現就所有完成了。
七、User.xml實體對象配置
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
- <mapper namespace="com.boonya.mybatis.entity.User">
- <resultMap id="UserResultMap" type="com.boonya.mybatis.entity.User">
- <result property="id" column="id" jdbcType="VARCHAR" javaType="string" />
- <result property="name" column="name" javaType="string"
- jdbcType="VARCHAR" />
- <result property="createtime" column="createtime" javaType="string"
- jdbcType="VARCHAR" />
- <result property="tilepath" column="tilepath" javaType="string"
- jdbcType="VARCHAR" />
- <result property="lastlogintime" column="lastlogintime"
- javaType="string" jdbcType="VARCHAR" />
- <result property="nickname" column="nickname" javaType="string"
- jdbcType="VARCHAR" />
- <result property="password" column="password" javaType="string"
- jdbcType="VARCHAR" />
- <result property="picture" column="picture" javaType="string"
- jdbcType="VARCHAR" />
- <result property="sex" column="sex" javaType="string" jdbcType="VARCHAR" />
- <result property="username" column="username" javaType="string"
- jdbcType="VARCHAR" />
- </resultMap>
- <span style="color:#ff0000">
- <select id="user" parameterType="int" resultType="com.boonya.mybatis.entity.User"
- resultMap="UserResultMap">select * from users where id=#{id} </select>
- <select id="users" resultMap="UserResultMap">select * from users order by id asc
- </select>
- <insert id="addUser" parameterType="com.boonya.mybatis.entity.User"
- parameterMap="UserResultMap">insert into users
- (id,name,createtime,email,tilepath,lastloginip,lastlogintime,nickname,password,picture,sessionid,sex,tel,username)
- values
- (#{id},#{name},#{createtime},#{email},#{tilepath},#{lastloginip},#{lastlogintime},#{nickname},#{password},#{picture},#{sessionid},#{sex},#{tel},#{username})
- </insert>
- <span style="color:#ff0000">
-
- <select id="dynamic_user" resultMap="UserResultMap">
- select * from users where username=#{username}
- <if test="name!=null">and name=#{name}</if>
- </select>
- <span style="color:#ff0000">
- <select id="dynamic_users" resultMap="UserResultMap">
- select * from users name=#{name} and createtime in
- <foreach collection="list" item="classTimeList" open="("
- separator="," close=")"> #{classTimeList} </foreach>
- </select>
- <span style="color:#ff0000">
- <select id="dynamic_findNameLike" resultMap="UserResultMap">
- SELECT * FROM USERS WHERE NAME IS NOT NULL
- <choose>
- <when test="nickname!=null">AND nickname like #{nickname}</when>
- <when test="picture!=null ">AND picture like #{picture}</when>
- <otherwise>AND lastlogintime > #{lastlogintime}</otherwise>
- </choose>
- </select>
- <span style="color:#ff0000">
- <select id="dynamic_findUSERSLike" resultMap="UserResultMap">
- select * from users
- <where>
- <if test="name!=null">WHERE name LIKE #{name}</if>
- </where>
- </select>
- </mapper>
注:若是使用配置需將mybatis-config.xml文件的mapper去掉註釋:
<!-- <mappers>
<mapper resource="mybatis/User.xml"/>
</mappers> -->
而且註釋掉使用註解的mapper隱射:
//註解方式查詢時須要註冊mapper
sqlSessionFactory.getConfiguration().addMapper(UserService.class);
配置方式是根據SQL語句的隱射去訪問的 如UserDao 中的getUsers方法:
//xml方式查詢
//users=session.selectList("users");
八、測試數據是否可以正常訪問
8-一、數據庫mybatis建立users表並添加數據
- /*
- Navicat MySQL Data Transfer
-
- Source Server : localhost
- Source Server Version : 50513
- Source Host : localhost:3306
- Source Database : mybatis
-
- Target Server Type : MYSQL
- Target Server Version : 50513
- File Encoding : 65001
-
- Date: 2012-12-17 18:25:15
- */
-
- SET FOREIGN_KEY_CHECKS=0;
-
- DROP TABLE IF EXISTS `users`;
- CREATE TABLE `users` (
- `id` varchar(50) NOT NULL,
- `username` varchar(30) DEFAULT NULL,
- `password` varchar(20) DEFAULT NULL,
- `name` varchar(30) DEFAULT NULL,
- `nickname` varchar(30) DEFAULT NULL,
- `sex` varchar(10) DEFAULT NULL,
- `picture` varchar(255) DEFAULT NULL,
- `createtime` varchar(20) DEFAULT NULL,
- `lastlogintime` varchar(50) DEFAULT NULL,
- `tilepath` varchar(255) DEFAULT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-
- INSERT INTO `users` VALUES ('HUSDHSHFSD_00001', 'BOONYA', '123456', 'BOONYA_U', 'BOONYA_*', '男', 'images/inde.png', '2012-12-17 15:30:23', '1832928398932', 'this/home/index.tile');
- INSERT INTO `users` VALUES ('HUSDHSHFSD_000010', 'BOONYA', '123456', 'BOONYA_U', 'BOONYA_*', '男', 'images/inde.png', '2012-12-17 15:30:23', '1832928398932', 'this/home/index.tile');
- INSERT INTO `users` VALUES ('HUSDHSHFSD_00002', 'BOONYA', '123456', 'BOONYA_U', 'BOONYA_*', '女', 'images/inde.png', '2012-12-17 15:30:23', '1832928398932', 'this/home/index.tile');
- INSERT INTO `users` VALUES ('HUSDHSHFSD_00003', 'BOONYA', '123456', 'BOONYA_U', 'BOONYA_*', '男', 'images/inde.png', '2012-12-17 15:30:23', '1832928398932', 'this/home/index.tile');
- INSERT INTO `users` VALUES ('HUSDHSHFSD_00004', 'BOONYA', '123456', 'BOONYA_U', 'BOONYA_*', '男', 'images/inde.png', '2012-12-17 15:30:23', '1832928398932', 'this/home/index.tile');
- INSERT INTO `users` VALUES ('HUSDHSHFSD_00005', 'BOONYA', '123456', 'BOONYA_U', 'BOONYA_*', '女', 'images/inde.png', '2012-12-17 15:30:23', '1832928398932', 'this/home/index.tile');
- INSERT INTO `users` VALUES ('HUSDHSHFSD_00006', 'BOONYA', '123456', 'BOONYA_U', 'BOONYA_*', '男', 'images/inde.png', '2012-12-17 15:30:23', '1832928398932', 'this/home/index.tile');
- INSERT INTO `users` VALUES ('HUSDHSHFSD_00007', 'BOONYA', '123456', 'BOONYA_U', 'BOONYA_*', '男', 'images/inde.png', '2012-12-17 15:30:23', '1832928398932', 'this/home/index.tile');
- INSERT INTO `users` VALUES ('HUSDHSHFSD_00008', 'BOONYA', '123456', 'BOONYA_U', 'BOONYA_*', '男', 'images/inde.png', '2012-12-17 15:30:23', '1832928398932', 'this/home/index.tile');
- INSERT INTO `users` VALUES ('HUSDHSHFSD_00009', 'BOONYA', '123456', 'BOONYA_U', 'BOONYA_*', '女', 'images/inde.png', '2012-12-17 15:30:23', '1832928398932', 'this/home/index.tile');
8-二、修改web.xml的servlet的配置
- <!DOCTYPE web-app PUBLIC
- "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
- "http://java.sun.com/dtd/web-app_2_3.dtd" >
-
- <web-app>
- <display-name>Archetype Created Web Application</display-name>
- <servlet>
- <servlet-name>DefaultUserListHandler</servlet-name>
- <display-name>DefaultUserListHandler</display-name>
- <description></description>
- <servlet-class>com.boonya.mybatis.servlet.DefaultUserListHandler</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>DefaultUserListHandler</servlet-name>
- <url-pattern>/userservice</url-pattern>
- </servlet-mapping>
-
- <welcome-file-list>
- <welcome-file>index.html</welcome-file>
- </welcome-file-list>
-
- </web-app>
將mybatis項目部署到Tomcat服務器中,啓動服務器,在瀏覽器輸入:http://localhost:8080/mybatis/userservice?method=users會看到以下圖所示的結果: