Example usage for org.hibernate.jdbc ReturningWork ReturningWork

List of usage examples for org.hibernate.jdbc ReturningWork ReturningWork

Introduction

In this page you can find the example usage for org.hibernate.jdbc ReturningWork ReturningWork.

Prototype

ReturningWork

Source Link

Usage

From source file:br.com.casadasmarmitas.util.HibernateUtil.java

public static Connection getConnection() {
    Session sessao = fabricaSessoes.openSession();
    Connection conexao = sessao.doReturningWork(new ReturningWork<Connection>() {
        @Override//from   ww w  . j a v  a 2 s  . c o  m
        public Connection execute(Connection conn) throws SQLException {
            return conn;
        }
    });
    return conexao;
}

From source file:com.eclecticlogic.pedal.provider.hibernate.HibernateProviderAccessSpiImpl.java

License:Apache License

@Override
public <R> R exec(EntityManager entityManager, final Function<Connection, R> work) {
    Session session = entityManager.unwrap(Session.class);
    return session.doReturningWork(new ReturningWork<R>() {

        @Override/*  w  ww  .  j  a v a 2  s .com*/
        public R execute(Connection connection) throws SQLException {
            return work.apply(connection);
        }
    });
}

From source file:com.herval.gestaoefetivo.util.HibernateUtil.java

public static Connection getConexao() {
    Session sessao = sessionFactory.openSession();

    Connection conexao = sessao.doReturningWork(new ReturningWork<Connection>() {
        @Override//from ww  w  .  j  av a2s.c om
        public Connection execute(Connection conn) throws SQLException {
            return conn;
        }
    });

    return conexao;
}

From source file:com.itrus.ca.common.persistence.BaseDaoImpl.java

License:Open Source License

public SQLQuery findBySQL(final String sql, final int pageNo, final int numPerPage) {
    return (SQLQuery) (T) getSession().doReturningWork(new ReturningWork() {
        public SQLQuery execute(Connection connection) throws SQLException {
            SQLQuery sqlQuery = getSession().createSQLQuery(sql);
            if (pageNo > 0) {
                sqlQuery.setFirstResult((pageNo - 1) * numPerPage);
                sqlQuery.setMaxResults(numPerPage);
            }// w  w  w .  j  a va  2  s.c  om

            return sqlQuery;
        }
    });
}

From source file:com.lib.Dao.java

/**
 * Select d liu t procedure//from  ww  w.  j av a  2  s. co  m
 *
 * @param nameProc Tn ca procedure (V d: exec GetABC ?,?,?)
 * @param values Tham s truy?n vo cho proc
 * @return ResultSet
 */
@Override
public ResultSet selectFromProceduce(final String nameProc, final Object[] values) {

    ResultSet rs = session.doReturningWork(new ReturningWork<ResultSet>() {
        @Override
        public ResultSet execute(Connection cnctn) throws SQLException {
            CallableStatement cs = null;
            try {
                cs = cnctn.prepareCall(nameProc);
                for (int i = 0; i < values.length; i++) {
                    cs.setObject(i + 1, values[i]);
                }
                ResultSet rs = cs.executeQuery();
                return rs;
            } catch (SQLException ex) {
                Logger.getLogger(Dao.class.getName()).log(Level.SEVERE, null, ex);
                return null;
            }
        }
    });

    return rs;
}

From source file:de.innovationgate.csmaintenance.MySQLEngineDependentPatch.java

License:Open Source License

