Example usage for org.apache.ibatis.session SqlSessionFactory openSession

List of usage examples for org.apache.ibatis.session SqlSessionFactory openSession

Introduction

In this page you can find the example usage for org.apache.ibatis.session SqlSessionFactory openSession.

Prototype

SqlSession openSession(ExecutorType execType);

Source Link

Usage

From source file:com.baomidou.mybatisplus.test.activerecord.ActiveRecordTest.java

License:Apache License

public static void main(String[] args) {
    // ?/*from   www . j  a  v a2 s. co m*/
    InputStream in = TestMapper.class.getClassLoader().getResourceAsStream("mysql-config.xml");
    MybatisSessionFactoryBuilder mf = new MybatisSessionFactoryBuilder();
    SqlSessionFactory sqlSessionFactory = mf.build(in);
    TableInfoHelper.initSqlSessionFactory(sqlSessionFactory);
    sqlSessionFactory.openSession(false);
    // ??
    Test t1 = new Test();
    t1.setType("test10");
    boolean rlt = t1.insert();
    print(" ar save=" + rlt + ", id=" + t1.getId());

    // ?ID
    t1.setType("t1023");
    rlt = t1.updateById();
    print(" ar updateById:" + rlt);

    //  SQL
    Test t11 = new Test();
    t11.setType("123");
    rlt = t11.update("id={0}", t1.getId());
    print("update sql=" + rlt);

    //  SQL
    Test t10 = t1.selectOne("id={0}", t1.getId());
    print("selectOne=" + t10.getType());

    // ?OR
    t1.setType("t1021");
    rlt = t1.insertOrUpdate();
    print(" ar saveOrUpdate:" + rlt);

    // ?ID
    Test t2 = t1.selectById();
    print(" t2 = " + t2.toString());
    t2.setId(IdWorker.getId());
    t2.insert();

    // 
    List<Test> tl = t2.selectAll();
    for (Test t : tl) {
        print("selectAll=" + t.toString());
    }

    // 
    print(" count=" + t2.selectCount(null));

    // 
    Page<Test> page = new Page<>(0, 10);
    page = t2.selectPage(page, null);
    print(page.toString());

    // ?ID
    rlt = t2.deleteById();
    print("deleteById=" + rlt + ", id=" + t2.getId());

    //  SQL 
    List<Map<String, Object>> ul = t2.sql().selectList(new SQL() {
        {
            SELECT("*");
            FROM("test");
            WHERE("type='t1021'");
        }
    }.toString());
    System.err.println("selectList SQL:");
    for (Map<String, Object> map : ul) {
        System.err.println(map);
    }

    // ?ID
    Test t20 = t2.selectById();
    print("t2 ??" + (null != t20));

    //  SQL
    rlt = t2.delete("type={0}", "t1021");
    System.err.println("delete sql=" + rlt);
}

From source file:com.baomidou.mybatisplus.test.GlobalConfigurationTest.java

License:Apache License

/**
 * ?//from  w w  w . j a  v a  2 s. c o  m
 */
@SuppressWarnings("unchecked")
public static void main(String[] args) {
    GlobalConfiguration global = GlobalConfiguration.defaults();
    global.setAutoSetDbType(true);
    // FieldStrategy.Empty
    global.setFieldStrategy(2);
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/mybatis-plus?characterEncoding=UTF-8");
    dataSource.setUsername("root");
    dataSource.setPassword("521");
    dataSource.setMaxTotal(1000);
    GlobalConfiguration.setMetaData(dataSource, global);
    // ?
    InputStream inputStream = GlobalConfigurationTest.class.getClassLoader()
            .getResourceAsStream("mysql-config.xml");
    MybatisSessionFactoryBuilder factoryBuilder = new MybatisSessionFactoryBuilder();
    factoryBuilder.setGlobalConfig(global);
    SqlSessionFactory sessionFactory = factoryBuilder.build(inputStream);
    SqlSession session = sessionFactory.openSession(false);
    TestMapper testMapper = session.getMapper(TestMapper.class);
    /*Wrapper type = Condition.instance().eq("id",1).or().in("type", new Object[]{1, 2, 3, 4, 5, 6});
    List list = testMapper.selectList(type);
    System.out.println(list.toString());*/
    Test test = new Test();
    test.setCreateTime(new Date());
    // ?
    test.setType("");
    testMapper.insert(test);

    SqlSession sqlSession = sessionFactory.openSession(false);
    NotPKMapper pkMapper = sqlSession.getMapper(NotPKMapper.class);
    NotPK notPK = new NotPK();
    notPK.setUuid(UUID.randomUUID().toString());
    int num = pkMapper.insert(notPK);
    Assert.assertTrue(num > 0);
    NotPK notPK1 = pkMapper.selectOne(notPK);
    Assert.assertNotNull(notPK1);
    pkMapper.selectPage(RowBounds.DEFAULT, Condition.create().eq("type", 12121212));
    NotPK notPK2 = null;
    try {
        notPK2 = pkMapper.selectById("1");
    } catch (Exception e) {
        System.out.println(",");
    }
    Assert.assertNull(notPK2);
    int count = pkMapper.selectCount(Condition.EMPTY);
    Assert.assertTrue(count > 0);
    int deleteCount = pkMapper.delete(null);
    Assert.assertTrue(deleteCount > 0);
    session.rollback();
    sqlSession.commit();
}

