jb

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

What is a Functional interface in Java 8?

A Functional interface in Java is an interface that has exactly one abstract method. It can have default methods with implementation. A default method is not abstract. In Java 8, java.lang.Runnable and java.util.concurrent.Callable are two very popular Functional interfaces.

What is a Single Abstract Method (SAM) interface in Java 8?

A Functional interface is also known as Single Abstract Method Interface, since it has exactly one abstract method.

What is the first level of cache in Hibernate?

A Hibernate Session is the first level of cache for persistent data in a transaction. The second level of cache is at JVM or SessionFactory level.

. What is the data type of a Lambda expression?

A Lambda expression fulfills the purpose of passing code as data. The data type of a Lambda expression is a Functional interface. In most of the cases this is java.lang.Runnable interface.

What is the purpose of a Static method in an Interface in Java 8?

A Static method in an Interface is utility or helper method. This is not an object level instance method. Some of the uses of Static method in an Interface are: Single Class: There is no need to create a separate Utils class for storing utility or helper methods. We can keep these methods in same interface. Encapsulation: With Static methods, complete behavior of a Class is encapsulated in same class. There is no need to maintain multiple classes. Extension: It is easier to extend a Class/API. If we extend a collection ArrayList, we get all the methods. We need not extend Collections class also.

Why do we need Functional interface in Java?

Functional Interfaces are mainly used in Lambda expressions, Method reference and constructor references. In functional programming, code can be treated as data. For this purpose Lambda expressions are introduced. They can be used to pass a block of code to another method or object. Functional Interface serves as a data type for Lambda expressions. Since a Functional interface contains only one abstract method, the implementation of that method becomes the code that gets passed as an argument to another method.

What is the use of version number in Hibernate?

Version number is used in optimistic locking in Hibernate. When a transaction modifies an object, it increments its version. Based on version number, second transaction can determine if the object it has read earlier has changed or not. If the version number at the time of write is different than the version number at the time of read, then we should not commit the transaction.

How will you re-attach an object in Detached state in Hibernate?

We can call one of the methods Session.update(), Session.saveOrUpdate(), or Session.merge() to re-attach an object in detached state with another session in Hibernate.

. What is the meaning of following lambda expression?

( e -> System.out.println( e ) ); This Lambda expression takes a parameter e and prints it via System.out.

What are the main differences between an interface with default method and an abstract class in Java 8?

An interface with a default method appears same as an Abstract class in Java. But there are subtle differences between two. Instance variable: An interface cannot have instance variables. An abstract class can have instance variables. Constructor: An interface cannot have a constructor. An abstract class can have constructor. Concrete Method: An interface cannot have concrete methods other than default method. An abstract class is allowed to define concrete methods with implementation. Lambda: An interface with exactly one default method can be used for lambda expression. An abstract class cannot be used for lambda expression.

What is the Detached state of an object in Hibernate?

An object is in detached state if it was persistent earlier but its Session is closed now. Any reference to this object is still valid. We can even update this object. Later on we can even attach an object in detached state to a new session and make it persistent. Detached state is very useful in application transactions where a user takes some time to finish the work.

. When should we use get() method or load() method in Hibernate?

As a thumb rule we can follow these guidelines: We should use get() method when we want to load an object. We should use load() method when we need a reference to an object without running extra SQL queries.

Can we provide implementation of a method in a Java Interface

Before Java 8, it was not allowed to provide implementation of a method in an Interface. Java 8 has introduced the flexibility of providing implementation of a method in an interface. There are two options for that: Default Method: We can give default implementation of a method. Static Method: We can create a static method in an interface and provide implementation.

What is the purpose of Callback interface in Hibernate?

Callback interface in Hibernate is mainly used for receiving notifications of different events from an object. Eg. We can use Callback to get the notification when an object is loaded into or removed from database.

What is the purpose of Configuration Interface in Hibernate?

Configuration interface can be implemented in an application to specify the properties and mapping documents for creating a SessionFactory in Hibernate. By default, a new instance of Configuration uses properties mentioned in hibernate.properties file. Configuration is mainly an initialization time object that loads the properties in helps in creating SessionFactory with these properties. In short, Configuration interface is used for configuring Hibernate framework in an application.

