Example usage for org.apache.ibatis.session SqlSession close

List of usage examples for org.apache.ibatis.session SqlSession close

Introduction

In this page you can find the example usage for org.apache.ibatis.session SqlSession close.

Prototype

@Override
void close();

Source Link

Document

Closes the session.

Usage

From source file:action.reviseProfile.java

public String getInfo() throws IOException {
    String resource = "orm/configuration.xml";
    Reader reader = Resources.getResourceAsReader(resource);
    SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
    SqlSession session = sessionFactory.openSession();
    try {/*from  w  w  w  . j a v  a2s .  c o m*/
        email = ActionContext.getContext().getSession().get("email").toString();
        userlist = session.selectList("selectuserbyemail", email);
        name = userlist.get(0).getName();
        sex = userlist.get(0).getSex();
        dob = userlist.get(0).getDob();
        driverlicense = userlist.get(0).getDriverlicense();
        return SUCCESS;
    } finally {
        session.close();
    }
}

From source file:adl.RecordActivitySpeechlet.java

License:Open Source License

public void writeAction(String intent) {

    SqlSession session = null;
    try {/* w w w  .  ja  v  a  2s  .  c o m*/
        session = SqlSessionHelper.getSessionFactory().openSession();
        ActionMapper mapper = session.getMapper(ActionMapper.class);

        ActionBean actionBean = new ActionBean();
        actionBean.setName(camelToUtterance(intent));//+
        actionBean.setTime(new Timestamp(System.currentTimeMillis()));
        mapper.addActionBean(actionBean);

        session.commit();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        session.close();
    }
}

From source file:cern.c2mon.server.history.dao.LoggerDAO.java

License:Open Source License

/**
 * Inserts into the database a set of rows containing the data coming in
 * several IFallback objects//from   www  .  ja v a2 s . co m
 *
 * @param data
 *          List of IFallback object whose data has to be inserted in the DB
 * @throws IDBPersistenceException
 *           An exception is thrown in case an error occurs during the data
 *           insertion. The exception provides also the number of already
 *           committed objects
 */
@SuppressWarnings("unchecked")
// add generics to persistence manager
public final void storeData(final List data) throws IDBPersistenceException {
    SqlSession session = null;
    int size = data.size();
    int commited = 0;
    T tag;

    try {
        // We use batch set of statements to improve performance
        session = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Obtained batch transacted SQL session (session: " + session.toString() + ")");
        }
        LoggerMapper<T> persistenceMapper = session.getMapper(mapperInterface);

        // Iterate through the list of DataTagCacheObjects to insert
        // them one by one
        for (int i = 0; i != size; i++) {
            if ((0 == i % RECORDS_PER_BATCH) && i > 0) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("storeData([Collection]) : Commiting rows for i=" + i);
                }
                session.commit();
                commited = i;
            }

            if (data.get(i) != null) {
                tag = (T) data.get(i);
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Logging object with ID: " + tag.getId());
                }
                persistenceMapper.insertLog(tag);
            }
        }
        // Commit the transaction
        session.commit();
        commited = size;
    } catch (PersistenceException e) {
        LOGGER.error("storeData([Collection]) : Error executing/closing prepared statement for " + data.size()
                + " dataTags", e);
        try {
            if (session != null) {
                session.rollback();
            }
        } catch (Exception sql) {
            LOGGER.error("storeData([Collection]) : Error rolling back transaction.", sql);
        }
        throw new IDBPersistenceException(e.getMessage(), commited);
    } finally {
        try {
            if (session != null) {
                session.close();
            }
        } catch (Exception e) {
            LOGGER.error("storeData([Collection]) : Error closing session.", e);
        }
    }
}

From source file:cern.c2mon.server.history.dao.LoggerDAO.java

License:Open Source License

@Override
public void storeData(IFallback object) throws IDBPersistenceException {
    SqlSession session = null;
    try {//ww  w.  j  ava 2 s .com
        session = sqlSessionFactory.openSession();
        LoggerMapper<T> loggerMapper = session.getMapper(mapperInterface);
        loggerMapper.insertLog((T) object);
        session.commit();
    } catch (PersistenceException ex1) {
        String message = "Exception caught while persisting an object to the history";
        LOGGER.error(message, ex1);
        if (session != null)
            session.rollback();
        throw new IDBPersistenceException(message, ex1);
    } finally {
        if (session != null)
            session.close();
    }
}

From source file:cl.beans.ContactoBean.java

public String guardar() {
    //Asignar un id por defecto
    contacto.setId(-1);// si es -1 es autoincrementable
    SqlSession session = new MyBatisUtil().getSession();
    if (session != null) {
        try {//from   ww w .  j a  va  2  s . c  o  m
            session.insert("Contacto.guardarContacto", contacto); //el nombre del namespace
            session.commit();
        } finally {
            session.close();
        }
    } else {
        System.out.println("Error");
    }
    FacesContext.getCurrentInstance().addMessage(null,
            new FacesMessage(FacesMessage.SEVERITY_INFO, "Aviso", "Contacto Creado"));
    return "index";
}