From source file:com.glaf.core.test.MyBatisSessionFactoryTest.java

License:Apache License

public static void main(String[] args) {
    long start = System.currentTimeMillis();
    SqlSessionFactory sqlSessionFactory = MyBatisSessionFactory.getSessionFactory();
    SqlSession session = null;//from   www.j  a  v a 2s .  c  o m
    Connection conn = null;
    try {
        conn = DBConnectionFactory.getConnection();
        session = sqlSessionFactory.openSession(conn);
        SystemParam m = session.selectOne("getSystemParamById", "sys_table");
        System.out.println(m.toJsonObject().toJSONString());
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (session != null) {
            session.close();
        }
        JdbcUtils.close(conn);
    }
    long time = System.currentTimeMillis() - start;
    System.out.println("" + (time));

    for (int i = 0; i < 20; i++) {
        start = System.currentTimeMillis();
        session = null;
        conn = null;
        try {
            conn = DBConnectionFactory.getConnection("yz");
            session = sqlSessionFactory.openSession(conn);
            SystemParam m = session.selectOne("getSystemParamById", "sys_table");
            System.out.println(m.toJsonObject().toJSONString());
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (session != null) {
                session.close();
            }
            JdbcUtils.close(conn);
        }
        time = System.currentTimeMillis() - start;
        System.out.println("" + (time));
    }
}

From source file:com.itfsw.mybatis.generator.plugins.tools.MyBatisGeneratorTool.java

License:Apache License

/**
 * ?SqlSession//from w ww .  ja v a2s  .c  om
 * @return
 * @throws IOException
 */
public SqlSession getSqlSession() throws IOException, ClassNotFoundException {
    org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration();
    config.setCallSettersOnNulls(true); // nullsetter
    config.setMapUnderscoreToCamelCase(true); // ???

    // mapper
    config.addMappers(targetPackage);
    // ??
    PooledDataSourceFactory dataSourceFactory = new PooledDataSourceFactory();
    dataSourceFactory.setProperties(DBHelper.properties);
    DataSource dataSource = dataSourceFactory.getDataSource();
    JdbcTransactionFactory transactionFactory = new JdbcTransactionFactory();

    Environment environment = new Environment("test", transactionFactory, dataSource);
    config.setEnvironment(environment);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(config);
    return sqlSessionFactory.openSession(true);
}

From source file:com.luxoft.mybatis.splitter.UpdateSplitterPluginTest.java

License:Apache License

public void splitterTest(ExecutorType execType) throws IOException, SQLException {
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
            .build(Resources.getResourceAsStream("configuration.xml"));
    SqlSession sqlSession = sqlSessionFactory.openSession(execType);
    sqlSession.insert("makeTable");
    sqlSession.flushStatements();//  w w  w .j ava  2 s.co  m
    doInsert(sqlSession);
    Assert.assertEquals(Arrays.asList("first", "second", "third"), sqlSession.selectList("get"));
    sqlSession.insert("dropTable");
    sqlSession.flushStatements();
    sqlSession.close();
}

From source file:com.mybatisX.test.activerecord.ActiveRecordTest.java

License:Apache License