. What is Criteria API in Hibernate?

Criteria is a simplified API in Hibernate to get entities from database by creating Criterion objects. It is a very intuitive and convenient approach for search features. Users can specify different criteria for searching entities and Criteria API can handle these. Criterion instances are obtained through factory methods on Restrictions.

Why do we need Default method in a Java 8 Interface?

Default methods in an Interface provide backward compatibility feature in Java 8. Let say there is an interface Car that is implemented by BMW, Chevrolet and Toyota classes. Now a Car needs to add capability for flying. It will require change in Car interface. Some of the car classes that do not have flying capability may fail. Therefore a Default Implementation of flying methods is added in Car interface so that cars with no flying capability can continue to implement the original Car interface.

What is the use of Dirty Checking in Hibernate?

Dirty Checking is very useful feature of Hibernate for write to database operations. Hibernate monitors all the persistent objects for any changes. It can detect if an object has been modified or not. By Dirty Checking, only those fields of an object are updated that require any change in them. It reduces the time-consuming database write operations.

. What are the different fetching strategies in Hibernate?

Hibernate 3 onwards there are following fetching strategies to retrieve associated objects: Join fetching: In Join strategy Hibernate uses OUTER join to retrieve the associated instance or collection in the same SELECT. Select fetching: In Select strategy, Hibernate uses a second SELECT to retrieve the associated entity or collection. We can explicitly disable lazy fetching by specifying lazy="false". By default lazy fetching is true. Subselect fetching: In Subselect strategy, Hibernate uses a second SELECT to retrieve the associated collections for all entities retrieved in a previous query or fetch. Batch fetching: In Batch strategy, Hibernate uses a single SELECT to retrieve a batch of entity instances or collections by specifying a list of primary or foreign keys. This is a very good performance optimization strategy for select fetching.

What is Hibernate Query Language (HQL)?

Hibernate Query Language is also known as HQL. It is an Object Oriented language. But it is similar to SQL. HQL works well with persistent objects and their properties. HQL does not work on database tables. HQL queries are translated into native SQL queries specific to a database. HQL supports direct running of native SQL queries also. But it creates an issue in Database portability.

What are the key characteristics of Hibernate?

Hibernate has following key characteristics: Object/Relational Mapping (ORM): Hibernate provides ORM capabilities to developers. So then can write code in Object model for connecting with data in Relational model. JPA Provider: Hibernate provides an excellent implementation of Java Persistence API (JPA) specification. Idiomatic persistence: Hibernate provides persistence based on natural Object-oriented idioms with full support for inheritance, polymorphism, association, composition, and the Java collections framework. It can work with any data for persistence. High Performance: Hibernate provides high level of performance supporting features like- lazy initialization, multiple fetching strategies, optimistic locking etc. Hibernate does not need its own database tables or fields. It can generate SQL at system initialization to provide better performance at runtime. Scalability: Hibernate works well in multi server clusters. It has built in scalability support. It can work well for small projects as well as for large business software. Reliable: Hibernate very reliable and stable framework. This is the reason for its worldwide acceptance and popularity among developer community. Extensible: Hibernate is quite generic in nature. It can be configured and extended as per the use case of application.

What is Hibernate framework?

Hibernate is a popular Object Relational Mapping (ORM) framework of Java. It helps in mapping the Object Oriented Domain model to Relational Database tables. Hibernate is a free software distributed under GNU license. Hibernate also provides implementation of Java Persistence API (JPA). In simple words, it is a framework to retrieve and store data from database tables from Java.

What is Query Cache in Hibernate?

Hibernate provides Query Cache to improve the performance of queries that run multiple times with same parameters. At times Query Caching can reduce the performance of Transactional processing. By default Query Cache is disabled in Hibernate. It has to be used based on the benefits gained by it in performance of the queries in an application.

How will you order the results returned by a Criteria in Hibernate?

