.Net转Java自学之路—Mybatis框架篇六(Spring整合、逆向工程)

Mybatis和Spring整合:

   持久层Mybatis的mapper.xml都需要spring进行管理,则需要spring通过单例方式管理SqlSessionFactory。spring和mybatis整合生成代理对象,使用SqlSessionFactory创建SqlSession。

<!-- SqlSessionFactory、数据源 配置:
     在applicationContext.xml中配置SqlSessionFactory -->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
    <!-- 加载mybatis的配置文件 -->
    <property name="configLocation" value="SqlMapConfig.xml的路径"/>
    <!-- 数据源 -->
    <property name="dataSource" ref="dataSource"/>
</bean>
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:db.properties路径">
<!-- 数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <!-- 属性值注入 -->
    <property name="driverClass" value="${jdbc.driverClass}"></property>
    <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
    <property name="user" value="${jdbc.user}"></property>
    <property name="password" value="${jdbc.password}"></property>
</bean>

  整合后的原始开发方式:

    持久层接口需要在spring配置文件中创建,并注入属性SqlSessionFactory。或者让持久层接口实现类继承SqlSessionDaoSupport,并通过this.getSqlSession()方法得到SqlSession。

<bean id="userDao" class="xx.x.x.UserDaoImpl">
    <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao{
    public User findUserById(int id) throws Exception{
        SqlSession sqlSession=this.getSqlSession();
        User user=sqlSession.selectOne("",id);
        return user;
    }
}

  mapper代理方式:

<!-- 在Spring中的mapper配置:
   MapperFactoryBean:根据mapper接口生成代理对象 -->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
    <!-- mapperInterface指定mapper接口-->
    <property name="mapperInterface" value="cn.ccir.mybatis.mapper.UserMapper"/>
    <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>

    该方法需要对每一个mapper进行配置,比较繁琐。可以通过mapper的批量扫描,从mapper包中扫描出mapper的接口,自动创建代理对象,并且在spring容器中注册。

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <!-- 指定扫描的包名
        需要遵循规范:将mapper接口和mapper映射文件名称保持一致,且在一个目录中。
        自动扫描出来的mapper的bean的id为mapper类名(首字母小写)
        若扫描多个包,每个包中间使用半角逗号分隔 -->
    <property name="basePackage" value="cn.ccir.mybatis.mapper"/>
    <!-- 注入sqlSessionFactory。若在name属性值中使用sqlSessionFactory,则在spring配置文件中配置的加载文件创建数据源会不能使用。 -->
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>

Mybatis逆向工程:

   Mybatis针对大量的sql语句编写,故提供了逆向工程,可以针对单表自动生成mybatis执行所需要的代码(mapper接口、mapper映射文件、po等);由数据库的表生成java代码。

  使用方式:

    使用java程序方式,不依赖开发工具来运行逆向工程。

  配置文件:generatorConfig.xml

<?xml version="1.0" encoding="UTF-8"?>    
<!DOCTYPE generatorConfiguration    
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"    
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">    
    
<generatorConfiguration>    
    <properties resource="jdbc.properties" />    
    <context id="sqlserverTables" targetRuntime="MyBatis3">    
        <!-- 生成的pojo,将implements Serializable-->    
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin>    
        <commentGenerator>    
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->    
            <property name="suppressAllComments" value="true" />    
        </commentGenerator>    
    
        <!-- 数据库链接URL、用户名、密码 -->    
        <jdbcConnection driverClass="${jdbc.driverClassName}"    
                        connectionURL="${jdbc.url}"    
                        userId="${jdbc.username}"    
                        password="${jdbc.password}">    
        </jdbcConnection>    
    
        <!--      
        默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer    
            true,把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal      
        -->    
        <javaTypeResolver>    
            <property name="forceBigDecimals" value="false" />    
        </javaTypeResolver>    
    
        <!--     
        生成model模型,对应的包路径,以及文件存放路径(targetProject),targetProject可以指定具体的路径,如./src/main/java,
        也可以使用“MAVEN”来自动生成,这样生成的代码会在target/generatord-source目录下    
        -->    
        <!--<javaModelGenerator targetPackage="com.joey.mybaties.test.pojo" targetProject="MAVEN">-->    
        <javaModelGenerator targetPackage="com.csdn.ingo.entity" targetProject="./src/main/java">    
            <property name="enableSubPackages" value="true"/>    
            <!-- 从数据库返回的值被清理前后的空格  -->    
            <property name="trimStrings" value="true" />    
        </javaModelGenerator>    
    
        <!--对应的mapper.xml文件  -->    
        <sqlMapGenerator targetPackage="mappers" targetProject="./src/main/resources">    
            <property name="enableSubPackages" value="true"/>    
        </sqlMapGenerator>    
    
        <!-- 对应的Mapper接口类文件 -->    
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.csdn.ingo.dao" targetProject="./src/main/java">    
            <property name="enableSubPackages" value="true"/>    
        </javaClientGenerator>    
    
    
        <!-- 列出要生成代码的所有表,这里配置的是不生成Example文件 -->    
        <table tableName="t_user" domainObjectName="UserInfoPO"    
               enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"    
               enableSelectByExample="false" selectByExampleQueryId="false" >    
            <property name="useActualColumnNames" value="false"/>    
        </table>  
    </context>    
</generatorConfiguration>  

  执行程序:

List<String> warnings=new ArrayList<String>();
boolean overwrite=true;
//指定逆向工程配置文件
File configFile=new File("generatorConfig.xml");
ConfigurationParser cp=new ConfigurationParser(warnings);
Configruation config=cp.parseConfiguration(configFile);
DefaultShellCallback callback=new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator=new MyBatisGenerator(config,callback,warnings);
myBatisGenerator.generate(null);
原文地址:https://www.cnblogs.com/zltao/p/10546163.html