OSGI系列之mybatis

一、不在blueprint文件中进行操作mybatis (绝对路径)

1、mybatis的配置文件(SqlMapConfig.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">


<configuration>
    <settings>
        <setting name="useGeneratedKeys" value="false"/>
    </settings>
    
    <typeAliases>
        <typeAlias alias="aa" type="com.xxx.yyy.contract"/>    
    </typeAliases>
    
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="org.postgresql.Driver"/>
                <property name="url" value="jdbc:postgresql://127.0.0.1:5432/uuu?characterEncoding=UTF-8"/>
                <property name="username" value="postgres"/>
                <property name="password" value="12345678"/>
            </dataSource>
        </environment>
    </environments>


    <mappers>
        <mapper url="file:///D:\deploy\mybatis\smsadmin\kkk.xml"/>
    </mappers>
</configuration>
2.在blueprint中引入mybatis(SqlMapConfig.xml)文件

<cm:property-placeholder persistent-id="com.xxx.yyy.gw" update-strategy="reload">
          <cm:default-properties>
              <cm:property name="SMSAdmin.SqlConfigUri" value="D:\\deploy\\mybatis\\smsadmin\\SqlMapConfig.xml"/>
          </cm:default-properties>
  </cm:property-placeholder>
    
  <bean id="sqlConfig" class="com.xxx.yyy.gw.Utils.MybatisSqlSessionFactory">
          <property name="sqlmapconfiguri" value="${SMSAdmin.SqlConfigUri}" />
  </bean>

3.封装MybatisSqlSessionFactory工具类,获取mybatis当前Session

import java.io.FileInputStream;
  import java.io.IOException;
  import org.apache.camel.util.IOHelper;
  import org.apache.ibatis.session.SqlSession;
  import org.apache.ibatis.session.SqlSessionFactory;
  import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  import org.slf4j.Logger;
  import org.slf4j.LoggerFactory;

  public class MybatisSqlSessionFactory {

    private final static Logger log = LoggerFactory.getLogger(MybatisSqlSessionFactory.class);
    private SqlSessionFactory sqlSessionFactory;
    private String sqlmapconfiguri="D:\\deploy\\mybatis\\smsadmin\\SqlMapConfig.xml";
    
    public String getSqlmapconfiguri() {
        return sqlmapconfiguri;
    }

    public void setSqlmapconfiguri(String sqlmapconfiguri) {
        this.sqlmapconfiguri = sqlmapconfiguri;
    }

    public static MybatisSqlSessionFactory mybatisSqlSessionFactory;
    
    public SqlSessionFactory createSqlSessionFactory() throws IOException {
        
        if(sqlSessionFactory == null){
            // TODO Auto-generated method stub
            FileInputStream is = new FileInputStream(sqlmapconfiguri);
            try {
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            } catch(Exception e){
                e.printStackTrace();
                log.error("异常:",e);
            }finally {
                IOHelper.close(is);
            }
        }
        return sqlSessionFactory;
    }
    
    public static MybatisSqlSessionFactory getMybatisSqlSessionFactory() {
        if(mybatisSqlSessionFactory ==null){//避免大多数不需要同步的情况发生阻塞
            synchronized (MybatisSqlSessionFactory.class){
                if(mybatisSqlSessionFactory == null){//基本的判断,判断是否实例化
                    mybatisSqlSessionFactory = new MybatisSqlSessionFactory();
                }
            }
        }    
        return mybatisSqlSessionFactory;
    }
    
    public static SqlSession GetSession() throws Exception{
        
        SqlSession session = MybatisSqlSessionFactory
        .getMybatisSqlSessionFactory()
        .createSqlSessionFactory()
        .openSession();
        log.info("session=",session.getConfiguration().getDatabaseId());
        return session;
    }
}
4.使用实例

public class Service{

private final static Logger log = LoggerFactory.getLogger(Service.class);
    
    private static SqlSession session;
    
    public Service() {
        try {
            session =MybatisSqlSessionFactory
                    .getMybatisSqlSessionFactory()
                    .createSqlSessionFactory()
                    .openSession();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            log.warn("获取session异常:", e);
        }
    }
    
    @Override
    public int deleteByPrimaryKey(String Id) {
        try{
            if(StringUtils.isNotEmpty(Id)){    
                if(session != null){
                    int status = session.delete("deleteByPrimaryKey", Id);
                    if(status > 0){
                        session.commit();
                        return status;
                    }
                }else{
                    log.info("session为空!");
                }
            }else{
                log.info("templateId为空!");
            }
        }catch(Exception e){
            session.rollback();
            log.warn("数据库访问异常:",e);
        }
        
        return 0;
    }

    @Override
    public int insert(Object record) {
        try{
            if(record!=null){
                if(session != null){
                    int status = session.insert("insert", record);
                    if(status > 0){
                        session.commit();
                        return status;
                    }
                }else{
                    log.info("session为空!");
                }
            }else{
                log.info("record为空!");
            }
        }catch(Exception e){
            session.rollback();
        }
        return 0;
    }
}

二、不在blueprint文件中进行操作mybatis (相对路径,推荐)

1、mybatis的配置文件(SqlMapConfig.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">


<configuration>
    <settings>
        <setting name="useGeneratedKeys" value="false"/>
    </settings>
    
    <typeAliases>
        <typeAlias alias="aa" type="com.xxx.yyy.contract"/>    
    </typeAliases>
    
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="org.postgresql.Driver"/>
                <property name="url" value="jdbc:postgresql://127.0.0.1:5432/uuu?characterEncoding=UTF-8"/>
                <property name="username" value="postgres"/>
                <property name="password" value="12345678"/>
            </dataSource>
        </environment>
    </environments>

</configuration>



2.Mapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<mappers>
    <mapper resource="/mybatis/aaMapper.xml"/>
.....

</mappers>

3.封装Mybatis工厂工具

3.1.SqlMapConfig.java类

public class SqlMapConfig {
    
     private final static Logger log = LoggerFactory.getLogger(MybatisTemplate.class);

    private String driver;
    private String url;
    private String username;
    private String password;
    private String poolMaximumIdleConnections;
    private String poolMaximumActiveConnections;
    private String mybatisPath;

    public String getDriver() {
        return driver;
    }

    public void setDriver(String driver) {
        this.driver = driver;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPoolMaximumIdleConnections() {
        return poolMaximumIdleConnections;
    }

    public void setPoolMaximumIdleConnections(String poolMaximumIdleConnections) {
        this.poolMaximumIdleConnections = poolMaximumIdleConnections;
    }

    public String getPoolMaximumActiveConnections() {
        return poolMaximumActiveConnections;
    }

    public void setPoolMaximumActiveConnections(String poolMaximumActiveConnections) {
        this.poolMaximumActiveConnections = poolMaximumActiveConnections;
    }

    public String getMybatisPath() {
        return mybatisPath;
    }

    public void setMybatisPath(String mybatisPath) {
        this.mybatisPath = mybatisPath;
    } 
}

3.2.创建MybatisSqlSessionFactory.java类

public class MybatisSqlSessionFactory {

    private final static Logger log = LoggerFactory.getLogger(MybatisSqlSessionFactory.class);
    public static SqlSessionFactory sqlSessionFactory;
    private SqlMapConfig config;

    public void createSqlSessionFactory(Class classLoader) throws IOException {
        if (sqlSessionFactory == null) {
            Properties properties = new Properties();
            properties.setProperty("driver", config.getDriver());
            properties.setProperty("url", config.getUrl().replace('#', '='));
            properties.setProperty("username", config.getUsername());
            properties.setProperty("password", config.getPassword());
            properties.setProperty("poolMaximumActiveConnections", config.getPoolMaximumActiveConnections());
            properties.setProperty("poolMaximumIdleConnections", config.getPoolMaximumIdleConnections());
            try (InputStream configFileInputStream = classLoader.getResourceAsStream("/mybatis/SqlMapConfig.xml")) {
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(configFileInputStream, properties);

                Configuration configuration = sqlSessionFactory.getConfiguration();

                InputStream mapperFileInputStream;
                mapperFileInputStream = classLoader.getResourceAsStream("/mybatis/Mapper.xml");
                if (mapperFileInputStream == null) {
                    throw new Exception("can not find Mapper.xml in resource /mybatis");
                }
                SAXReader read = new SAXReader();
                Document document = read.read(mapperFileInputStream);
                List list = document.getRootElement().elements();
                for (Iterator it = list.iterator(); it.hasNext();) {
                    Element element = (Element) it.next();
                    String resource = element.attributeValue("resource");
                    InputStream inputStream;
                    inputStream = classLoader.getResourceAsStream(resource);
                    if (inputStream == null) {
                        throw new Exception("can not find " + resource);
                    }
                    XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
                    mapperParser.parse();
                    inputStream.close();
                }
                mapperFileInputStream.close();
            } catch (DocumentException ex) {
                log.error(ex.getMessage(), ex);
            } catch (Exception ex) {
                log.error(ex.getMessage(), ex);
            }
        }
    }

    public void setConfig(SqlMapConfig config) {
        this.config = config;
    }

}

3.3创建MybatisTemplate.java

public class MybatisTemplate {
    
    private final static Logger log = LoggerFactory.getLogger(MybatisTemplate.class);
    
    private static MybatisSqlSessionFactory sessionFactory;
    
    protected SqlSession getSession() {
        try {
            sessionFactory.createSqlSessionFactory(this.getClass());
            return MybatisSqlSessionFactory.sqlSessionFactory.openSession(true);
        } catch (IOException ex) {
            log.error(ex.getMessage(), ex);
        }
        return null;
    }
    
    public void setSessionFactory(MybatisSqlSessionFactory sessionFactory) {
        MybatisTemplate.sessionFactory = sessionFactory;
    }
    
}
</pre><span style="font-family:'Helvetica Neue',Helvetica,Arial,sans-serif; font-size:13px; line-height:19.5px; background-color:rgb(245,245,245)">4.引入调用</span><pre name="code" class="html"><pp:property-placeholder app-id="orm" env="rd" version="1_0_0_0" files="SqlMapConfig" reload="true" />
    <bean id="mybatisConfig" class="Jmust.Utility.MybatisFactory.SqlMapConfig">
        <property name="driver" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
        <property name="poolMaximumActiveConnections" value="${poolMaximumActiveConnections}" />
        <property name="poolMaximumIdleConnections" value="${poolMaximumIdleConnections}" />
        <property name="mybatisPath" value="${mybatisPath}"/>
        
    </bean>
<bean id="sessionFactoryBean" class="Jmust.Utility.MybatisFactory.MybatisSqlSessionFactory"> 
        <property name="config" ref="mybatisConfig" />    
    </bean>
<bean class="Jmust.Utility.MybatisFactory.MybatisTemplate" > 
        <property name="sessionFactory" ref="sessionFactoryBean" />    
    </bean>

5.例子

public class SMSTemplateService extends MybatisTemplate implements ISMSTemplate {
    int status = getSession().insert("insertTemplate", record);
}




你可能感兴趣的:(mybatis)