From source file:cl.beans.ContactoBean.java

public List<Contacto> getContactos() {
    List<Contacto> lista = null;
    SqlSession session = new MyBatisUtil().getSession();
    if (session != null) {
        try {/*from   w w  w.j  a  v  a2  s .c  om*/
            lista = session.selectList("Contacto.obtenerContactos"); //el nombre del namespace

        } finally {
            session.close();
        }
    } else {
        System.out.println("Error");
    }
    return lista;
}

From source file:cn.com.git.udmp.test.mybatis.cursor.UdmpCursorSimpleTest.java

License:Apache License

@BeforeClass
public static void setUp() throws Exception {
    // create a SqlSessionFactory
    Reader reader = Resources.getResourceAsReader("cn/com/git/udmp/test/mybatis/cursor/mybatis-config.xml");
    sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
    reader.close();//  ww  w .j a  v a  2  s.co m

    // populate in-memory database
    SqlSession session = sqlSessionFactory.openSession();
    Connection conn = session.getConnection();
    reader.close();
    session.close();
}

From source file:cn.com.git.udmp.test.mybatis.cursor.UdmpCursorSimpleTest.java

License:Apache License

@Test
public void shouldGetAllUser() {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    BatchTestSouceMapper mapper = sqlSession.getMapper(BatchTestSouceMapper.class);
    Cursor<BatchTestSouce> usersCursor = mapper.findListByCursor();
    try {//  w ww. jav  a 2  s.c  o  m
        Assert.assertFalse(usersCursor.isOpen());

        // Cursor is just created, current index is -1
        Assert.assertEquals(-1, usersCursor.getCurrentIndex());

        Iterator<BatchTestSouce> iterator = usersCursor.iterator();

        // Check if hasNext, fetching is started
        Assert.assertTrue(iterator.hasNext());
        Assert.assertTrue(usersCursor.isOpen());
        Assert.assertFalse(usersCursor.isConsumed());

        // next() has not been called, index is still -1
        Assert.assertEquals(-1, usersCursor.getCurrentIndex());

        BatchTestSouce user = iterator.next();
        //            Assert.assertEquals("User1", user.getVcharC());
        System.out.println(user.getVcharC());
        Assert.assertEquals(0, usersCursor.getCurrentIndex());

        user = iterator.next();
        System.out.println(user.getVcharC());
        //            Assert.assertEquals("User2", user.getVcharC());
        Assert.assertEquals(1, usersCursor.getCurrentIndex());

        user = iterator.next();
        System.out.println(user.getVcharC());
        //            Assert.assertEquals("User3", user.getVcharC());
        Assert.assertEquals(2, usersCursor.getCurrentIndex());

        user = iterator.next();
        System.out.println(user.getVcharC());
        //            Assert.assertEquals("User4", user.getVcharC());
        Assert.assertEquals(3, usersCursor.getCurrentIndex());

        user = iterator.next();
        System.out.println(user.getVcharC());
        //            Assert.assertEquals("User5", user.getVcharC());
        Assert.assertEquals(4, usersCursor.getCurrentIndex());

        // Check no more elements
        Assert.assertFalse(iterator.hasNext());
        Assert.assertFalse(usersCursor.isOpen());
        Assert.assertTrue(usersCursor.isConsumed());
    } finally {
        sqlSession.close();
    }
}

From source file:cn.cuizuoli.appranking.service.AppRankingService.java

License:Apache License

/**
 * batchAdd//w w w .  ja  v a 2 s  .c o  m
 * @param appRankingList
 */
@Transactional
public void batchAdd(List<AppRanking> appRankingList) {
    SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
    AppRankingRepository batchAppRankingRepository = sqlSession.getMapper(AppRankingRepository.class);
    int i = 1;
    for (AppRanking appRanking : appRankingList) {
        appRanking.setId(appRankingIncrementer.nextStringValue());
        appRanking.setDateHour(DateTime.now().toString("yyyyMMddHH"));
        batchAppRankingRepository.insert(appRanking);
        if (i % 100 == 0) {
            sqlSession.commit();
        }
        i++;
    }
    sqlSession.commit();
    sqlSession.close();
}

From source file:com.albertzhe.mybatis_helloworld.mapper.impl.AdminMapperImpl.java

public Admin getAdminByID(Long id) {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    Admin admin = null;// ww w.j a  v a2s . c om

    try {
        admin = sqlSession.selectOne("com.albertzhe.mybatis_helloworld.mapper.AdminMapper.getAdminByID", id);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        sqlSession.close();
    }

    return admin;
}