Example usage for org.hibernate Session flush

List of usage examples for org.hibernate Session flush

Introduction

In this page you can find the example usage for org.hibernate Session flush.

Prototype

void flush() throws HibernateException;

Source Link

Document

Force this session to flush.

Usage

From source file:com.advdb.footballclub.FootBallClub.java

private void createPlayer(Session session) {

    Transaction transaction = null;/*from w  ww  . ja v  a  2s .  c  o  m*/
    try {
        System.out.println("start createPlayer.");
        transaction = session.beginTransaction();
        Reader in = new FileReader("/Users/apichart/Documents/DW_opponent/DimPlayer-Table 1.csv");
        Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(in);
        for (CSVRecord record : records) {
            String name = record.get(2);
            String nationality = record.get(3);
            String value = record.get(4);
            String height = record.get(6);
            String weight = record.get(7);
            DimPlayer d = new DimPlayer(name, nationality, Double.valueOf(value), Double.valueOf(height),
                    Double.valueOf(weight));
            session.save(d);
        }
        in.close();
        session.flush();
        session.clear();
        transaction.commit();

        System.out.println("finish createPlayer.");
    } catch (HibernateException e) {
        if (transaction != null) {
            transaction.rollback();
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(FootBallClub.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(FootBallClub.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.advdb.footballclub.FootBallClub.java

private void createFactMatch(Session session) {
    Transaction transaction = null;/* w ww  .  java  2s  .co m*/
    try {
        System.out.println("start createFactMatch.");
        transaction = session.beginTransaction();
        String hqlDC = "from DimCompetition dc";
        List result = session.createQuery(hqlDC).list();
        result.forEach((object) -> {

            DimCompetition dimCompetition = (DimCompetition) object;
            int startYear = dimCompetition.getSeasonStartYear();
            int endYear = dimCompetition.getSeasonEndYear();
            GregorianCalendar cal = randomYear(startYear, endYear);
            //                createDate(session, gregorianCalendar);
            if (dimCompetition.getCompetiotionName().equals(COMPETITION_NAME_ARR[0])
                    || dimCompetition.getCompetiotionName().equals(COMPETITION_NAME_ARR[1])) {

                int times = randomWithRange(1, 7);
                //Random opponent
                String hqlDO = "from DimOpponent do";
                List resultDO = session.createQuery(hqlDO).list();
                HashMap<Integer, Integer> opponentMap = new HashMap<Integer, Integer>();
                int opponentIndex;
                do {

                    opponentIndex = randBetween(0, resultDO.size());
                    if (!opponentMap.containsKey(opponentIndex)) {
                        opponentMap.put(opponentIndex, opponentIndex);
                        generateFactMatch(opponentIndex, cal, dimCompetition.getCompetitionKy(), session);
                        //Random tactic
                        //Random player

                    }
                } while (opponentMap.size() != times);

            } else if (dimCompetition.getCompetiotionName().equals(COMPETITION_NAME_ARR[2])
                    || dimCompetition.getCompetiotionName().equals(COMPETITION_NAME_ARR[3])) {

                //Random opponent
                String hqlDO = "from DimOpponent do";
                List resultDO = session.createQuery(hqlDO).list();
                HashMap<Integer, Integer> opponentMap = new HashMap<Integer, Integer>();
                int opponentIndex;
                do {
                    opponentIndex = randBetween(0, resultDO.size());
                    if (!opponentMap.containsKey(opponentIndex)) {
                        opponentMap.put(opponentIndex, opponentIndex);
                        generateFactMatch(opponentIndex, cal, dimCompetition.getCompetitionKy(), session);

                    }
                } while (opponentMap.size() != 38);

            } else {

            }

        });
        session.flush();
        session.clear();
        //            }
        transaction.commit();
        System.out.println("finish createFactMatch.");
    } catch (HibernateException e) {
        if (transaction != null) {
            transaction.rollback();
        }
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.ajar.Controller.GoogleStockDownload.java

public GoogleStockDownload(String symbol, Date start, Date end) {

    dates = new ArrayList<Date>();
    opens = new ArrayList<Double>();
    highs = new ArrayList<Double>();
    lows = new ArrayList<Double>();
    closes = new ArrayList<Double>();
    volumes = new ArrayList<Integer>();
    //        adjcloses = new ArrayList<Double>();                

    ////        https://www.google.com/finance/historical?q=IDX:ABBA&startdate=01+01,+2016&enddate=03+14,+2016&output=csv
    String url = "https://www.google.com/finance/historical?q=IDX:" + symbol + "&startdate="
            + formatter.format(start.getTime()) + "&enddate=" + formatter.format(end.getTime()) + "&output=csv";

    try {/*  w  w w .j  av a2 s  .c o  m*/
        URL googlefin = new URL(url);
        URLConnection data = googlefin.openConnection();
        Scanner input = new Scanner(data.getInputStream());

        if (input.hasNext()) //Skip line, its just header
        {
            input.nextLine();
        }

        //            Save to DB 
        Session session = HibernateSessionManager.getSessionFactory().openSession();
        session.beginTransaction();
        // Start read line
        while (input.hasNextLine()) {
            String line = input.nextLine();
            // TODO - Correct data to the correct arraylist
            // Print all result directly to prompt                 
            //                System.out.println(symbol+","+line);  
            //                Afif's property to save into Table DB

            String str = symbol + "," + line;
            String strArray[] = str.split(",");

            TrxStock trx = new TrxStock();
            String dtq = strArray[1];
            Date dtTrx = df.parse(dtq);
            trx.setTicklerID(strArray[0]);
            trx.setTicklerDT(dtTrx);
            trx.setTicklerOpen(Float.valueOf(strArray[2] + 0));
            trx.setTicklerHigh(Float.valueOf(strArray[3] + 0));
            trx.setTicklerLow(Float.valueOf(strArray[4] + 0));
            trx.setTicklerClose(Float.valueOf(strArray[5] + 0));
            trx.setTicklerVol(Float.valueOf(strArray[6]));
            //                trx.setTicklerInt(Float.valueOf(strArray[7]));
            session.save(trx);

            for (int i = 0; i < 100000; i++) {
                if (i % 50 == 0) { //20, same as the JDBC batch size
                    //flush a batch of inserts and release memory:
                    session.flush();
                    session.clear();
                }
            }
        }
        session.getTransaction().commit();
        System.out.println("Save to DB Success");
        session.close();
    } catch (Exception e) {
        System.err.println(e);
    }

}

From source file:com.ajar.StockDownloader.java

public StockDownloader(String symbol, GregorianCalendar start, GregorianCalendar end) {

    dates = new ArrayList<GregorianCalendar>();
    opens = new ArrayList<Double>();
    highs = new ArrayList<Double>();
    lows = new ArrayList<Double>();
    closes = new ArrayList<Double>();
    volumes = new ArrayList<Integer>();
    adjcloses = new ArrayList<Double>();

    //http://finance.yahoo.com/q/hp?s=ASII.JK&a=09&b=17&c=2000&d=01&e=7&f=2016&g=d
    //http://real-chart.finance.yahoo.com/table.csv?s=ASII.JK&a=09&b=17&c=2000&d=01&e=7&f=2016&g=d&ignore=.csv
    //        http://real-chart.finance.yahoo.com/table.csv?s=ASII.JK&d=2&e=7&f=2016&g=d&a=9&b=17&c=2000&ignore=.csv
    //        String url = "http://ichart.finance.yahoo.com/table.csv?s=" + symbol
    String url = "http://real-chart.finance.yahoo.com/table.csv?s=" + symbol + "&a=" + start.get(Calendar.MONTH)
            + "&b=" + start.get(Calendar.DAY_OF_MONTH) + "&c=" + start.get(Calendar.YEAR) + "&d="
            + end.get(Calendar.MONTH) + "&e=" + end.get(Calendar.DAY_OF_MONTH) + "&f=" + end.get(Calendar.YEAR)
            //                + "&g=d&ignore=.csv";
            + "&g=d";

    try {/*from  w  w w.j av  a  2  s  .  co  m*/
        URL yahoofinn = new URL(url);
        URLConnection data = yahoofinn.openConnection();
        Scanner input = new Scanner(data.getInputStream());

        if (input.hasNext()) //Skip line, its just header
        {
            input.nextLine();
        }

        //            Save to DB 
        Session session = HibernateSessionManager.getSessionFactory().openSession();
        session.beginTransaction();
        // Start read line
        while (input.hasNextLine()) {
            String line = input.nextLine();
            // TODO - Correct data to the correct arraylist
            // Print all result directly to prompt                 
            //                System.out.println(symbol+","+line);  
            //                Afif's property to save into Table DB

            String str = symbol + "," + line;
            String strArray[] = str.split(",");
            //                System.out.println("Save to DB");

            TrxStock trx = new TrxStock();
            trx.setTicklerID(strArray[0]);
            trx.setTicklerDT(formatter.parse(strArray[1]));
            trx.setTicklerOpen(Float.valueOf(strArray[2]));
            trx.setTicklerHigh(Float.valueOf(strArray[3]));
            trx.setTicklerLow(Float.valueOf(strArray[4]));
            trx.setTicklerClose(Float.valueOf(strArray[5]));
            trx.setTicklerVol(Float.valueOf(strArray[6]));
            trx.setTicklerInt(Float.valueOf(strArray[7]));
            session.save(trx);

            for (int i = 0; i < 100000; i++) {
                if (i % 50 == 0) { //20, same as the JDBC batch size
                    //flush a batch of inserts and release memory:
                    session.flush();
                    session.clear();
                }
            }
        }
        session.getTransaction().commit();
        System.out.println("Save to DB Success");
        session.close();
    } catch (Exception e) {
        System.err.println(e);
    }

}

From source file:com.akursat.ws.UserServiceImpl.java

@Override
public String find(String username) {
    Transaction trns = null;//from ww w  .ja  v  a  2  s . c om
    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session session = sessionFactory.openSession();
    try {
        trns = session.beginTransaction();
        Query query = session.createQuery("from Users where username=:username_param")
                .setParameter("username_param", username);
        List<Users> users = query.list();
        if (users.isEmpty()) {
            return "Empty";
        } else if (users.size() == 1) {
            return users.get(0).getEmail() + users.get(0).getBirthday() + users.get(0).getSex();
        }
        session.getTransaction().commit();
        sessionFactory.close();

    } catch (RuntimeException e) {
        if (trns != null) {
            trns.rollback();
        }
        e.printStackTrace();
    } finally {
        session.flush();
        session.close();
    }
    return "";
}

From source file:com.akursat.ws.UserServiceImpl.java

@Override
public void createUser(String username, String email, String password, Date birthday, Short sex) {
    Transaction trns = null;/*from w  ww  . j  a v  a 2 s. c  o m*/
    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session session = sessionFactory.openSession();
    try {
        trns = session.beginTransaction();
        if (find(username) != null) {
            System.out.println("User already exist!");
        } else {
            Users u = new Users();
            u.setUsername(username);
            u.setEmail(email);
            u.setBirthday(birthday);
            u.setPassword(password);
            u.setSex(sex);
            session.save(u);
            session.getTransaction().commit();
        }

    } catch (RuntimeException e) {
        if (trns != null) {
            trns.rollback();
        }
        e.printStackTrace();
    } finally {
        session.flush();
        session.close();
    }
}

From source file:com.akursat.ws.UserServiceImpl.java

@Override
public void deleteUser(String username) {
    Transaction trns = null;//from w ww. jav  a  2  s  .c  o  m
    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session session = sessionFactory.openSession();
    try {
        trns = session.beginTransaction();
        Query query = session.createQuery("delete Users where username = :username_param");
        query.setParameter("username_param", username);
        int result = query.executeUpdate();
        session.getTransaction().commit();
        System.out.println((result == 1 ? "User deleted." : "Fail!"));
    } catch (RuntimeException e) {
        if (trns != null) {
            trns.rollback();
        }
        e.printStackTrace();
    } finally {
        session.flush();
        session.close();
    }

}

From source file:com.akursat.ws.UserServiceImpl.java

@Override
public void updateUser(String username, String email) {
    Transaction trns = null;/*from  w  ww .  j ava 2s  .  co  m*/
    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session session = sessionFactory.openSession();
    try {
        trns = session.beginTransaction();
        Query query = session
                .createQuery("update Users set email = :email_param where username = :username_param ");
        query.setParameter("email_param", email);
        query.setParameter("username_param", username);
        int result = query.executeUpdate();
        session.getTransaction().commit();
        System.out.println((result == 1 ? "User updated." : "Fail!"));
    } catch (RuntimeException e) {
        if (trns != null) {
            trns.rollback();
        }
        e.printStackTrace();
    } finally {
        session.flush();
        session.close();
    }
}

From source file:com.alejandro.modelo.ModeloImagen.java

public static void delete(String id) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();/*from ww w.j a  v a  2 s .  c  om*/

    Imagen p = (Imagen) session.load(Imagen.class, Integer.parseInt(id));
    session.delete(p);

    session.getTransaction().commit();
    session.flush();
    session.close();
}

From source file:com.alejandro.modelo.ModeloImagen.java

public static void insert(Imagen p) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();/*from ww w  .j  a  v  a 2s  . c  o m*/

    session.save(p);

    session.getTransaction().commit();
    session.flush();
    session.close();
}