droolsbench项目灵活部署工程

1 篇文章 0 订阅
0 篇文章 0 订阅

droolsbench项目灵活部署工程

目录

│ droolstraining.iml
│ pom.xml

├─.idea
│ compiler.xml
│ encodings.xml
│ misc.xml
│ sbt.xml
│ vcs.xml
│ workspace.xml

├─logs
│ runtime.log.2019-07-02.log

├─src
│ ├─main
│ │ ├─java
│ │ │ ├─mybatis
│ │ │ │ ├─config
│ │ │ │ │ mybatis-conf.xml
│ │ │ │ │
│ │ │ │ └─mapper
│ │ │ │ ApplicantListMapper.xml
│ │ │ │ UserInfoMapper.xml
│ │ │ │
│ │ │ └─org
│ │ │ └─sky
│ │ │ └─drools
│ │ │ ├─approvaldecision
│ │ │ │ PaymentInfo.java
│ │ │ │ RemotePaymentRulz.java
│ │ │ │ StatefulRemotePaymentRulz.java
│ │ │ │
│ │ │ ├─dao
│ │ │ │ ├─mapper
│ │ │ │ │ ApplicantListMapper.java
│ │ │ │ │ UserInfoMapper.java
│ │ │ │ │
│ │ │ │ └─proxy
│ │ │ │ DAOProxyFactory.java
│ │ │ │
│ │ │ ├─dbrulz
│ │ │ │ KieSessionUtil.java
│ │ │ │ UserInfoBean.java
│ │ │ │
│ │ │ ├─service
│ │ │ │ UserInfoService.java
│ │ │ │ UserInfoServiceImpl.java
│ │ │ │
│ │ │ └─sql
│ │ │ └─datasource
│ │ │ DruidDataSourceFactory.java
│ │ │ IsSession.java
│ │ │ SessionFactory.java
│ │ │
│ │ └─resources
│ │ ├─mapper
│ │ │ ApplicantListMapper.xml
│ │ │ UserInfoMapper.xml
│ │ │
│ │ ├─mybatis
│ │ │ └─conf
│ │ │ mybatis-conf.xml
│ │ │
│ │ └─rules
│ │ user.drl
│ │
│ └─test
│ └─java
│ └─org
│ └─sky
│ └─drools
│ └─dbrulz
│ Test.java

└─target
│ drools-training-2.0.12.jar

├─classes
│ ├─mapper
│ │ ApplicantListMapper.xml
│ │ UserInfoMapper.xml
│ │
│ ├─mybatis
│ │ └─conf
│ │ mybatis-conf.xml
│ │
│ ├─org
│ │ └─sky
│ │ └─drools
│ │ ├─approvaldecision
│ │ │ PaymentInfo.class
│ │ │ RemotePaymentRulz.class
│ │ │ StatefulRemotePaymentRulz.class
│ │ │
│ │ ├─dao
│ │ │ ├─mapper
│ │ │ │ ApplicantListMapper.class
│ │ │ │ UserInfoMapper.class
│ │ │ │
│ │ │ └─proxy
│ │ │ DAOProxyFactory.class
│ │ │
│ │ ├─dbrulz
│ │ │ UserInfoBean.class
│ │ │
│ │ ├─service
│ │ │ UserInfoService.class
│ │ │ UserInfoServiceImpl.class
│ │ │
│ │ └─sql
│ │ └─datasource
│ │ DruidDataSourceFactory.class
│ │ IsSession.class
│ │ SessionFactory.class
│ │
│ └─rules
│ user.drl

├─maven-archiver
│ pom.properties

├─maven-status
│ └─maven-compiler-plugin
│ ├─compile
│ │ └─default-compile
│ │ createdFiles.lst
│ │ inputFiles.lst
│ │
│ └─testCompile
│ └─default-testCompile
│ createdFiles.lst
│ inputFiles.lst

└─test-classes
└─org
└─sky
└─drools
└─dbrulz
Test.class

工程配置文件源码

mybatis-conf.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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="org.sky.drools.sql.datasource.DruidDataSourceFactory">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://118.25.197.252:3306/test?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8" />
                <property name="username" value="root" />
                <property name="password" value="attack" />
                <property name="maxActive" value="20" />
                <property name="initialSize" value="5" />
                <property name="minIdle" value="1" />
                <property name="testWhileIdle" value="true" />
                <property name="validationQuery" value="SELECT 1" />
                <property name="testOnBorrow" value="true" />
                <property name="testOnReturn" value="true" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/UserInfoMapper.xml" />
        <mapper resource="mapper/ApplicantListMapper.xml" />
    </mappers>
