Posts

Showing posts from November, 2019

Java 9 Stream API iterate method example

Another improvement made by Java 9 is adding a new Stream.iterate method. This is a new feature in Java 9 Stream API. Java 8 Stream.iterate Prior to Java 9, The Stream Interface already had an iterate method. The Stream.iterate is a static method on the Stream interface. You can use it to create a new Stream. It accepts the following parameters: Initial Value UnaryOperator instance which is used to find subsequent values. It returns a Stream instance. The following code demonstrates this method: Stream<Integer> numberStream = Stream.iterate(2, num -> num+2).limit(10);numberStream.forEach(System.out::println); This code uses an initial value of 2. Also, the UnaryOperator is implemented via a lambda expression that simply increments the previous value by 2. Note that the Stream.iterate method returns an infinite Stream. So the code uses the limit method to terminate the Stream. So this code prints the following output: 2468101214161820 Java 9 Stream.iterate Java 9 has added an o

How Hibernate SessionFactory works

In this article, I will be explaining what is Hibernate SessionFactory and how it works. Consider the following code that demonstrates a typical Hibernate application: SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();Session session = sessionFactory.openSession();Transaction tx = session.beginTransaction();session.save(person);tx.commit();session.close();sessionFactory.close();   This code first creates a  SessionFactory object.  The sessionFactory contains all the data in the hibernate configuration file. The code uses the Configuration class to create the SessionFactory instance. The configuration.configure method reads the hibernate.cfg.xml file and sets up the Configuation object using the properties in this file. The buildSessionFactory method builds the sessionFactory object using this configuration data. The SessionFactory object is usually created only once at the start of the application and kept for later use. The SessionFactory cor