Hibernate provides an Order criterion that can be used to order the results. This can be order objects based on their property in ascending or descending order. Class is org.hibernate.criterion.Order. One example is as follows: Eg. List employees = session.createCriteria(Employee.class) .add( Restrictions.like("name", "F%") .addOrder( Order.asc("name") ) .addOrder( Order.desc("age") ) .setMaxResults(10) .list();

. What are the different strategies for cache mapping in Hibernate?

Hibernate provides following strategies for cache mapping: Read only: If an application requires caching only for read but not for write operations, then we can use this strategy. It is very simple to use and give very good performance benefit. It is also safe to use in a cluster environment. Read/Write: If an application also needs caching for write operations, then we use Read/Write strategy. Read/write cache strategy should not be used if there is requirement for serializable transaction isolation level. If we want to use it in a cluster environment, we need to implement locking mechanism. Nonstrict Read/Write: If an application only occasionally updates the data, then we can use this strategy. It cannot be used in systems with serializable transaction isolation level requirement. Transactional: This strategy supports full transactional cache providers like JBoss TreeCache.

What are the different types of collections supported by Hibernate?

Hibernate supports following two types of collections: Indexed Collections: List and Maps Sorted Collections: java.util.SortedMap and java.util.SortedSet

. How can we get statistics of a SessionFactory in Hibernate?

In Hibernate we can get the statistics of a SessionFactory by using Statistics interface. We can get information like Close Statement count, Collection Fetch count, Collection Load count, Entity insert count etc.

How does Transaction management work in Hibernate?

In Hibernate we use Session interface to get a new transaction. Once we get the transaction we can run business operations in that transaction. At the end of successful business operations, we commit the transaction. In case of failure, we rollback the transaction. Sample code is a follows: Session s = null; Transaction trans = null; try { s = sessionFactory.openSession(); trans = s.beginTransaction(); doTheAction(s); trans.commit(); } catch (RuntimeException exc) { trans.rollback(); } finally { s.close(); }

How can we mark an entity/collection as immutable in Hibernate?

In Hibernate, by default an entity or collection is mutable. We can add, delete or update an entity/collection. To mark an entity/collection as immutable, we can use one of the following: @Immutable: We can use the annotation @Immutable to mark an entity/collection immutable. XML file: We can also set the property mutable=false in the XML file for an entity to make it immutable.

. Which is the default transaction factory in Hibernate?

In Hibernate, default transaction factory is JDBCTransactionFactory. But we can change it by setting the property hibernate.transaction.factory_class.

What is the difference between load() and get() method in Hibernate?

In Hibernate, load() and get() methods are quite similar in functionality. The main difference is that load() method will throw an ObjectNotFoundException if row corresponding to an object is not found in the database. On the other hand, get() method returns null value when an object is not found in the database. It is recommended that we should use load() method only when we are sure that object exists in database.

How does Example criterion work in Hibernate?

In Hibernate, we can create an object with desired properties. Then we can use this object to search for objects with similar object. For this we can use org.hibernate.criterion.Example criterion. Egg. First we create a sample book object of author Richard and category mystery. Then we search for similar books. Book book = new Book(); book.setAuthor('Richard'); book.setCategory(Category.MYSTERY); List results = session.createCriteria(Book.class) .add( Example.create(book) ) .list();

What are the different second level caches available in Hibernate?

In Hibernate, we can use different cache providers for implementing second level cache at JVM/SessionFactory level. Some of these are: Hashtable EHCache OSCache SwarmCache JBoss Cache 1.x JBoss Cache 2

What are the different options to retrieve an object from database in Hibernate?

In Hibernate, we can use one of the following options to retrieve objects from database: Identifier: We can use load() or get() method and pass the identifier like primary key to fetch an object from database. HQL: We can create a HQL query and get the object after executing the query. Criteria API: We can use Criteria API to create the search conditions for getting the objects from database. Native SQL: We can write native SQL query for a database and just execute it to get the data we want and convert it into desired object.

How can we get current time by using Date/Time API of Java 8?

In Java 8 we can use Clock class to get the current time. Instead of using old method System.currentTimeMillis(), we can create a Clock object and call millis() method to get the current time in milliseconds. We can also call instant() method on Clock object to get the current time in a readable format.

What are the new JVM arguments introduced by Java 8?

In Java 8, PermGen space of ClassLoader is removed. It has been replaced with MetaSpace. Now we can set the initial and maximum size of MetaSpace. The JVM options -XX:PermSize and -XX:MaxPermSize are replaced by -XX:MetaSpaceSize and -XX:MaxMetaspaceSize respectively in Java 8.

What is a Default Method in an Interface?

In Java 8, we can provide implementation of a method in an Interface and mark this method with Default keyword. In this way, this implementation of the method becomes default behavior for any class implementing the interface.

How Java 8 supports Multiple Inheritance?

In Multiple Inheritance a class can inherit behavior from more than one parent classes. Prior to Java 8, a class can implement multiple interfaces but extend only one class. In Java 8, we can have method implementation within an interface. So an interface behaves like an Abstract class. Now if we implement more than one interface with method implementation in a class, it means we are inheriting behavior from multiple abstract classes. That is how we get Multiple Inheritance in Java 8.

If we create same method and define it in a class , in its parent class and in an interface implemented by the class, then definition will be invoked if we access it using the reference of Interface and the object of class?

In all the cases, method defined in the class will be invoked

Which method in Optional provides the fallback mechanism in case of null value?

In case, an Optional has null value, we can use orElseGet() method as fallback mechanism. If we implement orElseGet() method, it will be invoked when the value of Optional is null.

In case we create a class that extends a base class and implements an interface. If both base class and interface have a default method with same name and arguments, then which definition will be picked by JVM?

In such a scenario, JVM will pick the definition in base class.

What is Optional in Java 8?

Optional is a container object that may have a null or non-null value. If it has a value then isPresent() method returns true. It a value is present, we can call get() method to get the value. Else we will get nothing. It is very useful in handling data that has null values.

How can we analyze the dependencies in Java classes and packages?

Java 8 comes with a new command line tool jdeps that can help in analyzing the package-level and class-level dependencies. We can pass a jar file name or a class name as an argument to this tool. It will list all the dependencies of that jar or class.

How can you get the name of Parameter in Java by using Reflection?

Java 8 has introduced a method Parameter.getName() to get the name of a parameter by using reflection. Before using this feature, we need to turn on this feature in Java compiler. To turn on this feature, just run javac with -parameters argument. To verify the availability of this feature, we can use Parameter. isNamePresent() method.

What is a Lambda expression in Java 8?

Lambda expression is an anonymous function. It is like a method that does not need any access modifiers, name or return value declaration. It accepts a set of input parameters and returns result. Lambda expression can be passed as a parameter in a method. So we can treat code in Lambda expression as data. This piece of code can be passed to other objects and methods.

In Hibernate, how can an object go in Detached state?

Once the session attached to an Object is closed, the object goes into Detached state. An Object in Detached state can be attached to another session at a later point of time. This state is quite useful in concurrent applications that have long unit of work.

What are the advantages of Hibernate framework over JDBC?

Main advantages of Hibernate over JDBC are as follows: Database Portability: Hibernate can be used with multiple types of database with easy portability. In JDBC, developer has to write database specific native queries. These native queries can reduce the database portability of the code. Connection Pool: Hibernate handles connection pooling very well. JDBC requires connection pooling to be defined by developer. Complexity: Hibernate handles complex query scenarios very well with its internal API like Criteria. So developer need not gain expertise in writing complex SQL queries. In JDBC application developer writes most of the queries.

What are the differences between Collection and Stream API in Java 8?

Main differences between Collection and Stream API in Java 8 are: Version: Collection API is in use since Java 1.2. Stream API is recent addition to Java in version 8. Usage: Collection API is used for storing data in different kinds of data structures. Stream API is used for computation of data on a large set of Objects. Finite: With Collection API we can store a finite number of elements in a data structure. With Stream API, we can handle streams of data that can contain infinite number of elements. Eager vs. Lazy: Collection API constructs objects in an eager manner. Stream API creates objects in a lazy manner. Multiple consumption: Most of the Collection APIs support iteration and consumption of elements multiple times. With Stream API we can consume or iterate elements only once.

What are the differences between Intermediate and Terminal Operations in Java 8 Streams?

Main differences between Intermediate and Terminal Stream operations are as follows: Evaluation: Intermediate operations are not evaluated until we chain it with a Terminal Operation of Stream. Terminal Operations can be independently evaluated. Output: The output of Intermediate Operations is another Stream. The output of Terminal Operations is not a Stream. Lazy: Intermediate Operations are evaluated in lazy manner. Terminal Operations are evaluated in eager manner. Chaining: We can chain multiple Intermediate Operations in a Stream. Terminal Operations cannot be chained multiple times. Multiple: There can be multiple Intermediate operations in a Stream operation. There can be only one Terminal operation in Stream processing statement.

What are the main uses of Stream API in Java 8?

Main uses of Stream API in Java 8 are: It helps in using data in a declarative way. We can make use of Database functions like Max, Min etc., without running a full iteration. It makes good use of multi-core architectures without worrying about multi-threading code. We can create a pipeline of data operations with Java Stream that can run in a sequence or in parallel. It provides support for group by, order by etc. operations. It supports writing for code in Functional programming style. It provides parallel processing of data.

Can we access a static method of an interface by using reference of the interface?

No, a static method of interface has to be invoked by using the name of the interface.

Can we create a class that implements two Interfaces with default methods of same name and signature?

No, it is not allowed to create a class that implements interfaces with same name default methods. It will give us compile time error for duplicate default methods.

Is it mandatory to use @FunctionalInterface annotation to define a Functional interface in Java 8?

No, it is not mandatory to mark a Functional interface with @FunctionalInterface annotation. Java does not impose this rule. But, if we mark an interface with @FunctionalInterface annotation then Java Compiler will give us error in case we define more than one abstract method inside that interface.

Is it possible to have default method definition in an interface without marking it with default keyword?

No, we have to always mark a default method in interface with default keyword. If we create a method with implementation in an interface, but do not mark it as default, then we will get compile time error.

. What is an Object Relational Mapping (ORM)?

Object Relational Mapping (ORM) is a programming technique to map data from a relational database to Object oriented domain model. This is the core of Hibernate framework. In case of Java, most of the software is based on OOPS design. But the data stored in Database is based on Relation Database Management System (RDBMS). ORM helps in data retrieval in an Object Oriented way from an RDBMS. It reduces the effort of developers in writing queries to access and insert data.

. Why do we use POJO in Hibernate?

POJO stands for Plain Old Java Objects. A POJO is java bean with getter and setter methods for each property of the bean. It is a simple class that encapsulates an object's properties and provides access through setters and getters. Some of the reasons for using POJO in Hibernate are: POJO emphasizes the fact that this class is a simple Java class, not a heavy class like EJB. POJO is a well-constructed class, so it works well with Hibernate proxies.

What is the difference between session.save() and session.saveOrUpdate() methods in Hibernate?

Save method first stores an object in the database. Then it persists the given transient instance by assigning a generated identifier. Finally, it returns the id of the entity that is just created. SaveOrUpdate() method calls either save() or update() method. It selects one of these methods based on the existence of identifier. If an identifier exists for the entity then update() method is called. If there is no identifier for the entity then save() method is called as mentioned earlier.

What is the use of session.lock() method in Hibernate?

Session.lock() is a deprecated method in Hibernate. We should not use it. Instead we should call buildLockRequest(LockMode).lock(entityName, object) method in Hibernate.

What are the popular annotations introduced in Java 8?

Some of the popular annotations introduced in Java 8 are: @FunctionalInterface: This annotation is used to mark an interface as Functional Interface. As mentioned earlier, A FunctionalInterface can be used for lambda expressions. @Repeatable: This annotation is used for marking another annotation. It indicates that the marked annotation can be applied multiple times on a type.

What are the uses of Optional?

Some of the uses of Optional in Java are: We can use Optional to avoid NullPointerException in an application. Optional performs Null check at compile time, so we do not get run time exception for a null value. Optional reduces the codebase pollution by removing unnecessary null checks. Optional can also be used to handle default case for data when a value is null.

What are the steps for creating a SessionFactory in Hibernate?

Steps to create a SessionFactory in Hibernate are: Configuration: First create a Configuration object. This will refer to the path of configuration file. Resource: Add config file resource to Configuration object. Properties: Set properties in the Configuration object. SessionFactory: Use Configuration object to build SessionFactory.

Can you tell us about the core interfaces of Hibernate framework?

The core interfaces of Hibernate framework are as follows: Configuration: Configuration interface can be implemented in an application to specify the properties and mapping documents for creating a SessionFactory in Hibernate. Hibernate application bootstraps by using this interface. SessionFactory: In Hibernate, SessionFactory is used to create and manage Sessions. Generally, there is one SessionFactory created for one database. It is a thread-safe interface that works well in multi-threaded applications. Session: Session is a lightweight object that is used at runtime between a Java application and Hibernate. It contains methods to create, read and delete operations for entity classes. It is a basic class that abstracts the concept of persistence. Transaction: This is an optional interface. It is a short lived object that is used for encapsulating the overall work based on unit of work design pattern. A Session can have multiple Transactions. Query: This interface encapsulates the behavior of an object-oriented query in Hibernate. It can accept parameters and execute the queries to fetch results. Same query can be executed multiple times. Criteria: This is a simplified API to retrieve objects by creating Criterion objects. It is very easy to use for creating Search like features.

What are the main benefits of new features introduced in Java 8?

The main benefits of Java 8 features are: Support for functional programming by Lambda and Streams Ease of high volume data processing by Streams Ease of use by getting Parameter names through Reflection Reusable code with enhanced Collection APIs Smart exception handling with Optional Control on JVM with new Parameters Enhanced encryption support with Base 64 Faster execution with Nashorn JavaScript engine support

Why did Oracle release a new version of Java like Java 8?

The main theme of Java 8 is support for functional programming. With increase in Database size and growth of multi-code CPU servers, there is need for Java to support such large-scale systems. With new features of Java 8, it is possible to create functional programs to interact efficiently with Big Data systems. Support for Streams is very helpful in this regard. Lambda expressions are very useful for cloud computing where we can pass code as data and run the same code on multiple servers. Optional is a best practice that is borrowed from Google Guava library for handling the exceptional cases. This has made programs more robust with support for edge cases.

. What are the new features released in Java 8?

The new features released in Java 8 are: Lambda Expression Stream API Date and Time API Functional Interface Interface Default and Static Methods Optional Base64 Encoding and Decoding Nashorn JavaScript Engine Collections API Enhancements Concurrency Enhancements Fork/Join Framework Enhancements Spliterator Internal Iteration Type Annotations and Repeatable Annotations Method Parameter Reflection JVM Parameter Changes

What are the differences between Predicate, Supplier and Consumer in Java 8?

The subtle difference between Predicate, Supplier and Consumer in Java 8 is as follows: Predicate is an anonymous function that accepts one argument and returns a result. Supplier is an anonymous function that accepts no argument and returns a result. Consumer is an anonymous function that accepts one argument and returns no result.

What is the target type of a lambda expression ?

The target type of a lambda expression represents a type to which the expression can be converted. The target type for a lambda expression is a functional interface. The lambda expression must have same parameter type as the parameter in the function of the interface. It must also return a type compatible with the return type of function.

What is the type of a Lambda expression in Java 8?

The type of a lambda expression depends on the context it is being used. A lambda is like a method reference. It does not have a type of its own. Generally, a Lambda is an instance of a Functional Interface.

What are the core ideas behind the Date/Time API of Java 8?

There are three core ideas behind the Date/Time API of Java 8: Immutable-value classes: The new API avoids thread-safety and concurrency issues by ensuring that all the core classes are immutable and represent well-defined values. Domain-driven design: The new API is modeled on precise domain with classes that represent different use cases for Date and Time. The emphasis on domain-driven design offers benefits like clarity and understandability. Separation of chronologies: The new API allows people to work with different calendar systems. It supports the needs of users in different areas of the world likes Japan or Thailand that don't follow ISO-8601.

. What are the two locking strategies in Hibernate?

There are two popular locking strategies that can be used in Hibernate: Optimistic: In Optimistic locking we assume that multiple transactions can complete without affecting each other. So we let the transactions do their work without locking the resources initially. Just before the commit, we check if any of the resource has changed by another transaction, then we throw exception and rollback the transaction. Pessimistic: In Pessimistic locking we assume that concurrent transactions will conflict while working with same resources. So a transaction has to first obtain lock on the resources it wants to update. The other transaction can proceed with same resource only after the lock has been released by previous transaction.

What are the options to disable second level cache in Hibernate?

This is a trick question. By default Second level cache is already disabled in Hibernate. In case, your project is using a second level cache you can use one of the following options to disable second level cache in Hibernate: We can set hibernate.cache.use_second_level_cache to false. We can use CacheMode.IGNORE to stop interaction between the session and second-level cache. Session will interact with cache only to invalidate cache items when updates occur

What are the three main parts of a Lambda expression in Java?

Three main parts of a Lambda expression are: Parameter list: A Lambda expression can have zero or more parameters. Parameter list is optional to Lambda. Lambda arrow operator: "->" is known as Lambda arrow operator. It separates the list of parameters and the body of Lambda. Lambda expression body: The piece of code that we want to execute is written in Lambda expression body. E.g. In following example: Arrays.asList( "a", "b", "d" ).forEach( e -> System.out.println( e ) ); Parameter list = e Arrow = -> Body = System.out.println( e )

How can we define a Functional interface in Java 8?

To define a Functional interface in Java 8, we can create an Interface with exactly one abstract method. Another way is to mark an Interface with annotation @FunctionalInterface. Even with the annotation we have to follow the rule of exactly one abstract method. The only exception to this rule is that if we override java.lang.Object class's method as an abstract method, then it does not count as an abstract method.

How can you see SQL code generated by Hibernate on console?

To display the SQL generated by Hibernate, we have to turn on the show_sql flag. This can be done in Hibernate configuration as follows: <property name="show_sql">true</property>

How will you map the columns of a DB table to the properties of a Java class in Hibernate?

We can map the class properties and table columns by using one of the two ways: XML: We can map the column of a table to the property of a class in XML file. It is generally with extension hbm.xml Annotation: We can also use annotations @Entity and @Table to map a column to the property of a class.

.What are the advantages of a lambda expression

We can pass a lambda expression as an object to a method. This reduces the overhead involved in passing an anonymous class. We can also pass a method as a parameter to another method using lambda expressions.

How can we check if an Object is in Persistent, Detached or Transient state in Hibernate?

We can use following methods to check the state of an object in Hibernate: Persistent State: If call to EntityManager.contains(object) returns true, the object is in Persistent state. Detached State: If the call to PersistenceUnitUtil.getIdentifier(object) returns identifier property then the object is in detached state. Transient State: If call to PersistenceUnitUtil.getIdentifier(object) returns null then object is in Transient state. We can get access to PersistenceUnitUtil from the EntityManagerFactory in Hibernate.

. How can we monitor the performance of Hibernate in an application?

We can use following ways to monitor Hibernate performance: Monitoring SessionFactory: Since there is one SessionFactory in an application, we can collect the statistics of a SessionFactory to monitor the performance. Hibernate provides sessionFactory.getStatistics() method to get the statistics of SessionFactory. Hibernate can also use JMX to publish metrics. Metrics: In Hibernate we can also collect other metrics like- number of open sessions, retrieved JDBC connections, cache hit, miss etc. These metrics give great insight into the performance of Hibernate. We can tune Hibernate settings and strategies based on these metrics.

How can we auto-generate primary key in Hibernate?

We can use the primary key generation strategy of type GenerationType.AUTO to auto-generate primary key while persisting an object in Hibernate. Eg. @Id @GeneratedValue(strategy=GenerationType.AUTO) private int id; We can leave it null/0 while persisting and Hibernate automatically generates a primary key for us. Sometimes, AUTO strategy refers to a SEQUENCE instead of an IDENTITY .

What is the Transient state of an object in Hibernate?

When an object is just instantiated using the new operator but is not associated with a Hibernate Session, then the object is in Transient state. In Transient state, object does not have a persistent representation in database. Also there is no identifier assigned to an object in Transient state. An object in Transient state can be garbage collected if there is no reference pointing to it.

Is it possible to define a static method in an Interface?

Yes, from Java 8, an Interface can also has a static method.


Set pelajaran terkait

143 FINAL - Mod 6: Neuro (PRACTICE QUESTIONS)

View Set

PSY 100 LearningCurve: 13a. Classic Perspectives on Personality

View Set

Chapter 7: Networks: Mobile Business

View Set

Lesson 2: Introduction to Construction Technolog Exam

View Set

MACROECONOMICS FINAL- HOMEWORK 1-6

View Set

Principles of Marketing Exam Review

View Set

disease prevention & control unit 2

View Set