Leonardo Campos

Author Archives: Leonardo Campos

JPA interview questions and answers

I remember the days when I would write SQL commands directly on ASP pages. Yeah, what a shame. Then with Java, I started using DAOs to isolate all that tedious and somewhat messy code to deal with databases. But those were the old days. Not so recently, ORM technologies gained a lot of traction, and persistence was made much easier. JPA, which is an ORM, removes so much hassle from programming persistence code that I consider it to be of great importance. That’s why I believe it is important to prepare yourself with some key JPA interview questions and answers for your next interview for a Java Developer Position.

Question: What is JPA?

About the question: This is such an important topic and such a basic question that I would consider it a very very bad sign if a candidate couldn’t answer this question at least at a basic level.

Answer: JPA stands for Java Persistence API. It is a specification on how Java should support the mapping between objects and relational databases for persistence, which is called ORM (Object Relational Mapping). It can be seen as a framework for persistence that is very lightweight and based on POJOs.

Several vendors provide implementations for the JPA. The candidate should be able to point a few, like Hibernate, Toplink, Eclipselink and Apache OpenJPA.

The Impedance Mismatch

A term that I like is “The Impedance Mismatch”, which I first came across in the excellent “Pro JPA 2”, from Mike Keith. It describes the difference between the relational and the object oriented models and the hard times one gets to try to bridge this gap. By the way, using these kinds of terms is positive in an interview ;-).

Please explain the concept of POJO Persistence in JPA?

About the question: This is a question that I would use to assess the candidate’s level of understanding about JPA in order to select my next questions.

Answer: Historically, many frameworks and tools used for persistence in Java required that classes would extend some abstract class or interface or would impose some other very intrusive requirement.

POJO Persistence is about being able to make any Plain Old Java Object persistent in a non-intrusive way. This is made possible in JPA because it adopts a metadata-driven approach. This metadata can be very easily set using annotations in your POJOS or can be set externally using XML.

What is the EntityManager in JPA?

Answer: JPA is said to be “non-intrusive” but not “transparent persistence”. This means the entities don’t persist themselves magically. There is a need for an API which provides operations to persist and retrieve objects from the database. This is the reason of the EntityManager to exist, its “râison-dêtre”. EntityManager is the main API to provide methods to persist or retrieve data, methods such as persist or find.

The way to obtain an instance of the EntityManager is through an EntityManagerFactory or have it injected for you if you are using the Enterprise Edition.

Check these links to learn more:

Take a look at our question about Persistent Context as well.

What is a Persistent Context in JPA

Answer: Persistent objects are the ones being managed by the EntityManager. The Persistent Context is a set of entity instances being managed by the EntityManager. The identity is used to determine the uniqueness within the set because only one instance of an entity can exist within a Persistent context.

Check these links to learn more:

Could you please explain the concept of Entity in the context of JPA?

Answer: In the context of the Java Persistence API, an Entity means a POJO which has a state, can have relationships and would have its persistence to a relational database managed by some implementation of the JPA.

An Entity is an object that is persistable, it also must have a persistence identity, which means it has a primary key and a row of its own in a database table. There must be a mapping between a database table and the class, which can make extensive use of defaults to required the minimum necessary configuration.
The class can either be annotated with the @Entity annotation or be mapped in an external XML file. Another required annotation (or configuration in XML) is @Id, which marks the field or property (either the field itself or the getter method) responsible for holding the persistence identity (primary key).

Configuration by exception

This is a term you can use to refer to the fact that JPA makes extensive use of defaults, so one needs only to configure what is out of ordinary, or, in other words, configure by exception.

What is a Persistence Unit in JPA?

Answer: Persistence Unit is the configuration settings of a logical grouping of user defined persistable classes that an EntityManager is supposed to manage.

It is in a file called persistence.xml that we can describe the persistence unit. One single file can contain one or more persistence units. The persistence unit is named to create an EntityFactory. We are required to provide the Persistence Unit name in order for that configuration to be used.

More information:

What is the JPQL?

Answer: JPQL stands for Java Persistence Query Language. It is a very powerful query language, similar to SQL, to execute queries across entities and their relationships instead of directly against the data model.

You might be asking yourself why in the world would you need a Query Language given you could be writing SQL directly?
The answer is that it has two major advantages over writing SQL directly: The first one is that JPQL has an object-oriented syntax. The second one, which is kind of a consequence from the first is that JPQL is also not bound to a database schema, it uses a schema abstraction based on the object model instead of the relational one.

This code assumes you have an instance of EntityManager in the variable entityManager. Than it creates a query instance and asks for the result:

TypedQuery<Person> query = entityManager.createQuery(“SELECT p FROM Person p”, Person.class);

List<Person> people = query.getResultList();

The JPQL presents some features (not exclusive):

  • It can produce Single or Multiple value result types
  • It has aggregate functions, sorting and grouping clauses
  • Support for join, both inner and outer
  • Update and delete

What is a named query in the JPA? How to set and execute it?

Answer: In the context of JPQL, Named queries are a way to organize query definitions associating them with names. It is important to have in mind that the names must be unique within a single Persistent Unit.

There are two ways to set Named queries, either using annotation or setting them in external files.

The easiest way to set them is by using the @NamedQuery annotation in the class definition of any Entity. The only drawback is that it somehow “pollutes” the class with the queries.

@NamedQuery(name=”School.findByName”,  query=”SELECT s FROM School s WHERE s.name = :schoolName”)

The other option, the use of external file. Example (I’ve removed a lot of XML details to make the main construct clearer):

<?xml version=”1.0″ encoding=”UTF-8″?>

<entity-mappings …>

 <named-query name=”School.findByName”>

   <query>SELECT s FROM School s WHERE s.name = :schoolName</query>

 </named-query>

</entity-mappings>

And in the persistence.xml, using the “mapping-file” tag, the above file can be referenced.

To add several named queries is pretty straightforward in the external file, just add as many “named-query” tags as necessary. When using annotations, though, it is still very easy but you need to remember that the @NamedQuery annotation has to be nested within the @NamedQueries annotation:

@NamedQueries({

@NamedQuery(name=”…”,  query=”…”),

@NamedQuery(name=”…”,  query=”…”),

@NamedQuery(name=”…”,  query=”…”)

})

