

Libraries and standards
52. What is Hibernate? What's the difference between JPA and Hibernate?
To answer this question, I think we first need to understand what JPA is. It is a specification that describes an object-relational mapping of simple Java objects and provides an API for storing, retrieving, and manipulating such objects. That is, relational databases (DBs) are represented as a set of interconnected tables. And JPA is a widely adopted standard that describes how objects can interact with relational databases. As you can see, JPA is something abstract and intangible. It's like the idea itself, the approach.
53. What is cascading? How is it used in Hibernate?
As I said earlier, communication in Hibernate happens through data objects called entities. These entities represent specific tables in the database, and as you will recall, Java classes can contain references to other classes. These relationships are also reflected in the database. As a rule, they are either foreign keys (for OneToOne, OneToMany, ManyToOne relationships) or intermediate tables (for ManyToMany relationships). When your entity has references to other related entities, annotations are placed above these references to indicate the type of relationship: @OneToOne, @OneToMany, @ManyToOne, @ManyToMany. You can specify the type of cascade for this relationship in the annotations' cascade property. JPA has specific methods for interacting with entities (persist, save, merge ...). Cascade types are used to show how related data should behave; these methods are used on a target entity. So what are the cascading strategies (cascade types)? The JPA standard provides for the use of six cascade types:PERSIST — save operations occur in a cascade (for the save() and persist() methods). In other words, if we save an entity that is associated with other entities, then those entities are also saved in the database (if they are not already there)
MERGE — update operations occur in a cascade (for the merge() method)
REMOVE — delete operations occur in a cascade (remove() method)
ALL — contains three cascading operations all at once — PERSIST — MERGE — REMOVE
DETACH — related entities are not managed by the session (detach() method). That is, when the related entities' data is changed, the data in the database is not automatically updated — they are converted from persistent to detached (i.e. the entity is not managed by JPA)
REFRESH — every time an entity is refreshed with data from the database (refresh() — refreshes detached objects), its related entities are also refreshed. For example, you somehow changed the data taken from the database, and you want to restore the original values. In this case, you will find this operation useful.

REPLICATE — used when we have more than one data source and we want the data to be synchronized (Hibernate's replicate method). All entities must have identifiers (id) to ensure that they can be created without problems (to ensure that the same entity does not have different ids for different databases)
SAVE_UPDATE — cascading save/delete (for Hibernate's saveOrUpdate method)
LOCK — the opposite of the DETACHED operation: converts a detached entity back to the persistent state, i.e., the current session will track the entity once again
54. Can an Entity class be abstract?
According to 2.1 The Entity Class of the JPA specification, "Both abstract and concrete classes can be entities." So, the answer is yes, an abstract class can be an entity and can be marked with the @Entity annotation.55. What is an entity manager? What is it responsible for?
First of all, I would like to note that EntityManager is a crucial component of JPA. It is used for entities' interaction with the database. In general, methods for the entity's interaction with the database are called on the entity (persist, merge, remove, detach)... But I also note that this component is usually not a singleton for the entire application. It is often lightweight, one is deleted, and a new one is created using the EntityManagerFactory. If we draw a parallel with JDBC, where EntityManagerFactory is analogous to DataSource, then EntityManager is analogous to Connection. Earlier, I mentioned that a persistent entity is an entity that is managed by the current connection. This entity is managed by the EntityManager, which is closely related to the current connection, and the TransactionManager, which is responsible for opening/closing transactions. In the figure below, you can see the entity's life cycle:
56. What is the Assert class? Why is it used?
I haven't heard of such a class in JPA, so I will assume that this question refers to a class found in the JUnit library that is used for unit tests. In this library, the Assert class is used to check the results of code execution (here assert means an assertion that you have specific state/data at a specific location in the code). For example, let's say you are testing a method that is supposed to create a cat. You run the method and you get some result:
Cat resultOfTest = createCat();
But you need to make sure it was created correctly, right?
So you manually create a specific cat (expectedCat) with exactly the parameters that you expect to see in the cat obtained from the createCat() method.
Then you use the Assert class to verify the results:
Assert.assertEquals(resultOfTest, expectedCat);
If the cats are different, then an AssertionError will be thrown, which tells us that we did not get the expected results.
The Assert class has many different methods that cover a variety of operations helpful in verifying expected results. Here are a few of them:assertTrue(<boolean>) — the value passed in as an argument is expected to be true
assertFalse(<boolean>) — the value passed in as an argument is expected to be false
assertNotEquals(<object1>, <object2>) — the objects passed as arguments must be different when compared using equals (false)
assertThrows(<ClassNameOfException>.class, <exceptionObject>) — the second argument is expected to be an exception thrown by the first argument (i.e. the second argument is usually a method call that should throw an exception of the required type)
String
57. Describe Java's String class
String is a standard Java class responsible for storing and manipulating string values (sequences of characters). It is an immutable class (I wrote about immutable previously here), i.e., the data of objects of this class cannot be changed after they are created. I would like to note right away that the StringBuilder and StringBuffer classes are essentially identical — the only difference is that one of them is intended for use in a multithreaded environment (StringBuffer). These classes are like String, but differ in that they are mutable. Even after they are created, they let you modify the strings they represent, without creating a new object. Their methods differ from the standard String methods and are designed for string manipulation (there's a reason they call it a builder).58. What are the ways to create a String object? Where is it created?
The most common way to create a string is to specify the value we want in double quotation marks simply:
String str = "Hello World!";
You can also do it explicitly using new:
String str = new String("Hello World!");
You can also create a string from an array of characters:
char[] charArr = {'H','e','l','l','o',' ', 'W','o','r','l','d','!'};
String str = new String(charArr);
We can do it by calling the toString method on some object:
String str = someObject.toString();
We can do it by calling any other method that returns a string. Example:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String str = reader.readLine();
You understand that there can be many, many ways to create a string.
When a String object is created, it is stored in a string pool, which we will discuss in more detail in one of the questions below.
59. How do you compare two Java strings, and how do you sort them?
Java uses a double equal sign (==) to perform comparisons. If we need to compare simple values like ints, we will use it. But this method is not suitable for comparing full-fledged objects. It will only compare references, i.e. whether the references point to the same object or not. This means that if we compare two objects with the same field values using ==, we will get false. The fields have the same values, but the objects themselves occupy different locations in memory. String objects, despite their deceptive simplicity, are still objects. Comparing them using == is also not appropriate (despite the presence of a string pool). The proper solution is the Object class's standard equals method, which needs to be overridden to work correctly (by default, it uses == for comparisons). The String class overrides it, so we just use its implementation:
String firstStr = "Hello World!";
String secondStr = "Hello World!";
boolean isEquals = firstStr.equals(secondStr);

TreeSet<String> sortedSet = new TreeSet<>();
sortedSet.add("B");
sortedSet.add("C");
sortedSet.add("A");
sortedSet.forEach(System.out::println);
Console output:
60. Provide an algorithm for converting a string to characters. Write the corresponding code
As I said earlier, String objects have a lot of different useful methods. One of these is toCharArray. This method converts a string to a character array:
String str = "Hello world";
char[] charArr = str.toCharArray();
Next, we have an array of characters that we can reference by index:
char firstChar = charArr[0]; // H
61. How do you convert a string to a byte array and back? Write the corresponding code
The String class has a getBytes method, which is similar to the toCharArray method and returns the string as a byte array:
String str = "Hello world";
byte[] byteArr = str.getBytes();
byte firstChar = byteArr[6]; // 119
We've come to the logical conclusion of our review today. Thanks for reading!

GO TO FULL VERSION