</configuration>

ApplicantListMapper.xml:

<?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="org.sky.drools.dao.mapper.UserInfoMapper">
    <select id="selelctUserInApplicant" parameterType="String" resultType="int">
  SELECT count(1) from APPLICANT_LIST WHERE user_id=#{userId}
</select>
</mapper>

UserInfoMapper.xml

<?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="org.sky.drools.dao.mapper.UserInfoMapper">
    <select id="selelctUser" parameterType="String" resultType="int">
  SELECT age FROM user_info WHERE user_id=#{userId}
</select>
</mapper>

user.drl:

package rules;
import org.sky.drools.dbrulz.UserInfoBean;
dialect "java"

declare User
    age : int;
    validFlag : boolean;
end
rule "init studentbean"
salience 1000
    when
        $u:UserInfoBean(userId!=null)
then
      System.out.println("valid applicant for["+$u.getUserId()+"] and validFlag is["+$u.isValidFlag()+"]");
      User userVO=new User();
      userVO.setAge( $u.getAge());
      userVO.setValidFlag($u.isValidFlag());
      insert(userVO);
end

rule "less than < 17"

    when
       user: User(age<17) && u:UserInfoBean(userId!=null)
    then
       u.setApplicant("0");
end
rule "less than < 45"
    when
       (user: User(age<46 && age>=17)) && u:UserInfoBean(userId!=null)
then
        System.out.println("set applicant for "+u.getUserId()+" to 7000000");
        u.setApplicant("7000000");
end
rule "less than < 70"
    when
       (user:User(age<70 && age>=46)) && u:UserInfoBean(userId!=null)
then
        System.out.println("set applicant for "+u.getUserId()+" to 5000000");
        u.setApplicant("5000000");
end

rule "not a valid applicant"
    when
       user:User(!validFlag) && u:UserInfoBean(userId!=null)
then
        u.setApplicant("0");
end

Test.java:

package org.sky.drools.dbrulz;

import org.drools.core.base.RuleNameEndsWithAgendaFilter;
import org.junit.runner.RunWith;
import org.kie.api.runtime.KieSession;

//@RunWith(SpringJUnit4ClassRunner.class)

//@ContextConfiguration(locations = { "classpath:spring-mybatis.xml" })

public class Test {

    /*@org.junit.Test
    public void testAge() throws Exception {
        String name="sala";
        UserInfoBean u=new UserInfoBean();
        u.setUserId(name);
        int age=u.getAge();
        Boolean w=u.isValidFlag();
        System.out.println("age:"+age+";flg:"+w);
    }*/

