org.hibernate.jdbc.Work Java Examples
The following examples show how to use
org.hibernate.jdbc.Work.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Hibernate4Access.java From snakerflow with Apache License 2.0 | 6 votes |
public void runScript() { getSession().doWork(new Work() { public void execute(Connection conn) throws SQLException { if(JdbcHelper.isExec(conn)) { return; } try { String databaseType = JdbcHelper.getDatabaseType(conn); String schema = "db/core/schema-" + databaseType + ".sql"; ScriptRunner runner = new ScriptRunner(conn, true); runner.runScript(schema); } catch (Exception e) { throw new SnakerException(e); } } }); }
Example #2
Source File: DatabaseQueryServlet.java From document-management-system with GNU General Public License v2.0 | 6 votes |
/** * List tables from database */ private List<String> listTables(Session session) { final List<String> tables = new ArrayList<String>(); final String[] tableTypes = {"TABLE"}; final String[] tablePatterns = new String[]{"JBPM_%", "OKM_%", "DEFAULT_%", "VERSION_%", "jbpm_%", "okm_%", "default_%", "version_%"}; session.doWork(new Work() { @Override public void execute(Connection con) throws SQLException { DatabaseMetaData md = con.getMetaData(); for (String table : tablePatterns) { ResultSet rs = md.getTables(null, null, table, tableTypes); while (rs.next()) { tables.add(rs.getString(3)); } rs.close(); } } }); return tables; }
Example #3
Source File: TransactionIsolationDriverConnectionProviderTest.java From hibernate-master-class with Apache License 2.0 | 6 votes |
@Test public void test() { Session session = null; Transaction txn = null; try { session = getSessionFactory().openSession(); txn = session.beginTransaction(); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { LOGGER.debug("Transaction isolation level is {}", Environment.isolationLevelToString(connection.getTransactionIsolation())); } }); txn.commit(); } catch (RuntimeException e) { if ( txn != null && txn.isActive() ) txn.rollback(); throw e; } finally { if (session != null) { session.close(); } } }
Example #4
Source File: HibernateExtendedJpaDialect.java From bamboobsc with Apache License 2.0 | 6 votes |
@Override public Object beginTransaction(final EntityManager entityManager, final TransactionDefinition definition) throws PersistenceException, SQLException, TransactionException { Session session = (Session) entityManager.getDelegate(); if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) { getSession(entityManager).getTransaction().setTimeout(definition.getTimeout()); } entityManager.getTransaction().begin(); logger.debug("Transaction started"); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { logger.debug("The connection instance is " + connection.toString()); logger.debug("The isolation level of the connection is " + connection.getTransactionIsolation() + " and the isolation level set on the transaction is " + definition.getIsolationLevel() ); DataSourceUtils.prepareConnectionForTransaction(connection, definition); } }); return prepareTransaction(entityManager, definition.isReadOnly(), definition.getName()); }
Example #5
Source File: HibernateDao.java From opencron with Apache License 2.0 | 6 votes |
@Transactional(readOnly = false) public void executeBatch(final String sql, final Object[]... parameters) { getSession().doWork(new Work() { public void execute(Connection connection) throws SQLException { connection.setAutoCommit(false); PreparedStatement stmt = connection.prepareStatement(sql); for (Object[] arr : parameters) { int i = 1; for (Object p : arr) { stmt.setObject(i++, p); } stmt.addBatch(); } stmt.executeBatch(); connection.commit(); } }); }
Example #6
Source File: TransactionIsolationExternalDataSourceExternalconfgiurationConnectionProviderTest.java From hibernate-master-class with Apache License 2.0 | 6 votes |
@Test public void test() { Session session = null; Transaction txn = null; try { session = getSessionFactory().openSession(); txn = session.beginTransaction(); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { LOGGER.debug("Transaction isolation level is {}", Environment.isolationLevelToString(connection.getTransactionIsolation())); } }); txn.commit(); } catch (RuntimeException e) { if ( txn != null && txn.isActive() ) txn.rollback(); throw e; } finally { if (session != null) { session.close(); } } }
Example #7
Source File: AbstractPooledSequenceIdentifierTest.java From hibernate-master-class with Apache License 2.0 | 6 votes |
private void insertNewRow(Session session) { session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { Statement statement = null; try { statement = connection.createStatement(); statement.executeUpdate("INSERT INTO sequenceIdentifier VALUES NEXT VALUE FOR hibernate_sequence"); } finally { if (statement != null) { statement.close(); } } } }); }
Example #8
Source File: TestHibernateTypes.java From jasypt with Apache License 2.0 | 6 votes |
/** * Create db structure */ private void initDB() { Transaction transaction = session.beginTransaction(); session.doWork(new Work() { public void execute(Connection connection) throws SQLException { connection.createStatement().execute( "CREATE MEMORY TABLE PUBLIC.USER(" + "NAME VARCHAR(100)," + "LOGIN VARCHAR(100) PRIMARY KEY," + "PASSWORD VARCHAR(100)," + "BIRTHDATE VARCHAR(100)," + "DOCUMENT BLOB);"); } }); transaction.commit(); }
Example #9
Source File: TestHibernateTypes.java From jasypt with Apache License 2.0 | 6 votes |
/** * Create db structure */ private void initDB() { Transaction transaction = session.beginTransaction(); session.doWork(new Work() { public void execute(Connection connection) throws SQLException { connection.createStatement().execute( "CREATE MEMORY TABLE PUBLIC.USER(" + "NAME VARCHAR(100)," + "LOGIN VARCHAR(100) PRIMARY KEY," + "PASSWORD VARCHAR(100)," + "BIRTHDATE VARCHAR(100)," + "DOCUMENT BLOB," + "CODE NUMERIC, " + "CODE2 NUMERIC);"); } }); transaction.commit(); }
Example #10
Source File: TransactionIsolationExternalDataSourceConnectionProviderTest.java From hibernate-master-class with Apache License 2.0 | 6 votes |
@Test public void test() { Session session = null; Transaction txn = null; try { session = getSessionFactory().openSession(); txn = session.beginTransaction(); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { LOGGER.debug("Transaction isolation level is {}", Environment.isolationLevelToString(connection.getTransactionIsolation())); } }); txn.commit(); } catch (RuntimeException e) { if ( txn != null && txn.isActive() ) txn.rollback(); throw e; } finally { if (session != null) { session.close(); } } }
Example #11
Source File: MetadataController.java From youkefu with Apache License 2.0 | 6 votes |
@RequestMapping("/imptb") @Menu(type = "admin" , subtype = "metadata" , admin = true) public ModelAndView imptb(final ModelMap map , HttpServletRequest request) throws Exception { this.search(map, request); Session session = (Session) em.getDelegate(); session.doWork(new Work() { public void execute(Connection connection) throws SQLException { try { map.addAttribute("tablesList", DatabaseMetaDataHandler.getTables(connection)); } catch (Exception e) { e.printStackTrace(); }finally{ connection.close(); } } }); return request(super .createRequestPageTempletResponse("/admin/system/metadata/tablelist")); }
Example #12
Source File: TransactionIsolationInternalC3P0ConnectionProviderTest.java From hibernate-master-class with Apache License 2.0 | 6 votes |
@Test public void test() { Session session = null; Transaction txn = null; try { session = getSessionFactory().openSession(); txn = session.beginTransaction(); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { LOGGER.debug("Transaction isolation level is {}", Environment.isolationLevelToString(connection.getTransactionIsolation())); } }); txn.commit(); } catch (RuntimeException e) { if ( txn != null && txn.isActive() ) txn.rollback(); throw e; } finally { if (session != null) { session.close(); } } }
Example #13
Source File: OracleJsonBinaryTypeTest.java From hibernate-types with Apache License 2.0 | 5 votes |
@Override protected void afterInit() { doInJPA(new JPATransactionFunction<Void>() { @Override public Void apply(EntityManager entityManager) { entityManager.unwrap(Session.class).doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { Statement statement = null; try { statement = connection.createStatement(); statement.executeUpdate( "ALTER TABLE event MOVE LOB (location) STORE AS (CACHE)" ); statement.executeUpdate( "ALTER TABLE participant MOVE LOB (ticket, metadata) STORE AS (CACHE)" ); } finally { if(statement != null) { statement.close(); } } } }); return null; } }); }
Example #14
Source File: DefaultSequenceHandlerRepository.java From pnc with Apache License 2.0 | 5 votes |
@Override public void dropSequence(final String sequenceName) { Work work = new Work() { @Override public void execute(Connection connection) throws SQLException { DialectResolver dialectResolver = new StandardDialectResolver(); Dialect dialect = dialectResolver.resolveDialect(getResolutionInfo(connection)); PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { preparedStatement = connection.prepareStatement(dialect.getDropSequenceStrings(sequenceName)[0]); preparedStatement.execute(); } catch (SQLException e) { throw e; } finally { if (preparedStatement != null) { preparedStatement.close(); } if (resultSet != null) { resultSet.close(); } } } }; Session session = (Session) entityManager.getDelegate(); SessionFactory sessionFactory = session.getSessionFactory(); sessionFactory.getCurrentSession().doWork(work); }
Example #15
Source File: DefaultSequenceHandlerRepository.java From pnc with Apache License 2.0 | 5 votes |
@Override public void createSequence(final String sequenceName) { if (sequenceExists(sequenceName)) { return; } Work work = new Work() { @Override public void execute(Connection connection) throws SQLException { DialectResolver dialectResolver = new StandardDialectResolver(); Dialect dialect = dialectResolver.resolveDialect(getResolutionInfo(connection)); PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { preparedStatement = connection .prepareStatement(dialect.getCreateSequenceStrings(sequenceName, 1, 1)[0]); preparedStatement.execute(); } catch (SQLException e) { throw e; } finally { if (preparedStatement != null) { preparedStatement.close(); } if (resultSet != null) { resultSet.close(); } } } }; Session session = (Session) entityManager.getDelegate(); SessionFactory sessionFactory = session.getSessionFactory(); sessionFactory.getCurrentSession().doWork(work); }
Example #16
Source File: BaseHibernateDao.java From framework with Apache License 2.0 | 5 votes |
/** * Description: <br> * * @author 王伟<br> * @taskId <br> * @param sql * @param objcts * @param commitNumber * @throws DaoException <br> */ @Override public <T> void batchExecute(final String sql, final Collection<Object[]> objcts, final int commitNumber) throws DaoException { Session session = getSession(); session.flush(); session.doWork(new Work() { @Override public void execute(final Connection connection) throws SQLException { PreparedStatement stmt = null; try { stmt = connection.prepareStatement(sql); connection.setAutoCommit(false); int i = 0; for (Object[] object : objcts) { i++; for (int j = 0; j < object.length; j++) { stmt.setObject(j + 1, object[j]); } stmt.addBatch(); if (i % commitNumber == 0) { stmt.executeBatch(); connection.commit(); } } stmt.executeBatch(); connection.commit(); } finally { if (stmt != null) { stmt.close(); } } } }); }
Example #17
Source File: ReportUtils.java From document-management-system with GNU General Public License v2.0 | 5 votes |
/** * Execute report */ private static void executeDatabase(Session dbSession, final ByteArrayOutputStream baos, final JasperReport jr, final Map<String, Object> params, final int format) { dbSession.doWork(new Work() { @Override public void execute(Connection con) throws SQLException { try { ReportUtils.generateReport(baos, jr, params, format, con); } catch (JRException e) { throw new SQLException(e.getMessage(), e); } } }); }
Example #18
Source File: CustomHibernateJpaDialect.java From spring-boot with Apache License 2.0 | 5 votes |
@Override public Object beginTransaction(final EntityManager entityManager, final TransactionDefinition definition) throws PersistenceException, SQLException, TransactionException { Session session = (Session) entityManager.getDelegate(); if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) { getSession(entityManager).getTransaction().setTimeout( definition.getTimeout()); } final TransactionData data = new TransactionData(); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { Integer previousIsolationLevel = DataSourceUtils .prepareConnectionForTransaction(connection, definition); data.setPreviousIsolationLevel(previousIsolationLevel); data.setConnection(connection); } }); entityManager.getTransaction().begin(); Object springTransactionData = prepareTransaction(entityManager, definition.isReadOnly(), definition.getName()); data.setSpringTransactionData(springTransactionData); return data; }
Example #19
Source File: PostgreSQLInetTypeTest.java From hibernate-types with Apache License 2.0 | 5 votes |
@Test public void testJDBCQuery() { doInJPA(new JPATransactionFunction<Void>() { @Override public Void apply(EntityManager entityManager) { Session session = entityManager.unwrap(Session.class); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { PreparedStatement ps = null; try { ps = connection.prepareStatement( "SELECT * " + "FROM Event e " + "WHERE " + " e.ip && ?::inet = true" ); ps.setObject(1, "192.168.0.1/24"); ResultSet rs = ps.executeQuery(); while(rs.next()) { Long id = rs.getLong(1); String ip = rs.getString(2); assertEquals("192.168.0.123/24", ip); } } finally { if (ps != null) { ps.close(); } } } }); return null; } }); }
Example #20
Source File: PostgreSQLInetTypeTest.java From hibernate-types with Apache License 2.0 | 5 votes |
@Test public void testJDBCQuery() { doInJPA(new JPATransactionFunction<Void>() { @Override public Void apply(EntityManager entityManager) { Session session = entityManager.unwrap(Session.class); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { PreparedStatement ps = null; try { ps = connection.prepareStatement( "SELECT * " + "FROM Event e " + "WHERE " + " e.ip && ?::inet = true" ); ps.setObject(1, "192.168.0.1/24"); ResultSet rs = ps.executeQuery(); while(rs.next()) { Long id = rs.getLong(1); String ip = rs.getString(2); assertEquals("192.168.0.123/24", ip); } } finally { if (ps != null) { ps.close(); } } } }); return null; } }); }
Example #21
Source File: PostgreSQLInetTypeTest.java From hibernate-types with Apache License 2.0 | 5 votes |
@Test public void testJDBCQuery() { doInJPA(new JPATransactionFunction<Void>() { @Override public Void apply(EntityManager entityManager) { Session session = entityManager.unwrap(Session.class); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { PreparedStatement ps = null; try { ps = connection.prepareStatement( "SELECT * " + "FROM Event e " + "WHERE " + " e.ip && ?::inet = true" ); ps.setObject(1, "192.168.0.1/24"); ResultSet rs = ps.executeQuery(); while(rs.next()) { Long id = rs.getLong(1); String ip = rs.getString(2); assertEquals("192.168.0.123/24", ip); } } finally { if (ps != null) { ps.close(); } } } }); return null; } }); }
Example #22
Source File: OracleJsonBinaryTypeTest.java From hibernate-types with Apache License 2.0 | 5 votes |
@Override protected void afterInit() { doInJPA(new JPATransactionFunction<Void>() { @Override public Void apply(EntityManager entityManager) { entityManager.unwrap(Session.class).doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { Statement statement = null; try { statement = connection.createStatement(); statement.executeUpdate( "ALTER TABLE event MOVE LOB (location) STORE AS (CACHE)" ); statement.executeUpdate( "ALTER TABLE participant MOVE LOB (ticket, metadata) STORE AS (CACHE)" ); } finally { if(statement != null) { statement.close(); } } } }); return null; } }); }
Example #23
Source File: HibernateDao.java From opencron with Apache License 2.0 | 5 votes |
@Transactional(readOnly = false) public void executeBatch(final String[] sqlList) { getSession().doWork(new Work() { public void execute(Connection connection) throws SQLException { connection.setAutoCommit(false); Statement stmt = connection.createStatement(); for (String sql : sqlList) { stmt.addBatch(sql); } stmt.executeBatch(); connection.commit(); } }); }
Example #24
Source File: SessionImpl.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public void doWork(final Work work) throws HibernateException { WorkExecutorVisitable<Void> realWork = new WorkExecutorVisitable<Void>() { @Override public Void accept(WorkExecutor<Void> workExecutor, Connection connection) throws SQLException { workExecutor.executeWork( work, connection ); return null; } }; doWork( realWork ); }
Example #25
Source File: ExcelDataRepositoryImpl.java From es with Apache License 2.0 | 5 votes |
public void truncate() { em.unwrap(Session.class).doWork(new Work() { @Override public void execute(final Connection connection) throws SQLException { connection.createStatement().execute("truncate table showcase_excel_data"); } }); }
Example #26
Source File: StoreServiceImpl.java From vladmihalcea.wordpress.com with Apache License 2.0 | 5 votes |
@Override @Transactional(isolation = Isolation.SERIALIZABLE) public void purchase(Long productId) { Product product = entityManager.find(Product.class, 1L); Session session = (Session) entityManager.getDelegate(); session.doWork(new Work() { @Override public void execute(Connection connection) throws SQLException { LOGGER.debug("Transaction isolation level is {}", Environment.isolationLevelToString(connection.getTransactionIsolation())); } }); product.setQuantity(product.getQuantity() - 1); }
Example #27
Source File: MetadataController.java From youkefu with Apache License 2.0 | 4 votes |
@RequestMapping("/sync") @Menu(type = "admin" , subtype = "metadata" , admin = true) public ModelAndView sync(ModelMap map , HttpServletRequest request , @Valid String id) throws SQLException { final MetadataTable table = metadataRes.findById(id) ; Session session = (Session) em.getDelegate(); session.doWork(new Work() { public void execute(Connection connection) throws SQLException { try { MetadataTable metaDataTable = new MetadataTable(); //当前记录没有被添加过,进行正常添加 metaDataTable.setTablename(table.getTablename()); metaDataTable.setOrgi(table.getOrgi()); metaDataTable.setId(UKTools.md5(metaDataTable.getTablename())); metaDataTable.setTabledirid("0"); metaDataTable.setCreater(table.getCreater()); metaDataTable.setCreatername(table.getCreatername()); metaDataTable.setName(table.getName()); metaDataTable.setUpdatetime(new Date()); metaDataTable.setCreatetime(new Date()); processMetadataTable( DatabaseMetaDataHandler.getTable(connection, metaDataTable.getTablename()) , metaDataTable) ; for(TableProperties temp : metaDataTable.getTableproperty()) { boolean found = false ; for(TableProperties tp : table.getTableproperty()) { if(temp.getFieldname().equals(tp.getFieldname())) { found = true ; break ; } } if(found == false) { temp.setDbtableid(table.getId()); tablePropertiesRes.save(temp) ; } } } catch (Exception e) { e.printStackTrace(); }finally{ connection.close(); } } }); return request(super.createRequestPageTempletResponse("redirect:/admin/metadata/table.html?id="+id)); }
Example #28
Source File: SQLExecutorController.java From es with Apache License 2.0 | 4 votes |
@PageableDefaults(pageNumber = 0, value = 10) @RequestMapping(value = "/sql", method = RequestMethod.POST) public String executeQL( final @RequestParam("sql") String sql, final Model model, final Pageable pageable ) { model.addAttribute("sessionFactory", HibernateUtils.getSessionFactory(em)); String lowerCaseSQL = sql.trim().toLowerCase(); final boolean isDML = lowerCaseSQL.startsWith("insert") || lowerCaseSQL.startsWith("update") || lowerCaseSQL.startsWith("delete"); final boolean isDQL = lowerCaseSQL.startsWith("select"); if(!isDML && !isDQL) { model.addAttribute(Constants.ERROR, "您执行的SQL不允许,只允许insert、update、delete、select"); return showSQLForm(); } try { new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { if (isDML) { Query query = em.createNativeQuery(sql); int updateCount = query.executeUpdate(); model.addAttribute("updateCount", updateCount); } else { String findSQL = sql; String countSQL = "select count(*) count from (" + findSQL + ") o"; Query countQuery = em.createNativeQuery(countSQL); Query findQuery = em.createNativeQuery(findSQL); findQuery.setFirstResult(pageable.getOffset()); findQuery.setMaxResults(pageable.getPageSize()); Page page = new PageImpl( findQuery.getResultList(), pageable, ((BigInteger) countQuery.getSingleResult()).longValue()); model.addAttribute("resultPage", page); em.unwrap(Session.class).doWork(new Work() { @Override public void execute(final Connection connection) throws SQLException { PreparedStatement psst = connection.prepareStatement(sql); ResultSetMetaData metaData = psst.getMetaData(); List<String> columnNames = Lists.newArrayList(); for(int i = 1, l = metaData.getColumnCount(); i <= l; i++) { columnNames.add(metaData.getColumnLabel(i)); } psst.close(); model.addAttribute("columnNames", columnNames); } }); } return null; } }); } catch (Exception e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); model.addAttribute(Constants.ERROR, sw.toString()); } return showSQLForm(); }
Example #29
Source File: LanguageServlet.java From document-management-system with GNU General Public License v2.0 | 4 votes |
/** * Import a new language into database */ private void importLanguage(String userId, HttpServletRequest request, HttpServletResponse response, final byte[] data, Session dbSession) throws DatabaseException, IOException, SQLException { log.debug("importLanguage({}, {}, {}, {}, {})", new Object[]{userId, request, response, data, dbSession}); // Because need to be final and an array can be modified being final final String[] insertLanguage = new String[1]; dbSession.doWork(new Work() { @Override public void execute(Connection con) throws SQLException { Statement stmt = con.createStatement(); InputStreamReader is = new InputStreamReader(new ByteArrayInputStream(data)); BufferedReader br = new BufferedReader(is); String query; try { while ((query = br.readLine()) != null) { // Used to get the inserted language id if (query.indexOf("INSERT INTO OKM_LANGUAGE") >= 0) { insertLanguage[0] = query; } stmt.executeUpdate(query); } } catch (IOException e) { throw new SQLException(e.getMessage(), e); } LegacyDAO.close(stmt); } }); // Normalize imported language LanguageDAO.refresh(); for (Language language : LanguageDAO.findAll()) { // Check for inserted language id if (insertLanguage[0].indexOf(language.getId()) > 0) { LanguageDAO.normalizeTranslation(language); break; } } // Clean language cache again LanguageDAO.refresh(); log.debug("importLanguage: void"); }
Example #30
Source File: SessionDelegatorBaseImpl.java From lams with GNU General Public License v2.0 | 4 votes |
@Override public void doWork(Work work) throws HibernateException { delegate.doWork( work ); }