public String getPatchCode(WGDatabase db) throws WGAPIException {

    // Find out about the storage engine used on table "webarea"
    return ((Session) db.getNativeObject()).doReturningWork(new ReturningWork<String>() {

        public String execute(Connection conn) throws SQLException {
            Statement stmt1 = null;
            Statement stmt2 = null;
            try {
                // Query engine
                stmt1 = conn.createStatement();
                if (!stmt1.execute(
                        "SELECT ENGINE FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'webarea'")) {
                    throw new SQLException("Unable to determine storage engine for MySQL patch");
                }//from   w  w  w.  ja  v a 2 s . c o  m
                ResultSet set = stmt1.getResultSet();
                set.next();
                String engine = set.getString(1);

                // Query character set
                stmt2 = conn.createStatement();
                if (!stmt2.execute(
                        "SELECT CHARACTER_SET_NAME, COLLATION_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'webarea' AND COLUMN_NAME='id'")) {
                    throw new SQLException("Unable to determine storage engine for MySQL patch");
                }
                set = stmt2.getResultSet();
                set.next();
                String characterSet = set.getString(1);
                String collationName = set.getString(2);

                String code = WGUtils.strReplace(_code, "${mysql.engine}", engine, true);
                code = WGUtils.strReplace(code, "${mysql.charset}", characterSet, true);
                code = WGUtils.strReplace(code, "${mysql.collation}", collationName, true);

                return code;

            } catch (Exception e) {
                throw new SQLException("Exception determining patch code", e);
            } finally {
                if (stmt1 != null) {
                    try {
                        stmt1.close();
                    } catch (SQLException e) {
                    }
                }
                if (stmt2 != null) {
                    try {
                        stmt2.close();
                    } catch (SQLException e) {
                    }
                }
            }

        }
    });

}

From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java

License:Open Source License

public String getServerName() throws WGAPIException {

    try {/*from  w  ww  .j  a v  a2 s.  com*/
        DatabaseMetaData metaData = getSession().doReturningWork(new ReturningWork<DatabaseMetaData>() {
            public DatabaseMetaData execute(Connection connection) throws SQLException {
                return connection.getMetaData();
            }
        });
        return metaData.getDatabaseProductName() + " " + metaData.getDatabaseProductVersion();
    } catch (HibernateException e) {
        throw new WGBackendException("Error retrieving server name", e);
    } catch (SQLException e) {
        throw new WGBackendException("Error retrieving server name", e);
    }
}

From source file:io.vertigo.dynamo.plugins.database.connection.hibernate.HibernateConnectionProviderPlugin.java

License:Apache License

/**
 * @param em EntityManager/*from w  w  w  .  ja va 2 s  .c o  m*/
 * @return the sqlConnection
 */
private SqlConnection obtainWrappedConnection(final EntityManager em) {
    //preconisation StackOverFlow to get current jpa connection
    final Session session = em.unwrap(Session.class);
    return session.doReturningWork(new ReturningWork<SqlConnection>() {
        @Override
        public SqlConnection execute(final Connection connection) throws SQLException {
            return new SqlConnection(connection, getDataBase(), false);
        }
    });
}

From source file:net.clanwolf.starmap.server.util.WebDataInterface.java

License:Apache License

