• SpringMyBatis解析1-使用示例


    MyBatis使用介绍

    MyBatis的详细使用介绍  http://www.cnblogs.com/xrq730/category/796495.html

    建立PO 

    public class Person {  
        private String id;  
        private String name;  
    //set get 方法、、、  
    }  

    建立Mapper

    mapper是数据库操作的映射文件,也就是我们常说的dao文件。

    public interface PersonDao {  
        public List<Person> query();  
        public void save(Person p);  
        public void delete(String id);  
    }  

    建立配置文件

    配置文件主要用于程序中可变性高的设置,Mybatis的配置文件主要存在于configuration.xml中,当然configuration.xml中省略了其他mybatis的配置,例如settings里面的配置等等。

    configuration:根元素。

    properties:定义配置外在化。

    settings:一些全局性的配置。

    typeAliases:为一些类定义别名。

    typeHandlers:定义类型处理,也就是定义Java类型与数据库中的数据类型之间的转换关系。

    objectFactory:用于指定结果集对象的实例是如何创建的。

    plugins:MyBatis的插件,插件可以修改MyBatis内部的运行规则。

    environments:环境。

    environment:配置MyBatis的环境。

    transactionManager:事务管理器。

    dataSource:数据源。

    <?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>    
        <!-- 对事务的管理和连接池的配置 -->    
        <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://localhost:3306/test" />  
                       <property name="username" value="root" />  
                       <property name="password" value="root" />    
                </dataSource>    
            </environment>    
        </environments>    
        <!-- mapping 文件路径配置 -->    
        <mappers>    
            <mapper resource="resource/PersonMapper.xml" />    
        </mappers>    
    </configuration>  

    建立映射文件

    <?xml version="1.0" encoding="UTF-8" ?>  
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://www.mybatis.org/dtd/mybatis-3-mapper.dtd" >  
    <mapper namespace="net.itaem.dao.PersonDao" >  
     <resultMap id="resultMap" type="net.itaem.po.Person" >  
         <result column="id" property="id" jdbcType="CHAR" />  
        <result column="name" property="name" jdbcType="CHAR" />  
      </resultMap>  
      <!--添加-->   
      <insert id="save"  parameterType="net.itaem.po.Person">  
       insert into person(id,name) value(#{id,jdbcType=CHAR},#{name,jdbcType=CHAR})  
      </insert>  
      <!--查询-->  
      <select id="query"  resultMap="resultMap">  
       select * from person  
      </select>  
      <!--删除-->  
      <delete id="delete" parameterType="java.lang.String">  
       delete from person  where id=#{id,jdbcType=CHAR}  
      </delete>  
    </mapper>  

    建立测试类

    public class Test {  
        public static void main(String[] args) throws Exception {  
            Reader reader=Resources.getResourceAsReader("resource/configuration.xml");  
            SqlSessionFactory sessionFactory=new SqlSessionFactoryBuilder().build(reader);  
            SqlSession session=sessionFactory.openSession();  
            PersonDao personDao=session.getMapper(PersonDao.class);  
            Person person=new Person("11","Fighter168");  
            personDao.save(person);  
            //这里一定要提交,不然数据无法插入  
            session.commit();  
            session.close();  
        }  
    }  

    Spring中使用MyBatis介绍

    了解了MyBatis的独立使用过程后,我们再看看它与Spring整合的使用方式,比对之前的示例来找出Spring究竟为我们做了哪些操作来简化程序员的业务开发。由于在上面示例基础上作更改,所以,Person,PersonDao,映射文件保持不变。

    创建Spring配置文件

    里面主要配置的是数据源,sqlSessionFactory和Dao的信息。

    <?xml version="1.0" encoding="UTF-8"?>  
    <beans xmlns="http://www.springframework.org/schema/beans"  
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
    > <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/test"/> <property name="username" value="root"/> <property name="password" value="123abc"/> <!-- 连接池启动时候的初始连接数 --> <property name="initialSize" value="10"/> <!-- 最小空闲值 --> <property name="minIdle" value="5"/> <!-- 最大空闲值 --> <property name="maxIdle" value="20"/> <property name="maxWait" value="2000"/> <!-- 连接池最大值 --> <property name="maxActive" value="50"/> <property name="logAbandoned" value="true"/> <property name="removeAbandoned" value="true"/> <property name="removeAbandonedTimeout" value="180"/> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="configLocation" value="classpath:/resource/cfg.xml"/> <property name="dataSource" ref="dataSource"/> </bean> <bean id="personDao" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="net.itaem.dao.PersonDao"/> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean> </beans>

    看到上面配置personDao,我们单独的使用一个Bean去创建它,也许我们会想到如果我们又几十甚至是几百个dao,那配置就可能很恐怖了,不过,Spring的作者也考虑到了这样的问题,针对这种情况,如果dao很多的情况,其实也是可以采取扫描dao的形式注入spring的。

    创建MyBatis配置文件

    mybatis的配置文件除了去掉environment标签,其他没啥区别。

    <?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>    
        <!-- mapping 文件路径配置 -->    
        <mappers>    
            <mapper resource="resource/PersonMapper.xml" />    
        </mappers>    
    </configuration>  

    Spring使用MyBatis测试

    public class SpringTest {  
        public static void main(String[] args) {  
            ApplicationContext context=new ClassPathXmlApplicationContext("resource/ApplicationContext.xml");  
            PersonDao personDao=(PersonDao) context.getBean("personDao");  
            Person person=new Person("12","Fighter168");  
            personDao.save(person);  
        }  
    }  

    在Spring中使用MyBatis是相当方便的,不需要我们去管理sqlSessionFactory以及SqlSession的管理,更不需要我们去操作简单的事务。

  • 相关阅读:
    Tx.Origin 用作身份验证
    区块链夺宝合约
    (转)JVM内存分配 -Xms128m -Xmx512m -XX:PermSize=128m -XX:MaxPermSize=512m
    Oracle查看用户密码过期,修改永不过期
    springboot测试
    (转)Springboot定时任务
    书单
    (转)redis分布式锁-SETNX实现
    mybatis-generator 代码自动生成工具
    (转)通过Ajax使用FormData对象无刷新上传文件
  • 原文地址:https://www.cnblogs.com/wade-luffy/p/6093289.html
Copyright © 2020-2023  润新知