public static void main(String[] args) {
    // ?//from w w w .ja v a 2 s.c  o  m
    InputStream in = TestMapper.class.getClassLoader().getResourceAsStream("mysql-config.xml");
    MybatisSessionFactoryBuilder mf = new MybatisSessionFactoryBuilder();
    SqlSessionFactory sqlSessionFactory = mf.build(in);
    TableInfoHelper.initSqlSessionFactory(sqlSessionFactory);
    sqlSessionFactory.openSession(false);
    // ??
    Test t1 = new Test();
    t1.setType("test10");
    boolean rlt = t1.insert();
    print(" ar save=" + rlt + ", id=" + t1.getId());

    // ?ID
    t1.setType("t1023");
    rlt = t1.updateById();
    print(" ar updateById:" + rlt);

    //  SQL
    Test t11 = new Test();
    t11.setType("123");
    rlt = t11.update("id={0}", t1.getId());
    print("update sql=" + rlt);

    //  SQL
    Test t10 = t1.selectOne("id={0}", t1.getId());
    print("selectOne=" + t10.getType());

    // ?OR
    t1.setType("t1021");
    rlt = t1.insertOrUpdate();
    print(" ar saveOrUpdate:" + rlt);

    // ?ID
    Test t2 = t1.selectById();
    print(" t2 = " + t2.toString());
    t2.setId(IdWorker.getId());
    t2.insert();

    // 
    List<Test> tl = t2.selectAll();
    for (Test t : tl) {
        print("selectAll=" + t.toString());
    }

    // 
    print(" count=" + t2.selectCount());

    // 
    Page<Test> page = new Page<Test>(0, 10);
    page = t2.selectPage(page, null);
    print(page.toString());

    // ?ID
    rlt = t2.deleteById();
    print("deleteById=" + rlt + ", id=" + t2.getId());

    //  SQL 
    List<Map<String, Object>> ul = t2.selectListSql(new SQL() {
        {
            SELECT("*");
            FROM("test");
            WHERE("type='t1021'");
        }
    }.toString());
    System.err.println("selectList SQL:");
    for (Map<String, Object> map : ul) {
        System.err.println(map);
    }

    // ?ID
    Test t20 = t2.selectById();
    print("t2 ??" + (null != t20));

    //  SQL
    rlt = t2.delete("type={0}", "t1021");
    System.err.println("delete sql=" + rlt);
}

From source file:com.raycloud.cobarclient.mybatis.spring.SqlSessionUtils.java

License:Apache License

/**
 * Gets an SqlSession from Spring Transaction Manager or creates a new one if needed.
 * Tries to get a SqlSession out of current transaction. If there is not any, it creates a new one.
 * Then, it synchronizes the SqlSession with the transaction if Spring TX is active and
 * <code>SpringManagedTransactionFactory</code> is configured as a transaction manager.
 *
 * @param sessionFactory      a MyBatis {@code SqlSessionFactory} to create new sessions
 * @param executorType        The executor type of the SqlSession to create
 * @param exceptionTranslator Optional. Translates SqlSession.commit() exceptions to Spring exceptions.
 * @throws TransientDataAccessResourceException if a transaction is active and the
 *                                              {@code SqlSessionFactory} is not using a {@code SpringManagedTransactionFactory}
 * @see SpringManagedTransactionFactory/* ww  w  . j  a  v  a2 s.  co m*/
 */