    /*@org.junit.Test
    public void testRule() throws Exception {
            KieSession kieSession=KieSessionUtil.getKieSession();
            UserInfoBean u=new UserInfoBean();
            u.setUserId("sala");
            kieSession.insert(u);
            kieSession.fireAllRules(new RuleNameEndsWithAgendaFilter("rule1"));
            System.err.println("规则执行完毕后applicant:"+u.getApplicant());
    }

    @org.junit.Test
    public void testRule2() throws Exception {
        KieSession kieSession=KieSessionUtil.getKieSession();
        UserInfoBean u=new UserInfoBean();
        u.setUserId("sala");
        kieSession.insert(u);
        kieSession.fireAllRules();
        System.err.println("规则执行完毕后applicant:"+u.getApplicant());
    }*/
}

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>os.nut.drools</groupId>
    <artifactId>drools-training</artifactId>
    <version>2.0.12</version>
    <properties>
        <drools.version>6.5.0.Final</drools.version>
    </properties>
    <repositories>
        <repository>
            <id>guvnor-m2-repo</id>
            <name>Guvnor M2 Repo</name>
            <!--<url>http://localhost:8080/kie-drools/maven2/</url>-->
            <url>http://118.25.197.252:8080/drools-wb/maven2/</url>
        </repository>
    </repositories>
    <dependencies>
        <!-- drools -->
        <dependency>
            <groupId>org.kie</groupId>
            <artifactId>kie-api</artifactId>
            <version>${drools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.drools</groupId>
            <artifactId>drools-core</artifactId>
            <version>${drools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.drools</groupId>
            <artifactId>drools-compiler</artifactId>
            <version>${drools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.drools</groupId>
            <artifactId>drools-decisiontables</artifactId>
            <version>${drools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.drools</groupId>
            <artifactId>drools-templates</artifactId>
            <version>${drools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.kie</groupId>
            <artifactId>kie-ci</artifactId>
            <version>${drools.version}</version>
        </dependency>
        <!-- test -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.0</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.18</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>

        <!--<dependency>
        <groupId>org.kie</groupId>
        <artifactId>kie-spring</artifactId>
        <version>${drools.version}</version>
    </dependency>

        <dependency>
            <groupId>org.eclipse.jdt</groupId>
            <artifactId>org.eclipse.jdt.core</artifactId>
            <version>3.15.0</version>
        </dependency>-->
    </dependencies>

</project>

正式工程源码:

PaymentInfo.java:

package org.sky.drools.approvaldecision;

public class PaymentInfo implements java.io.Serializable {

    static final long serialVersionUID = 1L;

    public PaymentInfo() {
    }

    private int moneyAmount = 0;
    private String decisionPath = "";

    public void setMoneyAmount(int amount) {
        this.moneyAmount = amount;
    }

    public int getMoneyAmount() {
        return this.moneyAmount;
    }

    public void setDecisionPath(String path) {
        this.decisionPath = path;
    }

    public String getDecisionPath() {
        return this.decisionPath;
    }
}

RemotePaymentRulz

package org.sky.drools.approvaldecision;

import java.io.InputStream;

import org.drools.compiler.kproject.ReleaseIdImpl;
import org.drools.core.io.impl.UrlResource;
import org.kie.api.KieServices;
import org.kie.api.builder.KieModule;
import org.kie.api.builder.KieRepository;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.StatelessKieSession;

public class RemotePaymentRulz {

    public static void main(String[] args) throws Exception {
        String url = "http://localhost:8080/kie-drools-wb/maven2/org/sky/drools/ApprovalDecision/1.0.0/ApprovalDecision-1.0.0.jar";
        ReleaseIdImpl releaseId = new ReleaseIdImpl("org.sky.drools", "ApprovalDecision", "LATEST");
        KieServices ks = KieServices.Factory.get();
        KieRepository kr = ks.getRepository();
        UrlResource urlResource = (UrlResource) ks.getResources().newUrlResource(url);
        urlResource.setUsername("tomcat");
        urlResource.setPassword("tomcat");
        urlResource.setBasicAuthentication("enabled");
        InputStream is = urlResource.getInputStream();
        KieModule kModule = kr.addKieModule(ks.getResources().newInputStreamResource(is));
        KieContainer kContainer = ks.newKieContainer(kModule.getReleaseId());
        StatelessKieSession kSession = kContainer.newStatelessKieSession("defaultStatelessKieSession");
        PaymentInfo m = new PaymentInfo();
        m.setMoneyAmount(5000);
        kSession.execute(m);
        System.out.println(m.getDecisionPath());
        if (m.getDecisionPath().equalsIgnoreCase("m")) {
            System.out.println("数额<=5000需要经理审批");
        } else {
            System.out.println("数额>5000需要总经理审批");
        }
    }
}

StatefulRemotePaymentRulz

package org.sky.drools.approvaldecision;

import org.drools.core.io.impl.UrlResource;
import org.kie.api.KieServices;
import org.kie.api.builder.KieModule;
import org.kie.api.builder.KieRepository;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;

import java.io.InputStream;

public class StatefulRemotePaymentRulz {

    public static void main(String[] args) throws Exception {
        String url = "http://localhost:8080/kie-drools-wb/maven2/org/sky/drools/ApprovalDecision/1.0.0/ApprovalDecision-1.0.0.jar";

        KieServices ks = KieServices.Factory.get();
        KieRepository kr = ks.getRepository();
        UrlResource urlResource = (UrlResource) ks.getResources().newUrlResource(url);
        urlResource.setUsername("tomcat");
        urlResource.setPassword("tomcat");
        urlResource.setBasicAuthentication("enabled");
        InputStream is = urlResource.getInputStream();
        KieModule kModule = kr.addKieModule(ks.getResources().newInputStreamResource(is));
        KieContainer kContainer = ks.newKieContainer(kModule.getReleaseId());
        KieSession kieSession = kContainer.newKieSession();
        try {
            PaymentInfo m = new PaymentInfo();
            m.setMoneyAmount(10000);
            kieSession.insert(m);
            kieSession.fireAllRules();
            System.out.println(m.getDecisionPath());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                kieSession.dispose();
            } catch (Exception e) {
            }
        }

    }
}

ApplicantListMapper

package org.sky.drools.dao.mapper;

import org.apache.ibatis.annotations.Mapper;

//@Mapper
public interface ApplicantListMapper {
    public Integer selelctUserInApplicant(String userId);
}

UserInfoMapper

package org.sky.drools.dao.mapper;

import org.apache.ibatis.annotations.Mapper;

//@Mapper
public interface UserInfoMapper {
    public Integer selelctUser(String userId);
}

DAOProxyFactory

package org.sky.drools.dao.proxy;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionManager;
import org.sky.drools.sql.datasource.IsSession;
import org.sky.drools.sql.datasource.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DAOProxyFactory implements InvocationHandler {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private Object targetObject;

    public Object createProxyInstance(Object targetObject) {

        this.targetObject = targetObject;
        return Proxy.newProxyInstance(this.targetObject.getClass().getClassLoader(),
                this.targetObject.getClass().getInterfaces(), this);
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        SqlSessionFactory sqlSessionFactory = null;
        Object result = null;
        SqlSession session = null;
        try {

            Field[] fields = targetObject.getClass().getDeclaredFields();
            if (fields.length > 1) {
                throw new Exception("[mybatis]--->Expected only 1 myBatis SqlSession in [" + targetObject.getClass() + "] but found more than 1");
            }
            for (int i = 0; i < fields.length; i++) {
                if (fields[i].isAnnotationPresent(IsSession.class)) {
                    Field field = fields[i];
                    String fieldName = field.getName();
                    StringBuffer methodName = new StringBuffer();
                    methodName.append("set");
                    methodName.append(fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1));
                    logger.debug("[mybatis]--->init mybatis session start......");
                    logger.debug("[mybatis]--->the methodName [" + methodName.toString() + "] will be set mybatis session");
                    Method m = targetObject.getClass().getMethod(methodName.toString(), SqlSession.class);
                    sqlSessionFactory = SessionFactory.getInstance().factory;
                    logger.debug("[mybatis]--->get db connection from connection pool");
                    session = SqlSessionManager.newInstance(sqlSessionFactory);
                    logger.debug("[mybatis]--->get db connection done");
                    session = sqlSessionFactory.openSession();
                    m.invoke(targetObject, session);
                    logger.debug("[mybatis]--->Done mybatis session......");
                }
            }
            logger.debug("[mybatis]--->open mybatis session and begin Query......");
            result = method.invoke(targetObject, args);
        } catch (Exception e) {
            throw new Exception("[mybatis]--->Init SqlSession Error:" + e.getMessage(), e);
        } finally {
            try {
                session.close();
                logger.debug("[mybatis]--->close mybatis session");
            } catch (Exception e) {
            }
        }
        return result;
    }
}

KieSessionUtil

/*package org.sky.drools.dbrulz;

import org.kie.api.KieServices;
import org.kie.api.builder.*;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.io.ResourceFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;

public class KieSessionUtil {
    private static final String RULES_PATH = "rules/";
   public static KieSession getKieSession() throws IOException {
       ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();*/
       //Resource[] files=resourcePatternResolver.getResources("classpath*:" + RULES_PATH + "**/*.*");

       /*KieServices ser=KieServices.Factory.get();
       KieFileSystem kieFileSystem = ser.newKieFileSystem();
       for (Resource file : files) {
           kieFileSystem.write(ResourceFactory.newClassPathResource(RULES_PATH + file.getFilename(), "UTF-8"));
       }
       //return kieFileSystem;
       final KieRepository kieRepository = ser.getRepository();
       kieRepository.addKieModule(new KieModule() {
           public ReleaseId getReleaseId() {
               return kieRepository.getDefaultReleaseId();
           }
       });
       KieBuilder kieBuilder = ser.newKieBuilder(kieFileSystem);
       kieBuilder.buildAll();
       KieContainer container =ser.newKieContainer(kieRepository.getDefaultReleaseId());
       KieSession kieSession = container.newKieSession();
       return kieSession;
   }
}*/

UserInfoBean

package org.sky.drools.dbrulz;

import org.sky.drools.dao.proxy.DAOProxyFactory;
import org.sky.drools.service.UserInfoService;
import org.sky.drools.service.UserInfoServiceImpl;

import java.io.Serializable;

public class UserInfoBean implements Serializable {
        private int age = 0;
        private String applicant;
        private String userId;
        private boolean validFlag = false;

//没什么好多说的,我们为这个Bean提供了一组field,同时我们会为每个私有成员生成一对set/get方法。

        //关键在于getAge()方法的覆盖:


        public void setAge(int age) {
                this.age = age;
        }

        public String getApplicant() {
                return applicant;
        }

        public void setApplicant(String applicant) {
                this.applicant = applicant;
        }

        public String getUserId() {
                return userId;
        }

        public void setUserId(String userId) {
                this.userId = userId;
        }

        public boolean isValidFlag() throws Exception {
                int aCount = 0;
                //boolean result = false;
                DAOProxyFactory fac=new DAOProxyFactory();
                try {
                        UserInfoService userService = (UserInfoService) fac.createProxyInstance(new UserInfoServiceImpl());
                        aCount = userService.existInList(userId);
                        System.out.println("aCount====" + aCount);
                        if (aCount > 0) {
                                validFlag = true;
                        }
                }catch (Exception e){
                        System.out.println(e.getMessage());
                        throw new Exception("Mybatis error:"+e.getMessage(),e);
                }
                return validFlag;
        }

        public void setValidFlag(boolean validFlag) {
                this.validFlag = validFlag;
        }

        public int getAge() throws Exception {
        int age = 0;

        try {
        DAOProxyFactory factory = new DAOProxyFactory();
        UserInfoService stdService = (UserInfoService) factory.createProxyInstance(new UserInfoServiceImpl());
        age = stdService.getAge(userId);
        System.out.println(age);
        } catch (Exception e) {
        System.err.println(e.getMessage());
        throw new Exception("mybatis error: " + e.getMessage(), e);
        }
        return age;
        }

}

UserInfoService

package org.sky.drools.service;

public interface UserInfoService {
    public int getAge(String userId) throws Exception;
    public int existInList(String userId) throws Exception;
}

UserInfoServiceImpl

package org.sky.drools.service;

import org.apache.ibatis.session.SqlSession;
import org.sky.drools.dao.mapper.ApplicantListMapper;
import org.sky.drools.dao.mapper.UserInfoMapper;
import org.sky.drools.sql.datasource.IsSession;

public class UserInfoServiceImpl implements UserInfoService {

    @IsSession
    private SqlSession batisSession = null;

    public void setBatisSession(SqlSession batisSession) {
        this.batisSession = batisSession;
    }

    public int getAge(String userId) throws Exception {
        UserInfoMapper userMapper = batisSession.getMapper(UserInfoMapper.class);
        int age = userMapper.selelctUser(userId);
        return age;
    }

    public int existInList(String userId) throws Exception {
        ApplicantListMapper listMapper = batisSession.getMapper(ApplicantListMapper.class);
        int result = listMapper.selelctUserInApplicant(userId);
        return result;
    }

}

DruidDataSourceFactory

package org.sky.drools.sql.datasource;

import org.apache.ibatis.datasource.DataSourceFactory;

import javax.sql.DataSource;
import java.util.Properties;

public class DruidDataSourceFactory extends com.alibaba.druid.pool.DruidDataSourceFactory implements DataSourceFactory {
    protected Properties properties;

    public void setProperties(Properties props) {

        this.properties= props;

    }

    public DataSource getDataSource() {

        try {

            return  createDataSource(properties);

        } catch (Exception e) {

            e.printStackTrace();

        }

        return null;

    }
}

IsSession

package org.sky.drools.sql.datasource;

import java.lang.annotation.*;

@Documented //文档
@Retention(RetentionPolicy.RUNTIME) //在运行时可以获取
@Target({ ElementType.TYPE, ElementType.METHOD,ElementType.FIELD}) //作用到类,方法,接口上等
@Inherited //子类会继承
public @interface IsSession {
}

SessionFactory

package org.sky.drools.sql.datasource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;

public class SessionFactory {
    //private static Singleton1 instance = new Singleton1();

    private SessionFactory() {
    }

    private final static Logger logger = LoggerFactory.getLogger(SessionFactory.class);
    private static SessionFactory instance = null;
    public static SqlSessionFactory factory = null;

    public synchronized static SessionFactory getInstance() throws Exception {
        if (instance == null) {
            String resource = "/mybatis/conf/mybatis-conf.xml";
            InputStream confInputStream = null;
            try {
                //reader = Resources.getResourceAsReader(resource);
                //logger.info("path====" + this.getClass().getResourceAsStream(resource).toString());
                confInputStream = SessionFactory.class.getResourceAsStream(resource);
                factory = new SqlSessionFactoryBuilder().build(confInputStream);
            } catch (Exception e) {
                logger.error("init /resources/mybatis/conf/mybatis-conf.xml error: " + e.getMessage(), e);
            }

            instance = new SessionFactory();
        }
        return instance;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值