zoukankan      html  css  js  c++  java
  • mybatis实例讲解

    1  建一个web工程或java工程,如果要整合spring,则建一个web工程,加入mybatis-3.1.1.jar
     
    2  在src中创建一个xml文件,可以放在src目录中,也可以放在一个包中,这里放在一个包com.ibatistest.maps中,xml文件名为configuration.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">
     
    <!-- 全局配置文件,要引入命名空间,此文件就相当于hibernate的hibernate-cfg.xml, -->
    <configuration>
     
       <!--
          连接数据库的配置, 注意这里的键: 默认的环境 ID(比如:default=”development”)。 每个
          environment元素定义的环境 ID(比如:id=”development”)。 事务管理器的配置(比如:type=”JDBC”)。
          数据源的配置(比如:type=”POOLED”)
          可以配多个environment,由default来指定用哪一个连接(environment),
       -->
       <environments default="development">
      
          <environment id="development">
     
             <!--
                事务配置,具体的事务管理器, 在 MyBatis 中有两种事务管理器类型(也就是 type=”[JDBC | MANAGED]”):
     
                JDBC – 这个配置直接简单使用了 JDBC 的提交和回滚设置。 它依赖于从数据源得 到的连接来管理事务范围。
                 MANAGED
                –这个配置几乎没做什么。它从来不提交或回滚一个连接。而它会让 容器来管理事务的整个生命周期(比如 Spring 或 JEE
                应用服务器的上下文) 默认 情况下它会关闭连接。 然而一些容器并不希望这样, 因此如果你需要从连接中停止 它,将
                closeConnection 属性设置为 false。
                这两种事务管理器都不需要任何属性。然而它们都是类型别名,要替换使用它们, 你需
                要放置将你自己的类的完全限定名或类型别名,它们引用了你对 TransactionFactory 接口的实现 类。
             -->
             <transactionManager type="JDBC"></transactionManager>
     
             <!-- 连接数据库的具体属性 -->
             <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url"
                    value="jdbc:mysql://127.0.0.1:3306/crm_test?characterEncoding=utf-8" />
                <property name="username" value="root" />
                <property name="password" value="root" />
             </dataSource>
     
          </environment>
     
       </environments>
       <!-- 连接数据库的配置 -->
     
       <mappers>
          <mapper resource="com/mybatis/pojo/user.xml" />
       </mappers>
     
    </configuration>
     
    3   建相应的pojo、映射文件、表,映射文件的内容:
     <?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="userMapper">
    <!-- 根据id来查询一个用户 ,id="findUserBuId"是dao中要用到的key,parameterType="int" 调用时传递的参数,resultType="com.mybatis.pojo.User"返回的结果类型,sql中的参数要用#{id},id在此可以任意命名 -->
       <select id="findUserBuId" parameterType="int" resultType="com.mybatis.pojo.User">
          select * from tb_user where user_id=#{id}
      </select>
     
     
    <!-- 查询所有用户 -->
       <select id="findAllUser" resultType="com.mybatis.pojo.User">
          select   * from tb_user
       </select>
     
     
    <!-- 添加用户, parameterType="com.mybatis.pojo.User"调用时传递的参数类型,
    sql中的#{loginName},#{password},#{name},必须是#{}格式,
    而且loginName为com.mybatis.pojo.User类的一个属性,代码要提交事务
     
     -->
       <insert id="addUser" parameterType="com.mybatis.pojo.User">
          insert into tb_user(LOGIN_NAME,PASSWORD,NAME)
          values(#{loginName},#{password},#{name})
       </insert>
     
       <!-- 删除用户,sql中的#{userId},必须是#{}格式,而且loginName为com.mybatis.pojo.User类的一个属性,代码要提交事务 -->
       <delete id="deleteUserById" parameterType="int">
         <![CDATA[ delete from tb_user where user_id=#{userId} ]]>
       </delete>
     
       <!-- 修改用户 #username#必须是user对象的属性,代码要提交事务,
       更新时不用查询一个用户,直接设置用户对象的userId属性-->
       <update id="aa" parameterType="com.mybatis.pojo.User">
          update tb_user set login_name=#{loginName} where user_id=#{userId}
       </update>
    </mapper>
    Dao:
    public class UserDao {
     
           private final String resourse = "com/myibatis/xml/configuration.xml";
     
           private SqlSession sqlSession;
     
           public UserDao() {
                  Reader reader;
                  try {
                         reader = Resources.getResourceAsReader(resourse);
     
                         SqlSessionFactory sqlSessionFacroty = new SqlSessionFactoryBuilder()
                                       .build(reader);
                         sqlSession = sqlSessionFacroty.openSession();
     
                  } catch (IOException e) {
                         e.printStackTrace();
                  }
           }
     
           public User findUserById(Integer id) {
                  User user = sqlSession.selectOne("userMapper.findUserBuId", id);
     
                  sqlSession.close();
                  return user;
           }
     
           public List<User> findAllUser() {
                  List<User> users = sqlSession.selectList("userMapper.findAllUser");
                  System.out.println(users.size());
                  sqlSession.close();
                  return users;
           }
     
     
                  sqlSession.close();
                  return users;
           }
     
           public void addUser(User user) {
                  sqlSession.insert("addUser", user);
                  sqlSession.commit();
            sqlSession.close();
           }
     
           public void updateUser(User user) {
                  sqlSession.update("userMapper.aa", user);
                  sqlSession.commit();
                  sqlSession.close();
           }
     
           public void deleteUserByid(Integer id) {
                  sqlSession.delete("userMapper.deleteUserById", id);
                  sqlSession.commit();
            sqlSession.close();
           }
     
    }
    4   测试
    public static void main(String[] args) {
        UserDao userDao = new UserDao();
           User user=new User();
          user.setUserId(9);
          user.setLoginName("aa");
       
          userDao.updateUser(user);
       }
    5   ibatis spring整合
    5.1 为web工程添加spring组件
    5.2 在web.xml添加spring的启动
    5.3 在applicationContext.xml中加数据源和注入,内容:
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
     
        <!--此bean告诉Spring去哪找数据库的配置信息,因为有此Bean才出现下面用${}标记来取变量的语句-->
        <bean id="propertyConfig"
           class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
           <property name="location">
        <!--  属性文件如果是放在某个包下,则在这里读取时,要加上classpath: à <value>classpath:com/ibatistest/maps/dbcpconfig.properties</value>
           </property>
        </bean>
     
        <!--配置一个数据源,根据上面propertyConfig指定的location去找数据库连接的配置信息-->
        <bean id="dataSource"
           class="org.springframework.jdbc.datasource.DriverManagerDataSource">
           <property name="driverClassName">
               <value>${driverName}</value>
           </property>
           <property name="url">
               <value>${url}</value>
           </property>
           <property name="username">
               <value>${username}</value>
           </property>
           <property name="password">
               <value>${password}</value>
           </property>
        </bean>
     
        <!--根据dataSource和configLocation创建一个SqlMapClient-->
        <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
           <property name="configLocation">
              <!--  xml文件如果是放在某个包下,则在这里读取时,要加上classpath: à<value>classpath:com/ibatistest/maps/sql_map_config2.xml</value>
           </property>
           <property name="dataSource">
               <ref bean="dataSource" />
           </property>
        </bean>
     
        <!--根据sqlMapClien创建一个SqlMapClient模版类-->
        <bean id="sqlMapClientTemplate" class="org.springframework.orm.ibatis.SqlMapClientTemplate">
           <property name="sqlMapClient">
               <ref bean="sqlMapClient" />
           </property>
        </bean>
     
        <!--将上面的模版类织入到我们的DAO对象中-->
        <bean id="userDao" class="com.ibatistest.dao.UserDao">
           <property name="sqlMapClientTemplate">
               <ref bean="sqlMapClientTemplate" />
           </property>
        </bean>
    </beans>
     
    5.4  创建com.ibatistest.dao.UserDao,内容:
    package com.ibatistest.dao;
     
    import java.util.List;
     
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.FileSystemXmlApplicationContext;
    import org.springframework.orm.ibatis.SqlMapClientTemplate;
     
    import com.ibatistest.pojo.User;
     
    public class UserDao {
       private SqlMapClientTemplate sqlMapClientTemplate;
     
       public static void main(String[] args) {
          ApplicationContext factory = new FileSystemXmlApplicationContext(
                "WebRoot/WEB-INF/applicationContext.xml");
     
          UserDao userDao = (UserDao) factory.getBean("userDao");
     
          // userDao.findUserByUsername("sa");
     
          // User addUser = new User("ibatis spring add", "33333", "1");
          // userDao.addUser(addUser);
     
          userDao.deleteUserByid(31);
     
          userDao.findAllUser();
       }
     
       private User findUserByUsername(String username) {
          // 查询,getUser是对应映射文件的id,username为传入参数
     
          User user = (User) sqlMapClientTemplate.queryForObject("getUser",
                username);
          System.out.println(user.getUsername() + ">>>>" + user.getId());
          return user;
     
       }
     
       private void addUser(User user) {
          sqlMapClientTemplate.insert("addUser", user);
       }
     
       private void findAllUser() {
          List<User> allUsers = (List<User>) sqlMapClientTemplate
                .queryForList("findAllUser");
          for (User user : allUsers) {
             System.out.println(user.getUsername() + ">>>>" + user.getId());
          }
       }
     
       private void updateUser(User user) {
          sqlMapClientTemplate.update("updateUserById", user);
       }
     
       private void deleteUserByid(Integer id) {
          sqlMapClientTemplate.delete("deleteUserById", id);
       }
     
       public SqlMapClientTemplate getSqlMapClientTemplate() {
          return sqlMapClientTemplate;
       }
     
       public void setSqlMapClientTemplate(
             SqlMapClientTemplate sqlMapClientTemplate) {
          this.sqlMapClientTemplate = sqlMapClientTemplate;
       }
     
    }

    摘自:http://soft.oneedu.cn/bbs/2012/1231/1329.html

  • 相关阅读:
    网页结构树DOM
    网页设计之js
    css了解一下!!!
    Html !!!了解一下
    进程and线程and协程效率对比
    线程
    进程之生产者消费者模型(队列,管道,数据共享,进程池)
    进程之机制问题(锁,信号,事件)
    并发进程
    socket模块其他用法
  • 原文地址:https://www.cnblogs.com/wh-king/p/3227179.html
Copyright © 2011-2022 走看看