public static void createSystemList(SystemListTypes type) {
    initialize();//from   w w  w  .j a  va2s .com
    Log.print("Starting with the creation of the system list: " + type.name());

    EntityManager manager = EntityManagerHelper.getEntityManager();
    manager.getTransaction().begin();

    Session session = manager.unwrap(Session.class);
    ResultObject result = session.doReturningWork(new ReturningWork<ResultObject>() {
        @Override
        public ResultObject execute(Connection conn) throws SQLException {
            // execute your SQL
            ResultSet rs = null;
            ResultObject resultObject = new ResultObject();
            String systemsList = null;
            try (PreparedStatement stmt = conn.prepareStatement(selects.get(type.name()))) {
                rs = stmt.executeQuery();
                Log.print("Select done...");

                if (universe == null) {
                    universe = new UniverseDTO();
                }

                if (type == SystemListTypes.Factions) {
                    universe.factions.clear();
                    while (rs.next()) {
                        FactionDTO f = new FactionDTO();
                        f.setName(rs.getString("name"));
                        f.setShortName(rs.getString("short"));
                        f.setColor(rs.getString("color"));
                        f.setLogo(rs.getString("logo"));

                        universe.factions.put(f.getShortName(), f);
                    }
                    Log.print("Created universe classes (Factions)...");
                }

                if (type == SystemListTypes.HH_StarSystems) {
                    universe.starSystems.clear();
                    while (rs.next()) {
                        StarSystemDTO ss = new StarSystemDTO();
                        ss.setId(rs.getInt("sid"));
                        ss.setName(rs.getString("name"));
                        ss.setX(rs.getBigDecimal("x"));
                        ss.setY(rs.getBigDecimal("y"));
                        ss.setAffiliation(rs.getString("affiliation"));
                        ss.setStarType1(rs.getString("startype1"));
                        ss.setStarClass(rs.getString("class"));
                        ss.setSarnaLink(rs.getString("link"));
                        ss.setInfrastructure(rs.getString("infrastructure"));
                        ss.setWealth(rs.getString("wealth"));
                        ss.setVeternacy(rs.getString("veternacy"));
                        ss.setType(rs.getString("type"));

                        HashMap<String, String> maps = new HashMap<>();
                        maps.put("s1map1", rs.getString("s1map1"));
                        maps.put("s1map2", rs.getString("s1map2"));
                        maps.put("s1map3", rs.getString("s1map3"));
                        maps.put("s2map1", rs.getString("s2map1"));
                        maps.put("s2map2", rs.getString("s2map2"));
                        maps.put("s2map3", rs.getString("s2map3"));
                        maps.put("s3map1", rs.getString("s3map1"));
                        maps.put("s3map2", rs.getString("s3map2"));
                        maps.put("s3map3", rs.getString("s3map3"));
                        ss.setMaps(maps);

                        universe.starSystems.put(ss.getId(), ss);
                    }
                    Log.print("Created universe classes (StarSystems)...");
                }

                if (type == SystemListTypes.HH_Attacks) {
                    universe.attacks.clear();
                    while (rs.next()) {
                        AttackDTO a = new AttackDTO();
                        a.setId(rs.getInt("aid"));
                        a.setSeason(rs.getInt("season"));
                        a.setRound(rs.getInt("round"));
                        a.setPriority(rs.getInt("priority"));
                        a.setStarSystemId(rs.getInt("starsystem"));
                        a.setStarSystemDataId(rs.getInt("starsystemdata"));
                        a.setAttackedFromStarSystem(rs.getInt("attackedfromstarsystem"));
                        a.setAttackType(rs.getInt("attackType"));
                        a.setAttackerId(rs.getInt("attacker"));
                        a.setDefenderId(rs.getInt("defender"));

                        universe.attacks.add(a);
                    }
                    Log.print("Created universe classes (Attacks)...");
                }

                if (type == SystemListTypes.HH_Jumpships) {
                    universe.jumpships.clear();
                    while (rs.next()) {
                        JumpshipDTO js = new JumpshipDTO();
                        js.setShipID(rs.getInt("jsid"));
                        js.setShipName(rs.getString("jumpshipName"));
                        js.setShipID(rs.getInt("jumpshipFactionID"));
                        js.setStarSystemHistory(rs.getString("starHist"));
                        js.setLastMovedInRound(rs.getInt("lastMovedInRound"));
                        js.setCombatReady(rs.getBoolean("attackReady"));

                        universe.jumpships.put(js.getShipName(), js);
                    }
                    Log.print("Created universe classes (Jumpships)...");
                }
                universe.currentSeason = 1;
                universe.currentRound = 6;

                // create JSON representation
                rs.beforeFirst();
                systemsList = getJSONFromResultSet(rs, type.name(), true);
            } catch (Exception e) {
                Log.exception(WebDataInterface.class, e);
            }
            resultObject.setResultList(systemsList);
            return resultObject;
        }
    });

    File mapDataFile = null;
    File mapDataFileHH = null;
    File mapDataFileCM = null;

    String decodedPath = "";
    String systemsList = result.getResultList();
    String filename = "";
    String filenameHH = "";
    String filenameCM = "";

    try {
        String path = WebDataInterface.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        String pathHH = "/var/www/vhosts/clanwolf.net/httpdocs/starmap_CM";
        String pathCM = "/var/www/vhosts/clanwolf.net/httpdocs/starmap_HH";

        decodedPath = URLDecoder.decode(path, "UTF-8");
        File f = new File(decodedPath);
        String parent = f.getParent();
        filename = parent + File.separator + "mapdata_" + type.name() + ".json";
        filenameHH = pathHH + File.separator + "mapdata_" + type.name() + ".json";
        filenameCM = pathCM + File.separator + "mapdata_" + type.name() + ".json";

        mapDataFile = new File(filename);
        mapDataFileHH = new File(filenameHH);
        mapDataFileCM = new File(filenameCM);

        Log.print("Wrote file: " + filename);
        Log.print("Wrote file: " + filenameHH);
        Log.print("Wrote file: " + filenameCM);
    } catch (UnsupportedEncodingException usee) {
        Log.exception(WebDataInterface.class, usee);
    }

    if (mapDataFile != null) {
        try (BufferedWriter br = new BufferedWriter(new FileWriter(mapDataFile))) {
            br.write(systemsList);
        } catch (IOException ioe) {
            Log.exception(WebDataInterface.class, ioe);
        }
    } else {
        RuntimeException rte = new RuntimeException("Could not write file: " + filename);
        Log.exception(WebDataInterface.class, rte);
        throw rte;
    }

    if (mapDataFileHH != null) {
        try (BufferedWriter br = new BufferedWriter(new FileWriter(mapDataFileHH))) {
            br.write(systemsList);
        } catch (IOException ioe) {
            Log.exception(WebDataInterface.class, ioe);
        }
    } else {
        RuntimeException rte = new RuntimeException("Could not write file: " + mapDataFileHH);
        Log.exception(WebDataInterface.class, rte);
        throw rte;
    }

    if (mapDataFileCM != null) {
        try (BufferedWriter br = new BufferedWriter(new FileWriter(mapDataFileCM))) {
            br.write(systemsList);
        } catch (IOException ioe) {
            Log.exception(WebDataInterface.class, ioe);
        }
    } else {
        RuntimeException rte = new RuntimeException("Could not write file: " + mapDataFileCM);
        Log.exception(WebDataInterface.class, rte);
        throw rte;
    }

    manager.getTransaction().commit();
    manager.close();
}

