org.hibernate.Session#doWork ( )源码实例Demo

下面列出了org.hibernate.Session#doWork ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

private void setCurrentLoggedUser(EntityManager entityManager) {
    Session session = entityManager.unwrap(Session.class);
    Dialect dialect = session.getSessionFactory().unwrap(SessionFactoryImplementor.class).getJdbcServices().getDialect();
    String loggedUser = ReflectionUtils.invokeMethod(
        dialect,
        "escapeLiteral",
        LoggedUser.get()
    );

    session.doWork(connection -> {
        update(
            connection,
            String.format(
                "SET @logged_user = '%s'", loggedUser
            )
        );
    });
}
 
源代码2 项目: youkefu   文件: MetadataController.java
@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"));
  }
 
@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();
        }
    }
}
 
private void setCurrentLoggedUser(EntityManager entityManager) {
    Session session = entityManager.unwrap(Session.class);
    Dialect dialect = session.getSessionFactory().unwrap(SessionFactoryImplementor.class).getJdbcServices().getDialect();
    String loggedUser = ReflectionUtils.invokeMethod(
        dialect,
        "escapeLiteral",
        LoggedUser.get()
    );

    session.doWork(connection -> {
        update(
            connection,
            String.format(
                "SET @logged_user = '%s'", loggedUser
            )
        );
    });
}
 
/**
 * Import into database
 */
private void executeUpdate(Session session, byte[] data, ServletContext sc, HttpServletRequest request, HttpServletResponse response)
		throws SQLException, ServletException, IOException {
	log.debug("executeUpdate({}, {}, {})", new Object[]{session, request, response});
	List<DbQueryGlobalResult> globalResults = new ArrayList<DbQueryGlobalResult>();
	WorkerUpdate worker = new WorkerUpdate();
	worker.setData(data);
	session.doWork(worker);

	DbQueryGlobalResult gr = new DbQueryGlobalResult();
	gr.setColumns(null);
	gr.setResults(null);
	gr.setSql(null);
	gr.setRows(worker.getRows());
	gr.setErrors(worker.getErrors());
	globalResults.add(gr);

	sc.setAttribute("qs", null);
	sc.setAttribute("type", null);
	sc.setAttribute("showSql", null);
	sc.setAttribute("globalResults", globalResults);
	sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);

	log.debug("executeUpdate: void");
}
 
@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();
        }
    }
}
 
源代码7 项目: document-management-system   文件: LegacyDAO.java
/**
 * * Execute SQL query
 */
public static List<List<String>> executeSQL(final String query) throws DatabaseException {
	ResultWorker worker = new ResultWorker();
	Session session = null;
	Transaction tx = null;

	try {
		session = HibernateUtil.getSessionFactory().openSession();
		tx = session.beginTransaction();
		worker.setSql(query);
		session.doWork(worker);
		HibernateUtil.commit(tx);
	} catch (Exception e) {
		HibernateUtil.rollback(tx);
		throw new DatabaseException(e.getMessage(), e);
	}

	return worker.getResults();
}
 
源代码8 项目: hibernate-master-class   文件: AbstractTest.java
protected <T> T doInJDBC(ConnectionCallable<T> callable) {
    AtomicReference<T> result = new AtomicReference<>();
    Session session = null;
    Transaction txn = null;
    try {
        session = getSessionFactory().openSession();
        txn = session.beginTransaction();
        session.doWork(connection -> {
            result.set(callable.execute(connection));
        });
        txn.commit();
    } catch (RuntimeException e) {
        if ( txn != null && txn.isActive() ) txn.rollback();
        throw e;
    } finally {
        if (session != null) {
            session.close();
        }
    }
    return result.get();
}
 
protected void doInJOOQ(DSLContextVoidCallable callable, Settings settings) {
    Session session = null;
    Transaction txn = null;
    try {
        session = sessionFactory().openSession();
        txn = session.beginTransaction();
        session.doWork(connection -> {
            DSLContext sql = settings != null ?
                DSL.using(connection, sqlDialect(), settings) :
                DSL.using(connection, sqlDialect());
            callable.execute(sql);
        });
        txn.commit();
    } catch (Throwable e) {
        if ( txn != null ) txn.rollback();
        throw e;
    } finally {
        if (session != null) {
            session.close();
        }
    }
}
 
private void setEncryptionKey(EntityManager entityManager) {
	Session session = entityManager.unwrap(Session.class);
	Dialect dialect = session.getSessionFactory().unwrap(SessionFactoryImplementor.class).getJdbcServices().getDialect();
	String encryptionKey = ReflectionUtils.invokeMethod(
		dialect,
		"escapeLiteral",
		"encryptionKey"
	);

	session.doWork(connection -> {
		update(
			connection,
			String.format(
				"SET @encryption_key = '%s'", encryptionKey
			)
		);
	});
}
 
源代码11 项目: spring-boot   文件: CustomHibernateJpaDialect.java
@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;
}
 
源代码12 项目: document-management-system   文件: ConfigServlet.java
/**
 * Import configuration into database
 */
private void importConfig(String userId, HttpServletRequest request, HttpServletResponse response,
                          final byte[] data, Session dbSession) throws DatabaseException,
		IOException, SQLException {
	log.debug("importConfig({}, {}, {}, {}, {})", new Object[]{userId, request, response, data, dbSession});
	WorkerUpdate worker = new DatabaseQueryServlet().new WorkerUpdate();
	worker.setData(data);
	dbSession.doWork(worker);
	log.debug("importConfig: void");
}
 
protected void executeStatement(EntityManager entityManager, String... sqls) {
    Session session = entityManager.unwrap(Session.class);
    for (String sql : sqls) {
        try {
            session.doWork(connection -> {
                executeStatement(connection, sql);
            });
        } catch (Exception e) {
            LOGGER.error(
                String.format("Error executing statement: %s", sql), e
            );
        }
    }
}
 