public static SqlSession getSqlSession(SqlSessionFactory sessionFactory, ExecutorType executorType,
        PersistenceExceptionTranslator exceptionTranslator) {

    notNull(sessionFactory, "No SqlSessionFactory specified");
    notNull(executorType, "No ExecutorType specified");

    SqlSessionHolder holder = (SqlSessionHolder) getResource(sessionFactory);

    if (holder != null && holder.isSynchronizedWithTransaction()) {
        if (holder.getExecutorType() != executorType) {
            throw new TransientDataAccessResourceException(
                    "Cannot change the ExecutorType when there is an existing transaction");
        }

        holder.requested();

        if (logger.isDebugEnabled()) {
            logger.debug("Fetched SqlSession [" + holder.getSqlSession() + "] from current transaction");
        }

        return holder.getSqlSession();
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Creating a new SqlSession");
    }

    SqlSession session = sessionFactory.openSession(executorType);

    // Register session holder if synchronization is active (i.e. a Spring TX is active)
    //
    // Note: The DataSource used by the Environment should be synchronized with the
    // transaction either through DataSourceTxMgr or another tx synchronization.
    // Further assume that if an exception is thrown, whatever started the transaction will
    // handle closing / rolling back the Connection associated with the SqlSession.
    if (isSynchronizationActive()) {
        Environment environment = sessionFactory.getConfiguration().getEnvironment();

        if (environment.getTransactionFactory() instanceof SpringManagedTransactionFactory) {
            if (logger.isDebugEnabled()) {
                logger.debug("Registering transaction synchronization for SqlSession [" + session + "]");
            }

            holder = new SqlSessionHolder(session, executorType, exceptionTranslator);
            bindResource(sessionFactory, holder);
            registerSynchronization(new SqlSessionSynchronization(holder, sessionFactory));
            holder.setSynchronizedWithTransaction(true);
            holder.requested();
        } else {
            if (getResource(environment.getDataSource()) == null) {
                if (logger.isDebugEnabled()) {
                    logger.debug("SqlSession [" + session
                            + "] was not registered for synchronization because DataSource is not transactional");
                }
            } else {
                throw new TransientDataAccessResourceException(
                        "SqlSessionFactory must be using a SpringManagedTransactionFactory in order to use Spring transaction synchronization");
            }
        }
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("SqlSession [" + session
                    + "] was not registered for synchronization because synchronization is not active");
        }
    }

    return session;
}

From source file:griffon.plugins.mybatis.AbstractMybatisProvider.java

License:Apache License

public <R> R withSqlSession(String sessionFactoryName, Closure<R> closure) {
    if (isBlank(sessionFactoryName))
        sessionFactoryName = DEFAULT;/*w  w  w.  j  a v  a2  s  . co m*/
    if (closure != null) {
        SqlSessionFactory sf = getSessionFactory(sessionFactoryName);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Executing SQL stament on sqlSession '" + sessionFactoryName + "'");
        }
        SqlSession session = sf.openSession(true);
        try {
            return closure.call(sessionFactoryName, session);
        } finally {
            session.close();
        }
    }
    return null;
}

From source file:griffon.plugins.mybatis.AbstractMybatisProvider.java

License:Apache License

public <R> R withSqlSession(String sessionFactoryName, CallableWithArgs<R> callable) {
    if (isBlank(sessionFactoryName))
        sessionFactoryName = DEFAULT;//from  w w  w. j a  v  a 2s .c o  m
    if (callable != null) {
        SqlSessionFactory sf = getSessionFactory(sessionFactoryName);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Executing SQL stament on sqlSession '" + sessionFactoryName + "'");
        }
        SqlSession session = sf.openSession(true);
        try {
            callable.setArgs(new Object[] { sessionFactoryName, session });
            return callable.call();
        } finally {
            session.close();
        }
    }
    return null;
}

From source file:io.soabase.example.MockDatabase.java

License:Apache License

@SuppressWarnings("ParameterCanBeLocal")
public static void main(String[] args) throws Exception {
    if (!Boolean.getBoolean("debug")) {
        OutputStream nullOut = new OutputStream() {
            @Override/* w w w  . j  ava  2s. c  om*/
            public void write(int b) throws IOException {
            }
        };
        System.setOut(new PrintStream(nullOut));
    }

    args = new String[] { "--database.0", "mem:test", "--dbname.0", "xdb", "--port", "10064" };
    Server.main(args);

    SqlSession session;
    try (InputStream stream = Resources.getResource("example-mybatis.xml").openStream()) {
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
        Configuration mybatisConfiguration = sqlSessionFactory.getConfiguration();
        mybatisConfiguration.addMapper(AttributeEntityMapper.class);
        session = sqlSessionFactory.openSession(true);
    }

    AttributeEntityMapper mapper = session.getMapper(AttributeEntityMapper.class);
    mapper.createTable();

    mapper.insert(new AttributeEntity("test", "global"));
    mapper.insert(new AttributeEntity("test2", "hello", "one"));
    mapper.insert(new AttributeEntity("test2", "goodbye", "two"));

    List<AttributeEntity> attributeEntities = mapper.selectAll();
    System.out.println(attributeEntities);

    System.out.println("Running...");
    Thread.currentThread().join();
}