From source file:net.satago.tapestry5.jpa.test.JpaTest.java

License:Apache License

private void clearDatabase() throws SQLException {
    CommitCounter.versionedThing.get().reset();

    EntityManager em = getEntityManager();
    em.clear();//from ww w .  j  a  va2 s  .com
    EntityTransaction transaction = em.getTransaction();
    if (!transaction.isActive()) {
        transaction.begin();
    }

    final Connection c;

    if (concreteJpaProviderTestModuleClass == HibernateJpaTestModule.class) {
        //  Hibernate cannot unwrap JDBC connection directly
        c = em.unwrap(Session.class).doReturningWork(new ReturningWork<Connection>() {
            @Override
            public Connection execute(Connection connection) throws SQLException {
                return connection;
            }
        });
    } else {
        c = em.unwrap(Connection.class);
    }

    Statement s = c.createStatement();
    s.execute("SET REFERENTIAL_INTEGRITY FALSE");
    Set<String> tables = new HashSet<String>();
    ResultSet rs = s.executeQuery("select table_name " + "from INFORMATION_SCHEMA.tables "
            + "where table_type='TABLE' and table_schema='PUBLIC'");
    while (rs.next()) {
        // if we don't skip over the sequence table, we'll start getting "The sequence table information is not complete"
        // exceptions
        if (!rs.getString(1).startsWith("DUAL_") && !rs.getString(1).equals("SEQUENCE")) {
            tables.add(rs.getString(1));
        }
    }
    rs.close();
    for (String table : tables) {
        s.executeUpdate("DELETE FROM " + table);
    }
    transaction.commit();
    s.execute("SET REFERENTIAL_INTEGRITY TRUE");
    s.close();
}