The last point the candidate should mention is how to execute the named query. It is necessary to invoke the instance method createNamedQuery from the EntityManager:

em.createNamedQuery(“School.findByName”, School.class).setParameter(“name”, name).getSingleResult();

if the query is expected to return more than one value, use the method .getResultList() instead of the .getSingleResult()

Some examples used were adapted from this post (in Portuguese) about named queries in external files.

What is paging and how to achieve it in JPA?

Answer: A common problem with large result sets is that they can be inefficient to display and or to load. The applications must be able to cope with this problem and a common technique is to present the data in fixed size batches called pages, the paging also provides a way to navigate the results, retrieving other pages.

Pagination is made very easy with JPA, the two interfaces related to queries, Query and TypedQuery have the methods setFirstResult() to set what is the first element of the given page and setMaxResults() to determine the page or size.

What happens if a query is executed against entities that have uncommitted changes?

Answer: One might be tempted to think that the changes that are not yet committed would not visible to the queries. This possible explanation could stem from the fact that queries are executed directly against the database, not using the internal cache.

However, the persistence provider ensures, by default, that queries can see pending transactional changes in their resultset. To have more control, both EntityManager and Query interfaces provide a way to set the flush mode, which is used by the provider to determine how to handle pending changes and queries.

The options available are AUTO (default option) and COMMIT. The first tells the provider that the pending changes should be included in the results. The second option allows the provider to just ignore uncommitted changes.

What is the Java Criteria API?

Answer:Retrieving entities is one of the most important functions of an ORM technology. For that, JPA offers two different ways to express queries, the query languages (JPQL and native SQL) and the Criteria API.

This API, part of the JPA, allows the creation of dynamic queries. One of its advantages over JPQL is that it can be validated at compile time, so problems can be discovered much earlier.

Please explain the Life cycle of an Entity within JPA

Answer: Remember an Object is considered Managed if it is associated with an Entity Manager. So, once you create an object it is considered transient (not managed by an Entity Manager and no representation in the database). If this object is persisted, it becomes managed.

There are other ways to get to a managed state, like when you retrieve objects from the database, such as using find, or when you have a detached (we are going to see this one soon) that you merge.

Detached: These are objects that are not managed by the EntityManager, but they are persisted. In other words, they have are stored in the database. These objects can return to a MANAGED state if it is merged back. The EntityManager’s merge method is invoked with the object as a parameter.

What is lazy loading in JPA?

Answer: Performance is a very important topic when loading the relationships of an Entity. Lazy loading represents a mechanism used by many ORMs, such as JPA for Java or Entity Framework for .Net to load information just when they are actually demanded.

Although the objective of Lazy Loading is to improve performance, the wrong use of Lazy or Eager strategies can significantly be detrimental to it.

The strategies JPA uses by default are almost always the best choice. Unfortunately, this is not always the case. So one should know what are the defaults and its weakness.

Lazy strategy, on the other hand, is used by default with relationships of the types one-to-many or many-to-many. This means that the relationships will not be loaded immediately with the entity, it will wait for an accessor method to be invoked, such as a getter. Once the method is invoked, it executes a query against the database to finally load the data.

Look for the code below, where School has many students, in a one-to-many relationship, therefore using Lazy Loading by default. There is a performance problem with this code:

for(School school : schools) {

for(Student student : school.getStudents(){

System.out.println(student.getID());

}

}

It will be executed in what is known as N+1 queries, which is a known problem in the using JPA. In this particular case, having an Eager strategy could have had better performance.

What are Embeddable classes? How to create them?

Answer: An Embeddable class represents part of an Entity persistent data but it does not contain a persistent identity of their own.  Instances of an embeddable class share the identity of the entity that owns it.

@Entity
public class Order {

@Id
protected long id
@Embedded
Payment payment;

}

@Embeddable
public class Payment {

private String type;
private String currency;
private double amount;

// … }

<entity-mappings>

<entity class=”techcareersource.jpa.Order”>

<attributes>

          


</attributes>

</entity>

</entity-mappings>

As we can see in the examples above, embedded objects can be either specified in XML using the embedded element or it can be annotated as @Embeddable and @Embedded annotations.

Check the Oracle tutorial page about Embeddable Classes.

What are Persistent Fields?

Answer: Simply put, ORM is about mapping objects to relational databases.

In the case of JPA, it does not even require that the object being mapped follow the JavaBeans convention. The fields, except public ones, can be directly mapped to a column in a table in the database.

For field access to be used, it is just a matter of annotating the one single field of the entity for JPA to use field access. The other fields become persistent by default, which means they too get mapped to columns of the same table as the Entity. If a field should not be persistent, one must either annotate it with @Transient or simply use the Java transient modifier.

What are Persistent Properties?

Answer: We’ve answered what were Persistent Fields.

Persistent properties are the mapping between setter/getter from an Object that follows the JavaBean conventions to columns on a table in a relational database.

It is required that the annotations be applied to the getter methods. The same rules about the @Transient annotation or transient modifier apply here.

Please, briefly explain Multiplicity in Entity Relationships and what are its possible types?

Answer: Entities have relationships with other entities, and a good ORM has to be possible to map these relationships to the database.

There are two important concepts related to Entity Relationships, namely Role, and Cardinality. A student has a relationship with a school, he or she plays the role of studying in that School. The cardinality refers to a number of entities exist on each side of a relationship. Let’s say that ordinarily, a student has one school, but a school has many students.

It is the cardinality of both source and target roles that are used to name the mappings.

We have, so, four types of multiplicities, that we can divide into two groups.

Single-Valued Associations

When the target role has a cardinality of one, it is about single-valued associations.

  • One-to-one:
    The cardinality on both sides of the relationship is one. This would be the case for a School with a Principal, where the School has only one person playing the role of Principal, and this person plays this role for a single School.
    In the School entity, there would be a field or property to store a Principal. The Principal probably also have a School entity field or property.
    The easiest way to signal this association is by using the @OneToOne annotation on the persistent field or property.
  • Many-to-one:
    The cardinality on the source side is many and on the target side of the relationship is one. From the perspective of a Student, the relationship with School is many to one.
    The easiest way to signal this association is by using the @ManyToOne annotation on the persistent field or property.

Collection-Valued Associations

When the source role has a cardinality of one, it is about collection-valued associations.

  • One-to-many:
    This is the case of source role having a cardinality of one and target source of many. Still, in the example of School, it has many Students or many ClassRooms.
    The easiest way to signal this association is by using the @OneToMany annotation on the persistent field or property.
  • Many-to-many:
    This is the case where both source and target roles having a cardinality of many. An example would be that each Teacher has many Students, and each Student has many Teachers.
    The easiest way to signal this association is by using the @ManyToMany annotation on the persistent field or property.

Check the Multiplicity in Entity Relationships from Oracle.

What is the difference between “@JoinColumn” and “mappedBy” Foreign Key Constraints

Imagine a relationship of one to many, like a School which has many Students.

The most common way to represent this in the database would be to use a foreign key like “schoolID” in the Students table.

If we follow this, then we would have:

@Entity

public class School {

@OneToMany(mappedBy = “student”)

private List<Student> departments;

}

@Entity

public class Student {

@ManyToOne

@JoinColumn(name = “schoolID”)

private School school;

}

The side of the relationship (considering the data scheme) that has the foreign key or the “join column”, is considered as “owner” of the relationship. It is important to understand this because the annotations are always defined on the owning side of the relationship. In our example, the Student owns the relationship, so it is in this class that the annotation @JoinColumn must be defined.

The mappedBy, on the other hand, is used in the non-owning or inverse side of the relationship.

Please explain what are Compound Primary Keys.

It is not always possible or desirable to have a single field to represent the identity of an entity. The primary key is composed of more than a single field. In the database, it means the Primary Key is composed of more than a single column.

To represent a compound primary key in an Entity it is necessary to have a separate class, called Primary Key Classes, containing the primary key fields. These classes must define the methods equals() and hashCode().

An example of the compound key might be from a Course entity, where it can be formed from the topic and the level, as CIVIL_LAW-101 and CRIMINAL_LAW-101.

What are the differences between EntityManager.merge() and EntityManager.persist()?

Answer: The merge method can both update and existing entity and insert a new one, while the persist method only inserts an entity.

The question that arises is why would one choose to use the persist method, given that merge apparently can do both saving and updating.

The main difference is in the treatment your Entity will receive after the methods are invoked.

The persist method will insert your entity and make the entity instance itself managed, while merge will either insert or update your Entity, but it makes a copy of your instance and that copy becomes managed.

The picture below should help understand what happens:

differences between EntityManager.merge() and EntityManager.persist()

Differences between EntityManager.merge() and EntityManager.persist()

There is a very good discussion about this topic on stackoverflow.

When to override “equals() & hashcode()” method in an Entity class ?

Whenever you need to have Entity objects within collections such as Set, List etc the identity of objects become an issue because once an object is in the collection, the behavior of changing its identity is probably not what you want.

Entities that represent the same Entity should be considered equal and return, therefore, the same hashcode. The most straightforward implementation would be to just use the id in the implementations of both equals() and hashcode(). The problem with this approach is that it would change identity once the object is persisted, after all, Entities in general just receive their ids upon insertion. If you implement an equals method that does something while id is null and something else after it is set, which would be a possible first solution that comes to mind, the identity of this Entity would change once it receives an id.

Like we said, identity change is very problematic for instances in collections. Hashcode should always return the same value for the same identity and collections make use of the hashes to store the items internally.

Let’s look at an example in code:

Set<School> schools = new HashSet<>();

School s = new School();

schools.add(s);

schools.contains(s); //returns true. Same hash as when inserted in set, right?

s.setID(5); //this would happen if it had been persisted

schools.contains(s); //returns false. Different hash now.

So it is fundamental that the implementation of equals() and hashCode() is valid both before and after the object is persisted.

The natural answer is to have an id generated as soon as the entity first created.

Check these references:

Explain Directionality in JPA Relationships?

Entities can have relationships with other entities. For this to happen, at least one side of the relationship must have an attribute that refers to the other entity.

If only one side knows about the relationship, then the relationship has only one direction, it is called unidirectional.

If on the other hand, both sides of the relationships have attributes pointing to each other, this relationship is called a bi-directional. In the end, a Bidirectional relationship is nothing more than a pair of unidirectional relationships.

The relationship between Student and Locker - JPA interview questions and answers

The relationship between Student and Locker

The relationship between Student and Locker can be modeled as a bi-directional one-on-one relationship.

A bi-directional role has to follow some rules (check them all at here at the Oracle’s tutorial page). The most important one to remember is that the owned side of the relationship must use the “mappedBy” element to point to the owning side (the one which contains the foreign key). Check our “What is the difference between @JoinColumn and mappedBy Foreign Key Constraints” .

What are the different types of cascade Operations for Entities?

The following are the different types of cascade operations available for Entities:

  • CascadeType.PERSIST – Triggered when the method persist from EntityManager is invoked and an Entity is persisted; The related entity will be persisted as well.
  • CascadeType.DETACH – Triggered when an entity is removed from Persistence Context. The related entity will be detached as well.
  • CascadeType.MERGE – Triggered when a change is made to an Entity, either when the transaction in which the change happened ends or when the merge() method is invoked. The related entity will be merged as well.
  • CascadeType.REFRESH – Triggered when an entity is making up-to-date by receiving information from the database; The related entity will be refreshed as well.
  • CascadeType.REMOVE – Triggered when an entity is removed from the database. The marked relationships will be removed as well.
  • CascadeType.ALL – All prior triggers will be reflected on the related entities.

More details on https://docs.oracle.com/cd/E19798-01/821-1841/bnbqm/index.html

Entity Framework Interview Questions and Answers

If you are a Software Developer you probably have used or heard about Object Relational Mapping, also known as ORMs. Entity Framework is a good example of an ORM tool and it is currently the most popular ORM in the .NET world. Made by Microsoft, it keeps growing and becoming ever more effective by the day. There are lots of topics to discuss, but we will touch some basic and advanced Entity Framework interview questions.

Question: What is an ORM?

About this question: This is a common question to assess candidate’s understanding about what they are using and why.

Answer: ORM is an abbreviation of Object Relational Mapping. In computer science it describes a technique to convert data from one type, most usually data stored in a relational database, to an object oriented type.

References:

Why should we use an ORM?

About this question: This is common question to assess the candidate’s understanding of the pros and cons of using an abstraction layer such as an ORM. This helps the interviewer to understand how experienced a candidate is. A mature developer would not only know how to use a tool or technology, but above all, why he is using it.

Answer: ORM stands for Object Relational Mapping. There are two different worlds, so to say, one is the relational and the other is the object oriented. There is a lot of work to bridge these two worlds, this is called The Impedance Mismatch. An ORM works as the bridge.

So, ORK should allow developers to communicate with data structures without writing SQL scripts, for example, or implementing ADO.NET communication, which means a lot easier life than having to do this without an ORM tool.

Pros:

  • ORM saves a lot of time because: it’s easier to update, maintain, and reuse the code;

It comes with a lot of automation (database manipulation, I18N, etc).

  • ORM library is more flexible because: It fits into the developer’s natural form of coding (it’s your language!); it abstracts the DB system, so you can change it whenever you want; it allows you to use OOP as data inheritance without a headache.

Cons:

  • You have to learn a new library;
  • ORM is an 80/20 solution, in which 80% of users require only 20% of SQL functionality. But even considering that 80% of users use only 20% of SQL features, if the system grows the chances are high that you will have to violate the abstraction somehow.

Check the first answer in this stackoverflow question for more information.

What is the Entity Framework?

About this question: This question may be asked to assess the candidate’s basic view of Entity Framework.

Answer: The Entity Framework is an ORM tool which is highly used by the .NET community to map entities from database to Object Oriented models.
Developers can map classes to tables in a database, making it much easier to deal with the data stored there.

It is also about productivity, since it eliminates the need to write SQL statements such as SELECT, INSERT, UPDATE and DELETE.

References:

What is LINQ to SQL?

About this question: This question may be asked to see candidate’s understanding of what is “LINQ to SQL” and how it works as an ORM.

Answer: “LINQ to SQL” is a component of the Visual Studio which offers infrastructure for managing relational data as objects. If converts queries written in C # or Visual Basic to dynamic SQL. It provides an interface that allows you to map the database objects generating the classes to perform the operations using the LINQ syntax. Also allows you to make changes to the objects and update the database.

Main benefits of LINQ to SQL:

  • You can program the data access code directly in Visual Basic or C #;
  • Syntax and schema checking at compile time;
  • Support for tools to create queries (IntelliSense);
  • You do not have to wait until you run to know if the query is correct. You check it at compile time.

https://msdn.microsoft.com/en-us/library/bb425822.aspx

If you want to configure your relational mapping of Entity Framework programmatically, what would you do?

About this question: This question checks how experience is the candide regarding configuring Entity.

Answer: It is highly recommended to use Code First configuration to define my models in code. Code first is an approach that enables you to describe a model programmatically. It is also interesting to point to the fact it is configured by exception, which means several conventions and defaults are at play.

Besides Code First, these are steps you should follow:

If you want to create a relational mapping configuration inside Designer which technique would you use?

About this question:  This question depends on candidate’s understanding of several ways of configuring the EF.

Answer: The Model First technique is the most indicated approach if database does not exists or Database First technique if database has been already created.

What is currently the latest version of Entity Framework?

About this question: This is a common question to assess how much the candidate is following the trends of the technology that they are using and how passionate they are to learn new things.

Answer: There are two versions of the Entity Framework: Entity Framework Core and Entity Framework 6.x.

Entity Framework 6.x (EF6.x) is a relatively mature, stable, and tested data access technology. EF6.x remains a supported product and will continue to see bug fixes and minor improvements for some time.

Entity Framework Core (EF Core) is a lightweight, extensible, cross-platform version of the Entity Framework. EF Core introduces many enhancements and new features when compared to EF6.x. At the same time, EF Core is a new code base and a new product.

EF Core maintains the EF6.x developer experience and most high-end APIs remain the same, so EF Core will look very familiar to anyone who has ever used EF6.x.

Check more information on the EF Core vs EF 6 comparison offered by microsoft.

Which are the pros and cons of the new Entity Framework Core 1.0?

Answer:

The main pros:

  • it allows one to execute code on Linux and MacOS environments.
  • it can work with NOSQL Databases.

The main cons:

  • it does not provide Lazy loading
  • It does not support stored procedures
  • no graphical modeling tools supported.

Check this stackoverflow example for more information.

What is lazy loading in Entity Framework?

Answer: Lazy loading is the mechanism used by Entity Framework to load information on demand. This mechanism makes the entities lighter because their associations are loaded only when the method that makes the associative data available is invoked. It means that when objects are returned by a query, related objects are not loaded at the same time, instead they are loaded automatically when the navigation property is accessed.

https://msdn.microsoft.com/en-us/library/dd456846(v=vs.110).aspx

What are the new features available in Entity Framework 6.x?

About this question: This question would depend on candidate’s understanding of new features in each new release of Entity Framework.

Answer: The main changes are:

  • asynchronous queries
  • stored procedure map
  • customizing code first conventions

Other additions can be seen in this tutorial.

Check also the post from Microsoft about Entity Framework Ninja Edition.

What is a Migrations in Entity Framework?

About this question: This question depends on candidate’s understanding of what is migrations and why we them need.

Answer: Migrations is an Entity Framework feature that allow one to have versions of the database, rollback versions and maintain a history. Migrations watches its POCO (Plain Old C# Object) classes and creates update and downgrade methods with the code needed to apply the changes. Something interesting is that one can use lambda expressions or pure SQL to change what the Migration will make.

https://msdn.microsoft.com/en-us/library/jj591621(v=vs.113).aspx

What is DbContext? What patterns are implemented by it?

About this question: The answer to this question depends on the candidate’s understanding of patterns and a deep knowledge about the Entity Framework.

Answer: DbContext is the main Entity class. It is responsible for interacting with data objects. This context class manages the entities objects at run time, which includes populating objects with data from a database, tracking changes, and persisting data to the database.

DbContext implements the Repository pattern as well as the Unit of Work pattern by default.

Check the excelente first answer for this stackoverflow question.

When would be a good idea to turn off lazy loading? How would you do it?

About this question: The answer to this question depends on the candidate’s practical understanding on how to configure Entity Framework lazy loading and why they would need it.

Answer: Sometimes Lazy Loading can lead to an excessive number of queries sent to the database, this could happen due to the fact that we do not have control over the execution of the queries that will be executed by the proxies classes.

A simple example: assuming a query is run to find cities and it returns 100 cities, each time we access the “neighborhood” property a new query is sent to the database. Thus, if we access the “neighborhoods” property of these 100 cities, 101 queries will be sent to the database (one query to return the 100 cities and 100 more queries to return the neighborhood of each county).

You could turn the lazy loading off by setting context settings property “LazyLoadingEnabled” to false.

How to resolve migrations conflicts?

About this question: This is a tough question that measures hands on past experience from the candidate working in teams, where migration conflicts can be common.

Answer: So, assuming you are in a developer position and you have found a conflict, you could:

  1. rollback your database to the state before any of the migrations.
  2. Put your database and migration at the same state as the database and migration of the other developer. That can be done by a target-specific migration.
    update-database -targetmigration:target -verbose
  3. Now, with a database that is identical to where the other left it, you should re-scaffold the migration.

For more information, check this excelente explanation given by Anders Abel.

What would happen if we try to map Entity Framework query to IQueryable model?

About this question: This question depends on understanding of what is IQueryable interface and how it works with Entity Framework.

Answer: If we execute a query in the database and we try to map it to IQueryable model, we will get a lazy loaded query inside the model, not an object oriented model. Only if we try to map our query to List or to array, EF will execute the query against the database and map it to our object oriented classes.

What is the feature of Entity splitting in Entity Framework for? Why should one use it?

Answer: The Entity splitting in Entity Framework allows one to separate properties of an object into more than a single table if necessary. It could be used to implement a better normalized database.

More detailed information can be found in the Introduction to Entity Framework from Microsoft.

Why should we use transactions? And how can we accomplish that?

About this question: This question is about the understanding of what transactions are and how one can use them with Entity Framework.

Answer: Transactions guarantee atomicity to a set of operations, i.e. either all of them will succeed, or all of them will fail. A classic example is a bank transfer, where two changes are necessary in your records:

  • reduce the balance of account A in X;
  • increase the balance of account B to X. If the first operation is performed, and soon after the system fails, your database will be inconsistent

With Entity Framework we can achieve it by using DbContext.Database.UseTransaction and DbContext.Database.BeginTransaction.

Check the transaction topic from the Microsoft introduction to Entity Framework.

How would you create a deep clone of a Dataset with the Entity Framework built in functions?

About this question: This question helps to measure how much understanding of EF built in functions the candidate has.

Answer: You can create a deep clone using the Clone method. It will create a new object with same properties and new instance.

How to change the state of an entity to remove it from database?

About this question: This question depends on practical experience of using deep state method of Entity Framework’s entities.

Answer: You could achieve it by changing the state of the entity to EntityState.Deleted. But it is not a great solution because you will not remove child elements of this entity. If that is your intention, it would much be better to use the Remove method.

Check this Microsoft Forum about this subject.

How would you call an stored procedure in a DbContext?

Answer:

DbContext API provides methods to execute database queries and commands in native SQL. The importance of these methods goes beyond the fact that they allow executing your own native queries, but they also allow one to access Stored Procedures.

So, calling a stored procedure could be achieved by calling the SqlQuery method:

DbContext.Database.SqlQuery<YourEntityType>(“storedProcedureName”,params);

Check this post from Diego Vega on the Microsoft blog to have a much more detailed view on this.

What is property annotation method in EF?

About this question: This question depends on candidate’s understanding about the configuration and mapping of fields in Entity Framework.

Answer: Property annotation is a configuration method inside the Entity Framework that allows developers to describe fields and properties as a database configuration. It is implemented by attributes.

Take a look at the Entity Framework Tutorial page on Data Annotation

How can we describe maximum length of characters using property annotations?

About this question: This question depends on understanding what specific attribute is using for describing maximum length of characters.

Answer: It can be achieved by [MaxLength(number of characters, error message)] also we could describe minimum length by attribute MinLength.

[MaxLength(75)]
public string name { get; set; }

[MaxLength(75),MinLength(8)]
public string name { get; set; }

http://www.entityframeworktutorial.net/code-first/maxlength-minlength-dataannotations-attribute-in-code-first.aspx.

We wish you a very good interview.

Java 8 interview questions and answers

Released in 2014, Java 8 is until now the newest version released by Oracle. Among other cool features, it added Functional Programming spice to this mature language. In this article, I am going to present 22 Java 8 interview questions for a Java Developer Position.

So, why specific Java 8 interview questions?

While a profound knowledge and experience in a specific programming language is important, when I am interviewing candidates for Java Software Developer positions, what I mostly want to know concerning the technical aspect of the interview is their knowledge and experience about Software Engineering.
So, why make specific questions about Java 8? Java 8 was first released in 2014, so I would consider a must that the candidate knows pretty well about it by now. But in order to have a fluid interview, I would follow general software engineering questions with general Java questions, including specific points about Java 8 to assess how up to date the candidate is with the programming language.

Question: Can you please tell us some new features added in Java 8 with a short explanation about each?

About the question: This questions can be used as an introductory question to evaluate the candidate’s awareness of Java 8. I would mostly use it for more experienced developers, due to the fact that new ones might know all about it, but are not aware these things are “new” to Java.

Answer:

  • Lambda Expressions: Lambdas are anonymous functions that capture the variables of its surrounding context. They can be used to treat code as data, or, as an example, to be referenced and used as an ordinary object and passed as argument an to methods and constructors. See more on the question “What are Lambda Expressions?”
  • Functional interfaces: Functional interfaces are plain old Java interfaces with only one abstract methodSee more on the question “What are Functional Interfaces?”
  • Method References: Method references are also Lambda Expressions. When all a Lambda Expression does is to invoke one method or constructor, you can substitute for a much simpler syntax called Method Reference.
  • Stream API: a special iterator class that allows the processing of data in a declarative way. Streams can also leverage multi-core architectures without you having to write a single line of multi-threaded code. Writing parallel code is hard and error-prone, as we all know.
  • Default Methods: Interfaces can now contain implementation code, this is called default methods. It allows an Interface to have methods added to them without having to worry about classes who implement this interface. See more on Java SE 8: Implementing Default Methods in Interfaces.

There are several other additions to the language that I would consider a “plus” if the candidate could talk about, things such as

  • Date API: Date API in Java has always been, let’s say, questionable. This new API is inspired in the JodaTime API.
  • Optional: A new wrapper class used to avoid NullpointerExceptions. As a matter of fact, the express optionality.
  • Nashorn Javascript Engine: An engine for executing and evaluating JavaScript code.

What are Lambda Expressions in Java 8?

About the question: Lambda Expressions are, in my opinion, the most important addition brought by Java 8. Yes, Stream API is also very important, but the elegance of Stream API is also due to the use of Lambda Expressions.
I would expect the candidate to have a very good understanding of the concept of Lambda Expressions, what is required to use them and how they relate to anonymous or local classes.

Answer: Lambda Expressions are anonymous functions that capture the variables of its surrounding context. They can be used to treat code as data, or, as an example, to be referenced and used as an ordinary object and passed as an argument to methods and constructors.

Prior to Java 8, when there was such a need, normally anonymous classes were the way to go, but now, Lambda expressions are a much simpler solution.

If you have a simple Interface with one and only abstract method to be implemented, you have a Functional interface, which allows you to use Lambda Expressions as their implementation.

Just like local or anonymous classes, Lambda Expressions can capture variables, or in other words, they have the same access to local variables of the enclosing scope.

The difference between anonymous classes and Lambda Expressions lies in the fact that unlike local and anonymous classes, lambda expressions do not have any shadowing issues because they are lexically scoped. This means that they do not inherit any names from a supertype or introduce a new level of scope. Declarations in a lambda expression are interpreted just as they are in the enclosing environment.

What are Functional Interfaces?

About the question: This is a question I would ask in order to know the candidate’s knowledge about Lambda Expressions. Although it is not required that the candidate mention Lambda Expressions, I would expect to in order to explain the importance of them.

Answer: A Functional Interface is any interface with only one abstract method, annotated or not with the @Functionalnterface annotation. They are important because Lambda Expressions are in fact implementations of these abstract methods. Several out of the box function interfaces have been added to Java for the developer’s convenience.

What are Method References?

About the question: Since Method References can make the code much more readable and clean, and also make the development itself faster, it is important that the candidate knows at least what they are and the basic structure of them.

Answer: When all a lambda expression does is call one single method from an object or a class, or even a constructor, it can be expressed in a much less verbose way called Method Reference. So, method references are a syntax sugar to create lambda expressions that only invoke one method or constructor.

Let’s look at some example code, the Method Reference is in red:

public class LambdaExperiments {

public static void main(String[] args) {

//Declaring and using Lambda Expression

Consumer<String> lambdaExpression = p -> System.out.println(p);

showMethodReference(lambdaExpression);

//Using Lambda Expression directly

showMethodReference(p -> System.out.println(p));

//Using Method Reference

showMethodReference(System.out::println);

}

public static void showMethodReference(Consumer<String> consumer) {

consumer.accept(“String to be treated”);

}

}

What are Default Methods?

About the question: I would ask this question to know about the candidate’s knowledge about what changed in relation to Interfaces and especially when to use and when not to use default methods.

Answer: Java 8 brought the concept of Default Methods or method implementations directly on an Interface.

One of the biggest advantages of this feature is the possibility to add new methods to an interface that has already several implementation classes without breaking backward compatibility, making unnecessary for these classes to implement this new method.

They require the “default” keyword at the beginning of the method signature.

We should avoid the creation of default methods and try to keep the separation of interface and implementation as much as possible.

Are Lambda Expressions Closures? Please explain.

About the question: I would use this question to assess the general programming knowledge (Closures) and also specific knowledge of Java 8 Lambda Expressions. This could be a good opening question because it is very broad and you can choose next questions based on the level of the candidate’s answer.

Answer: Yes, Lambda Expressions are closures. For the interviewer, though, what is mostly important is to assess the candidate’s line of thought and the preciseness of the concepts used in their explanation.

First of all, it is important for the candidate to state their understanding of closures:

“Closures are functions that refer to independent (free) variables (variables that are used locally but defined in an enclosing scope). In other words, these functions ‘remember’ the environment in which they were created.”

Closures by Mozilla Developer Network

Check the following video, which has a pretty good explanation on how closures work in Javascript.

Another way to say it is that a closure is a function that keeps access to the variables of the enclosing context. A closure allows the function to access those captured variables through the closure’s copies of their values or references, even when the function is invoked outside their scope.

In most functional programming languages, where the concept of closures has been introduced, the surrounding context variables are accessible via reference, which means the value can be manipulated. In Java, on the other hand, Lambda Expressions keep a copy of the values.

Despite the fact that in the post “Are Java 8 Lambdas Closures?“, Bruce Eckel, author of the famous “Thinking in Java” and other “Thinking in” series, wrote that Java had “closures with restrictions,” which might not be “perfect” closures, but was nonetheless still quite useful.”, I would say Java provides full-fledged closures.

What is the type of a Lambda Expression?

About the question: This question assesses basic understanding of Lambda Expression. I would be concerned with a candidate that can not formulate a coherent answer.

Answer: A Lambda Expression is an anonymous implementation of a functional interface, so the type is the Interface it implements. The compiler is pretty smart to figure it out, let’s take a look at a simple example:

public class LambdaExperiments {

//This is a Functional Interface, because it has only one abstract method

private interface FilterByAge {

abstract boolean test(int age);

}

public static void main(String[] args) {

//Case 1

Predicate<Integer> lambdaExpression = p -> p > 5;

System.out.println(lambdaExpression instanceof Predicate);

LambdaExperiments le = new LambdaExperiments();

//Case 2

le.giveMeAFilteredList(p -> p > 5);

}

public List<String> giveMeAFilteredList(FilterByAge filter) {

System.out.println(filter instanceof Predicate);

System.out.println(filter instanceof FilterByAge);

//This method accomplishes nothing, it is just to show the type of the Lambda Expression

return Collections.emptyList();

}

}

Notice that even having the same implementation “p -> p > 5”, they are not interchangeable because they implement two different Functional Interfaces.

Case 1 type is Predicate, Case 2 type is FilterByAge because it is the type required by the method being invoked.

What does it mean for a variable to be “effectively final”, how would that be of any importance and how can one tell that a particular variable is in fact “effectively final“?

About the question: This question does not need a long answer, but it is very important that the candidate is aware of this concept to work with Lambda Expressions.

Answer: A variable or parameter whose value is never changed after it is initialized is called “effectively final”. With Java 8, the compiler became smart enough to realize that even though a variable is not explicitly declared final, it has been treated as so by the code which never changes the variable’s value after initialization.

This is important because just like anonymous classes, for lambda expressions to be able to access local variables and parameters of the enclosing block, these need to be either final or effectively final.

Explain the syntax of a Lambda Expression

About the question: I would only ask this one in case the candidate has already demonstrated a reasonable knowledge about Lambda Expressions. I would expect the candidate to explain the parameter part of the expression, as well as the expression part.

Answer: A lambda expression is composed of the parameter part and the expressions part, with the “arrow” token separating them:

parameterPart -> expressionsPart;

About the parameters part:

There is no need to declare the type because the compiler can infer it from the values provided. You only need to use parenthesis when more than one parameter is used, then you would have a comma-separated list of formal parameters enclosed in parentheses.

(param1, param2, paramN) -> expressionsPart;

About the expression part:

The expression part is composed of a single expression, which does not need curly braces or a statement block which does. Since a return statement is not an expression you would need to enclose it in curly braces.

parameterPart -> {statement;};

What do you gain as a developer by having Lambda Expressions included in Java?

About the question: This question is intended to see if the candidates use Lambda Expression on their daily activities and if they are doing a good use of this tool.

Answer: Even with some slight difference to Anonymous or local classes, lambda expressions are used almost exactly for the same purposes and can significantly reduce the verboseness of the necessary code.

Especially for repetitive iterations, you can use lambda expressions to remove the “mutable” part, and let a library do the rest of the tedious work.

This is surely a good candidate for the use of the Strategy Pattern from (Design Patterns: Elements of Reusable Object-Oriented Software), made much easier by lambda expressions. (see Separating Concerns Using Lambda Expressions).

There is extensive use of Lambda in new APIs, such as the Stream API. Other classes have been also enhanced due to the introduction of lambda expressions, such as the wrappers for primitive classes, to allow the use of method references more easily. An example is Integer.sum as you can see in much more detail in the Oracle’s article New and Enhanced APIs That Take Advantage of Lambda Expressions and Streams in Java SE 8.

Please explain the System.out::println expression?

About the question: This is another question about method reference but it does not say so. So I would expect the candidate to say this is a method reference and explain about it, pretty much as the above question.

Answer: When all a Lambda Expression does is to call one single method from an object or a class, it can be expressed in a much less verbose way called Method Reference. It is just a very nice syntax sugar to call the System.out.println with the same parameter provided to the Lambda Expression.

//Using Lambda Expression

methodWhoseExpectedParamIsConsumer(p -> System.out.println(p));

//Using Method Reference

methodWhoseExpectedParamIsConsumer(System.out::println);

Could you explain the Double Colon “::” in Java?

About the question: This is yet another question about Method Reference. So I would expect the candidate to say this is about method references, explain about it and its syntax.

Answer: The double colon token is part of the syntax for Method References. When all a Lambda Expression does is to call one single method from an object or a class, it can be expressed in a much less verbose way called Method Reference.

The four possible types of method references are:

  • References to a static method: Class::staticMethodName
  • References to an instance method of an arbitrary object: Class::instanceMethodName
  • References to an instance method of a particular object: objectName::instanceMethodName
  • References to a constructor: Class::new

What is the @FunctionalInterface annotation used for?

About the question: This is a question I would ask to know about the candidate’s knowledge about Lambda Expressions. Not knowing this would not be so demeaning in my opinion, but a right answer would show a bit more knowledge about the subject.

Answer: Any Interface with this annotation will be understood by the compiler as a functional interface, as defined by the Java Language Specification.

Compilers are required to generate error messages if the annotated type does not satisfy the requirements of a functional interface. It is important to remember that a Functional Interface does not require this annotation do be so, the annotation just makes the compiler aware of its intent.

When talking about Functional Interfaces provided by Java, what is the difference between the Predicate, Consumer and Function interfaces?

About the question: This is a question I would ask to know about the candidate’s knowledge about Lambda Expressions. I would expect this question to be easy for someone who uses lambda expressions on a daily basis.

Answer: The abstract method contained in the Predicate Interface takes one argument and returns a boolean value. It is commonly used in filters, where an iteration provides a value to this method and a true or false value is expected to say if the value is accepted or not.

The abstract method on the Function interface, on the other hand, takes one argument and returns a value. Which is normally used to map values.

The Consumer interface, at last, does not return any value.

What is the difference between an interface with a default method and an abstract class?

About the question: When I ask this question, my intent as an interviewer is to capture from the candidate what is the essence of a default method and especially, what it is not.

Answer: Java 8 brought the concept of default methods or method implementations in an Interface. So one might ask what is the difference between an interface and an abstract class now.

Abstract classes can have many things that an interface cannot, like constructors and instance variables. Abstract classes, even if they have only one abstract method, can’t be used as functional interfaces, which seems pretty obvious but it is always better to make it clear.

What happens if you create an Interface that extends another interface which contains a Default Method?

About the question: This is a question I would ask if the candidate has been pretty consistent in the interview so far. Since default methods are not something you normally do in your day to day life I would consider okay if the candidate fails to give a perfect answer. I would like to see, though, is their line of thought.

Answer: If an interface that contains a default method is extended, there are three options:

  • The child interface does not mention the default method: The effect is that the default method is inherited;
  • The child interface redeclares the method: The method then becomes abstract;
  • The child interface redefines the method: The effect is that the new method overrides the one from the super interface;

https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html

What would be a good reason for the introduction of Default Methods in Java 8?

About the question: When I ask this question, my intent as an interviewer is to capture from the candidate what is the purpose of default methods, the knowledge about this question is an indicator on how adequate the candidate will make use of default methods in the code they produce.

Answer: One of the driving forces behind the introduction of default methods in Java 8 was the possibility to add new methods to an interface that has already several implementation classes without breaking backward compatibility, making unnecessary for these classes to implement this new method.

Does default methods introduce multiple inheritances?

About the question: This question is one that I appreciate because it brings higher concepts as multiple inheritances and relates them to the new concepts introduced to Java 8. Clear concepts exposed by the candidate are always good signs.

Answer: Default methods are a cool feature that allows one to create new methods to an interface without forcing the previously implementations to also implement the new method, this is the driving force behind the introduction of Default Methods.

Since a class can implement more than one interface and these interfaces can have implementations on their own, we could say we have a form of multiple inheritances (without a state, though). If they both have the same signature, then the implementation class has to explicitly tell which one to use.

Remember the purpose of default methods and avoid using them, unless you are adding new methods to an interface that has implementation classes or you can’t tell if it does. The separation of Interface and implementation should be kept.

Default Methods in Java 8 and Multiple Inheritance

Does default methods introduce the diamond problem in Java 8?

About the question: This is yet another question that brings concepts related to inheritance and relates them to the new concepts introduced to Java 8. Clear concepts exposed by the candidate are always good signs.

Answer: The diamond problem is a common problem found in languages which allow multiple inheritances.

The above drawing shows an interface A being extended by interface B and interface C, the class D implementing both B and C.

The diamond problem in Java 8

The diamond problem, common in languages which allow multiple inheritances.

The problem of the diamond does not occur in Java because interfaces have no state. Java does not allow for multiple inheritances with classes.

The method resolution is pretty straight forward:

  • If B and C do nothing about the default method, then D inherits from A, no problem.
  • If B or C (not both) redeclare the method in A, then this method becomes abstract and also the most specific one, which will require D to implement it;
  • If B or C (not both) redefine the method in A, then this new implementation becomes the most specific one, which will be inherited by D;
  • If B and C, redefine or redeclare the implementation, then D will have to get rid of the ambiguity by implementing the method.

What are Interface Static Methods in Java 8 ? How are they invoked?

About the question: Interfaces now can have implementation code, both default, and static methods. This question aims to assess the candidate’s knowledge about the changes introduced to the Java interfaces.

Answer: Java 8 added the possibility to create static methods in interfaces. Neither the interfaces that extend an interface with a static method nor the classes that implement it, inherit this static method, it is necessary to invoke them explicitly using the interface name, just like any other static method: NameOfInteface.staticMethod();

A static method can only be invoked directly by the implementation methods (either static or default) from the defining interface.

What is a stream and how is it different from a collection?

About the question: Streams are one of the most important additions to Java 8. It is frequently confused with collections. It is important to fully understand what they are and what is their purpose to be able to make good use of it in the day to day work.

Answer: The short answer could be that collections deal mostly with data while streams deal with computations.

A collection is a data structure that stores multiple elements in it. Unlike a collection, a stream does not represent a data structure, it is a sequence of elements carried from a source through a sequence of stream operations called a pipeline.

A very important conceptual difference is about when things are computed. A collection holds the values which have to be precomputed. On the other hand, a Stream computes the elements just in time.

Normally we store data in the collections to process data. How would you have done so in the past, without the Stream API?

Let’s say you have a List of all high school students from Nebraska.

Each student instance stores:

  • a double for the grade obtained in the quarter
  • an instance to the school the student attends (which holds the city they are located)
  • what is the student’s school year

Suppose you want to find out the average grade from all Sophomore students from Lincoln.

Without showing code, one possible way would be to:

  • create an empty collection to hold the filtered students;
  • iterate through the collection of all students;
  • test each student to see if they are both from Lincoln and a Sophomore;
  • add each instance that passes this test to the collection to hold filtered students.
  • iterate this filtered collection to sum the grades
  • divide the sum by the collection’s size.

With Stream API, it is much more declarative the way the same operation could be done:

Predicate<Student> test = …

studentsFromNebraska.parallelStream()

.filter(test)

.mapToDouble(Student::getGrade)

.average();

The two biggest advantages of this new code is clarity and efficiency. The clarity comes from the fact that this code is much more declarative, after all, we only express what we want, not how, which is handled for you. The efficiency stems from the fact that the Stream API leverage multicore architectures for you without the need to implement any multithread code, that, let’s face it, is both hard and error-prone.

Another difference is the type of iteration: In the Stream API the iteration is internal, which means the iteration is done behind the scenes for you, in contrast, collections are iterated explicitly.

More information: Processing Data with Java SE 8 Streams, Part 1

What are intermediate and terminal operations when talking about the Stream API?

About the question: In the previous question, we dealt with the difference between Streams and Collections, now the idea of this current question is to assess the candidate’s understanding of how to work with Streams.

Answer: Stream operations that have the return type Stream can be connected and since nothing is executed until a terminal operation is reached (Lazy), they are called intermediate operations. When a terminal operation is found, it closes the stream pipeline.

Operations that close a stream pipeline are called terminal operations, they produce a non-Stream type result, which can be even void.

What is stream pipelining in Java 8?

About the question: See question above.

Answer: With the Stream API, it is possible to chain several intermediate operations together to process data until a terminal operation is reached. In other words, a pipeline is a sequence of aggregate operations. This enables certain optimizations, such as laziness and short-circuiting.

A pipeline has the following component parts:

  • Source: Where the elements of the stream are coming from. This could be things like a collection, an array, a generator function, or an I/O channel.
  • Then you would have from zero to N intermediate aggregate operations, which will return a new Stream with the effects of the operation. As examples of intermediate operations we have filter, map, reduce, find, match, sorted, and so on.
  • Finally, the pipeline needs a terminal operation, which means that all intermediate operations will only be executed when the terminal operation is reached.

Laziness means the operations execution can be postponed until the terminal operation is invoked, which means optimizations also occur at this stage, like the short-circuiting (you probably remember this from conditional statements, the idea is the same)