/**
 * Import mime types into database
 */
private void importMimeTypes(String userId, HttpServletRequest request, HttpServletResponse response,
                             final byte[] data, Session dbSession) throws DatabaseException,
		IOException, SQLException {
	log.debug("import({}, {}, {}, {}, {})", new Object[]{userId, request, response, data, dbSession});

       WorkerUpdate worker = new DatabaseQueryServlet().new WorkerUpdate();
       worker.setData(data);
       dbSession.doWork(worker);
       log.debug("importMimeTypes: void");
}
 
源代码15 项目: document-management-system   文件: ReportUtils.java
/**
 * 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);
			}
		}
	});
}
 
@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);
}
 
源代码17 项目: framework   文件: BaseHibernateDao.java
/**
 * 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();
                }
            }
        }
    });
}
 
源代码18 项目: youkefu   文件: MetadataController.java
@RequestMapping("/addsqlsave")
@Menu(type = "admin" , subtype = "metadata" , admin = true)
public ModelAndView addsqlsave(ModelMap map , HttpServletRequest request , final @Valid String datasql , final @Valid String name) throws Exception {
	if(!StringUtils.isBlank(datasql) && !StringUtils.isBlank(name)){
		final User user = super.getUser(request);
 	Session session = (Session) em.getDelegate();
 	session.doWork(
 		    new Work() {
 		        public void execute(Connection connection) throws SQLException 
 		        {
 		        	try{
 		        		int count = metadataRes.countByTablename(name) ;
				    		if(count == 0){
			 		    		MetadataTable metaDataTable = new MetadataTable();
				  				//当前记录没有被添加过,进行正常添加
				  				metaDataTable.setTablename(name);
				  				metaDataTable.setOrgi(user.getOrgi());
				  				metaDataTable.setId(UKTools.md5(metaDataTable.getTablename()));
				  				metaDataTable.setTabledirid("0");
				  				metaDataTable.setCreater(user.getId());
				  				metaDataTable.setCreatername(user.getUsername());
				  				metaDataTable.setName(name);
				  				metaDataTable.setDatasql(datasql);
				  				metaDataTable.setTabletype("2");
				  				metaDataTable.setUpdatetime(new Date());
				  				metaDataTable.setCreatetime(new Date());
				  				metadataRes.save(processMetadataTable( DatabaseMetaDataHandler.getSQL(connection, name, datasql) , metaDataTable));
				    		}
 			    	}catch(Exception ex){
 			    		ex.printStackTrace();
 			    	}finally{
 			    		connection.close();
 			    	}
 		        }
 		    }
 		);
 	
	}
	
    return request(super.createRequestPageTempletResponse("redirect:/admin/metadata/index.html"));
}
 
源代码19 项目: uyuni   文件: ExplainPlanGenerator.java
/** Execute the task
 *  @throws IOException If the output file can't be opened.
 *  @throws SQLException if something goes wrong with the DB.
 */
public void execute() throws IOException, SQLException {
    Session session = null;
    Connection conn = null;
    try {
        session = HibernateFactory.getSession();
        PrintStream out = new PrintStream(new FileOutputStream(outfile));

        session.doWork((connection) -> {

            Collection fileKeys = ModeFactory.getKeys();

            TreeSet ts = new TreeSet(fileKeys);
            Iterator i = ts.iterator();
            while (i.hasNext()) {
                String file = (String)i.next();
                Map queries = ModeFactory.getFileKeys(file);
                if (file.equals("test_queries")) {
                    continue;
                }
                out.println("\nFile:   " + file);

                Iterator q = new TreeSet(queries.keySet()).iterator();
                int count = 0;
                while (q.hasNext()) {
                    Mode m = (Mode)queries.get(q.next());

                    /* Don't do plans for queries that use system tables or for
                     * dummy queries.
                     */
                    if (shouldSkip(m)) {
                        out.println("\nSkipping dummy query:  " + m.getName());
                        continue;
                    }
                    if (!(m instanceof SelectMode)) {
                        out.println("\nSkipping Write or Callable mode:" + m.getName());
                        continue;
                    }
                    out.println("\nPlan for " + m.getName());

                    String query = "EXPLAIN PLAN " +
                        "SET STATEMENT_ID='" + QUERY_NAME + "' FOR " +
                        m.getQuery().getOrigQuery();

                    // HACK!  Some of the queries actually have %s in them.
                    // So, replace all %s with :rbb so that the explain plan
                    // can be generated.
                    query = query.replaceAll("%s", ":rbb");

                    PreparedStatement ps = conn.prepareStatement(query);

                    ps.execute();
                    ps.close();

                    // Now that we have generated the explain plan, we just
                    // need to get it from the DB.
                    ps = conn.prepareStatement(EXPLAIN_QUERY);
                    ps.setString(1, QUERY_NAME);
                    ps.setString(2, QUERY_NAME);
                    ResultSet rs = ps.executeQuery();
                    while (rs.next()) {
                        String parentId = rs.getString("explain_parent_id");
                        String id = rs.getString("explain_id");
                        String operation = rs.getString("explain_operation");

                        out.println(parentId + " " + id + " " + operation);
                    }
                    count++;
                    rs.close();
                    ps.close();
                    Statement st = conn.createStatement();
                    st.execute("Delete FROM plan_table where " +
                                    "STATEMENT_ID='" + QUERY_NAME + "'");
                    st.close();

                }
            }
            out.close();
        });
    }
    catch (HibernateException he) {
        throw new
            HibernateRuntimeException(
                "HibernateException in ExplainPlanGenerator.", he);
    }
}
 
/**
 * 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");
}