Week 6 Flashcards

1
Q

ORM Framework features, advantages, and disadvantages

A
  • Object Relational Mapping is a tool that uses objects to connect the OOP language and database systems
  • Benefits - ORM maps an object to the table, can hide the details of SQL queries from OO logic, provides methods for automatic versioning and timestamping, provides caching support for better performance, best suited for large projects, injected transaction management, configurable logging, faster development of applications
  • some ORM tools are Hibernate, JPA, Active JPA, iBATIS, IBM Pure Query, etc
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What methods are available in the Object class (4)?

A

.clone
.hashcode
.equals
.toString

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How would you clone an object?

A

First, tag the class with the Cloneable marker interface.

Next, invoke clone().

The clone method is declared in java.lang.Object and does a shallow copy.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is an enhanced for loop?

A

Enhanced for loops allow easier traversal of Collections (actually any arrays or Iterables)

Syntax - for (object x : collection){. . .}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is try-with-resources?

What interface must the resource implement to use this feature?

A
  • a Java 7 feature
  • allows for automatically closing resources in a try/catch block using try(resource) {…} syntax
  • Must implement the AutoCloseable interface
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How would you make numbers in your code more readable?

A

Use the underscore ( _ ) for numeric literals; must be placed between numbers (EX - 45,000 = 45_000)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are covariant return types?

A

A method is allowed to return objects that are child classes of the return type.

Also, when overriding a method, the return type of the new method can be a child class of the original return type

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are 3 usages of the super() keyword?

A
  1. to refer to immediate parent class instance variable.
  2. super() is used to invoke immediate parent class constructor (also can pass params)
  3. to invoke immediate parent class method.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Can you overload / override a main method? static? private? default? protected?

A

Main method - overload, cannot override b/c is static method.

Static method - overload, cannot override b/c belongs to class (not inherited).

Private method - overload, cannot override b/c doesn’t get inherited.

Default method - both.

Protected method - both (override if inherited).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the difference between FileReader and BufferedReader?

A

FileReader is just a Reader which reads a file, so it reads characters and uses the platform-default encoding.

BufferedReader reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines (e.g. can read one line at a time).

You can wrap a BufferedReader around a FileReader

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How would you pass multiple values with a single parameter into a method?

A

Use varargs

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is static block?

A
  • used for static initialization

- executed only once - upon creation of the first object of a class or access to static methods of a class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What are static imports?

A

a static method or variable from a class - syntax: import static

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How would you clone an object?

A

use the .clone() method inherited from object class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What makes a class immutable (6)?

A
  1. Declare the class as final so it can’t be extended.
  2. Make all fields private so that direct access is not allowed.
  3. Don’t provide setter methods for variables.
  4. Make all mutable fields final so that it’s value can be assigned only once.
  5. Initialize all the fields via a constructor performing deep copy.
  6. Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

If 2 objects are equal, do they have the same hashcode? If not equal?

A

If two objects have the same hashcode then they are NOT necessarily equal.

But if objects are equal, then they MUST have same hashcode.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What data types are supported in switch statements (6)?List all non-access modifiers?

A
  1. byte
  2. char
  3. enums
  4. int
  5. short
  6. string
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

List all non-access modifiers (9)?

A
  1. abstract
  2. default
  3. final
  4. native
  5. static
  6. strictfp
  7. synchronized
  8. transient
  9. volatile
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Which collections cannot hold null values (4)?

A

HashTable
TreeSet
ArrayDeque
PriorityQueue

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is the .forEach() merthod in Java 8?

A

The forEach() method accepts what is called a functional interface as its parameter (specifically a Consumer), which the lambda expression ( -> ) then implements at runtime.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

If 2 interfaces have default methods and you implement both, what happens?

A

The code will NOT compile unless you override the method.

However, the code WILL compile if one interface is implemented further up in the class hierarchy than the other - in this case, the closest method implementation in the hierarchy will be called.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

If 2 interfaces have same variable names and you implement both, what happens?

A

The code will compile unless you make a reference to the variable (this is an ambiguous reference).

You must explicitly define the variable by using the interface name: int a = INTERFACENAME.a;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Why does HashTable not take null key?

A

The HashTable hashes the keys given as input, and the null value cannot be hashed

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What new syntax for creating variables was introduced with Java 10?

A

The var keyword, with type inference

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

Is there an interactive REPL (read, evaluate, print, loop) tool for Java like there is for languages like Python?

A

Yes, the jshell tool introduced in Java 9

26
Q

What are collection factory methods?

A

They allow you to directly populate collections

27
Q

Can you catch more than one exception in a single catch block?

A

Yes, use the | operator

28
Q

What are the 7 logging levels?

A

Least to most restrictive:

  1. ALL => all levels
  2. DEBUG => designates fine-grained informational events that are most useful to debug an application
  3. INFO => informational messages that highlight the progress of the application at the coarse grained level
  4. WARN => designates potentially harmful situations
  5. ERROR => designates error events that might still allow the application to continue running
  6. FATAL => severe error events that presumably lead the application to abort
  7. OFF => highest possible level, intended to turn off logging
29
Q

Why is it important to use a logger instead of writing to standard output?

A

You can set logging thresholds, as well as keeping track of application events in a log file

There is no advantage to using a logger

Loggers can reduce design complexity

Loggers are easier to configure

30
Q

What file formats can you use for log4j configuration (4)?

A
  1. XML
  2. JSON
  3. YML
  4. Properties
31
Q

What is JPA?

A
  • Java Persistence API
  • standard API for accessing, persisting, and managing data between Java objects/classes and relational databases
  • defined in the javax.persistence package
  • uses Java Persistence Query Language to person database operations
  • uses EntityManager interface to create, read, and delete operations for instances of mapped entity classes
32
Q

What is Hibernate?

A
  • an ORM tool for Java programming language
  • open-source persistent framework
  • a flexible and powerful ORM solution to map Java classes to database tables
  • an implementation of JPA, so it follows the common standards provided by the JPA
  • defined in the org.hibernate package
  • uses Hibernate Query Language (HQL)
  • Hibernate’s Session interface is an extension of the JPA EntityManager interface
33
Q

What are the benefits of using Hibernate over JDBC (4)?

A
  • used to overcome JDBC’s drawbacks
  1. transparent persistence - reduces the lines of connection code
  2. database independent - can be used to connect with any database, and changing the SQL sent to a database is as simple as changing the database dialect in the config file
  3. provides an abstraction - many common tasks are implemented for us internally (like establishing a connection or performing CRUD)
  4. supports dual-level caching mechanism - retains the objects in the cache to reduce repeated hits to the database; highly scalable and optimizes the app’s performance
34
Q

Tell me about some of the JPA annotations you have worked with (15 listed)? What do they do? How do you specify multiplicity relationships with JPA annotations?

A

@Column - maps the field to the column table (attributes include name, length, nullable, and unique)
@Entity - used to mark a class as a mapped/persistence class. MUST have a no-args constructor with package visibility
@Table - used to specify the table details that used to persist the entity in the database
@GeneratedValue - used to instruct the database to generate a value for the field automatically
@Id - used to mark the field as a primary key column
@JoinColumn - specifies a column for joining an entity association or element collection
@JoinTable - used in the mapping of associations. It is specified on the owning side of an association
@NamedQuery - is a way to use any query by some meaningful name (like an alias)
@PersistenceContext - handles a set of entities which hold data to be persisted in some persistence store
@Transient - tells the hibernate, not to add this particular column

Specify multiple relationships with JPA using @ForeignKey, @OneToOne, @OneToMany, @ManyToOne, @ManyToMany

35
Q

What are the interfaces of Hibernate (5)?

A

ALL are defined in the org.hibernate package

  1. Session - session objects are created using the SessionFactory and are used to perform CRUD operations.
  2. SessionFactory - used to create the Session Object. The SessionFactory object is used by all threads of an application.
  3. Query - obtained by calling Session.createQuery(); can be used to expose extra functionality beyond that provided by Session.iterate() and Session.find()
  4. Transaction - associated with a Session and usually instantiated by a call to Session.beginTransaction(); used whenever we perform any operation and based upon that operation there is some change in database
  5. Criteria - a simplified API for retrieving entities by composing Criterion objects
    • restrictions - class in hibernate that provides several methods that can be used as conditions (known as Criterion). These conditions are added to a criteria object with the add() method
    • projections - used in order to query only a subset of the attributes of an entity or group of entities you’re querying with Criteria
36
Q

What is multi-threading?

A

Handling multiple threads / paths of execution in your program

37
Q

In what ways can you create a thread?

A

By extending the thread class or by implementing the runnable interface

you must call threads with .start() method to start it as a new thread of execution

38
Q

Lifecycle of a thread?

A

When created, in NEW state.

When .start() is called, it goes to RUNNABLE state.

When .run() is called, goes to RUNNING state.

If .sleep() or .wait() is called, will go to WAITING.

If dependent on another thread to release a lock, it will go to BLOCKED state.

When finished executing, will be in DEAD state and cannot be restarted.

39
Q

What is deadlock?

A

Deadlock occurs when one thread is waiting on a resource held by another thread, which is waiting on a resource the first has. In this scenario, execution of both threads is blocked and the program is stuck indefinitely.

Deadlock occurs when a thread ends unexpectedly and disrupts execution of the program

Deadlock occurs when two threads call each other and get stuck in an infinite loop

Deadlock occurs when the program terminates before a thread can finish executing

40
Q

What is a thread?

A

A special method that executes only once

A class which allows for more efficient and faster processing

A representation of a path of execution, allowing for concurrent processing

A separate program which can be run only after the end of the current program

41
Q

What is the synchronized keyword used for?

A

addressing the problem of deadlock by preventing access to the resource by more than one thread at a given time

synchronizing the execution of many separate threads so they finish execution at the same time

preventing access to the resource from outside the class

enabling the class to be serialized

42
Q

Threads can be created by..?

A
  1. passing a Thread into the constructor of Runnable: new Runnable(Thread)
  2. extending the Thread class and overriding the .start() method
  3. extending the Runnable class and overriding the .run() method
43
Q

Tell me how you set up hibernate? What files are you editing, what goes in them, etc.

A
  • configuration files would go into an XML file or properties file:
    1. XML file (named hibernate.cfg.xml) - contains the database and session related configuration. Database configuration includes the JDBC connection URL, Database user credentials, driver class, and hibernate dialect.
    2. properties file (named hibernate.properties) - also used to configure Hibernate
  • if both are present, then hibernate gives priority to a hibernate.cfg.xml file
  • the difference between a hibernate.cfg.xml and hibernate.properties file is that in an XML file we can directly map classes using the element, but there is no way to configure this in a properties file
44
Q

Explain Hibernate configuration: SQL dialect?

A

Dialect allows Hibernate to generate SQL optimized for a particular relational database.

Hibernate generates queries for the specific database based on the Dialect class.

A hibernate dialect gives information to the framework of how to convert hibernate queries(HQL) into native SQL queries

45
Q

Explain Hibernate configuration: hbm2ddl?

A

automatically validates and exports DDL (data definition language) to the schema when the sessionFactory is created

46
Q

Explain Hibernate configuration: show_sql?

A

If this property value is true then it enables the logging of all hibernate-generated SQL statements to the console.

47
Q

explain eager vs lazy loading?

A

Eager loading - the process whereby a query for one type of entity also loads related entities as part of the query. Eager loading is achieved by the use of the Include method.

Lazy loading - delaying the loading of related data, until you specifically request for it.

While lazy loading delays the initialization of a resource, eager loading initializes or loads a resource as soon as the code is executed. Eager loading also involves pre-loading related entities referenced by a resource.

48
Q

Under what circumstances would your program throw a LazyInitializationException?

A

when Hibernate needs to initialize a lazily fetched association to another entity without an active session context

49
Q

What is HQL? What makes it different from SQL?

A
  • Hibernate Query Language - object-oriented query language of the Hibernate framework.
  • It supports OOP concepts like polymorphism, inheritance, and abstraction.
  • It is database-independent and easy to learn.
  • different from SQL because HQL queries against persistent objects instead of tables/columns
50
Q

What is the Criteria API?

A
  • provides an object oriented approach for querying a database and getting results; a programmatic and typesafe way to fetch data from the relational database
51
Q

What is caching?

What is the difference between L1 and L2 cache?

A

Hibernate performs caching to optimize the performance of an application. It’s used to reduce the number of database hits by storing data locally in a cache.

L1 - checks for cached data; enabled by default and can’t be disabled; a mandatory cache through which all requests must pass; associated with the Session object and each object caches data independently so there is NO sharing of cached data across sessions and cached data is deleted when session closes; only useful for repeated queries in the same session

L2 - responsible for caching objects and sharing data across sessions; disabled by default but we can enable it through configuration (adding properties to the hibernate configuration file); assciated with the SessionFactory object and is shared among all sessions created using the same session factory;

52
Q

How do you enable second-level/L2 caching?

A
  • we can enable it through configuration by adding the following properties to the hibernate configuration file:

true
org.hibernate.cache.ehcache.EhCacheRegionFactory

  • to make an entity eligible for L@ caching we annotate it @Cache(usage = CacheConcurrencyStrategy.( ))
53
Q

What is JPQL?

A
  • Java Persistence Query Language - object-oriented query language used to perform database operations.
  • uses the EntityManager interface to create, read, and delete operations for instances of mapped entity classes
54
Q

Explain Named Queries

A
  • an SQL expression with a predefined unchangeable query string; can be defined in hibernate mapping file or inan entity class
  • annotations used in entity class:
    @NamedQueries - used to define the multiple HQL expressions.
    @NamedQuery - used to define the single HQL expression. has 2 attributes:
    - name - used to specify a name by which a session object can locate the query.
    - query - used to specify the HQL statments.
    @NamedNativeQueries - used to define the multiple native SQL expressions.
    @NamedNativeQuery - used to define the single native SQL expression.
55
Q

What are the 3 object states in Hibernate?

A

An object of a persistent class (a class mapped to a relational database table) can be in one of three different states. These states are defined in relation to a persistence context (Session object).

  1. transient state - When an object is created using the new operator and not yet associated with a Hibernate Session, then the object state is transient; doesn’t represent a row; garbage collected if the app does not hold a reference
  2. persistent state - The object state is persistent when it is associated with the hibernate session; represents a row in the database and has an identifier value; transient can become persistent by associating them with a Session using save() /Persist() /or saveOrUpdate() methods;when data comes from database using get() or load() method, it’s persistent
  3. detached state - When a persistent object has its session closed, then it becomes detached; any changes made to detached objects will not be saved automatically to the db; if a detached instance is reattached with a new Session, it becomes persistent again; the Session class’ close(), evict(Object), and clear() methods are used to move a persistent object to the detached state; the Session class’ update(Object) and merge(Object) methods can be used to reattach detached objects to a session.
56
Q

Can you write native SQL with Hibernate? Is this a good idea?

A

Yes. In hibernate, we can directly write SQL statements using Native SQL, but using HQL or JPQL is recommended

57
Q

How would you configure Hibernate to print to the console all SQL statements run?

A

Add ‘show_sql’ property to the Hibernate configuration file

58
Q

What is automatic dirty checking?

A

Hibernate provides a feature called Automatic Dirty checking where changes to a persistent object are automatically saved to the database when the session is flushed or the transaction is committed. So the code does not need to invoke an explicit save or update.

59
Q

What is Transactional Write Behind?

A
  • when Hibernate tries to defer the Persistence Context (first-level cache) flushing up until the last possible moment
60
Q

What are the 7 transaction propagation strategies?

A
  1. Mandatory - if there is an active transaction, then it will be used. If there isn’t an active transaction, then Spring throws an exception
  2. Nested - Spring checks if a transaction exists, and if so, it marks a save point
  3. Never - Spring throws an exception if there’s an active transaction
  4. Not supported - If a current transaction exists, first Spring suspends it, and then the business logic is executed without a transaction
  5. Required - the default propagation. Spring checks if there is an active transaction, and if nothing exists, it creates a new one
  6. Requires new - Spring suspends the current transaction if it exists, and then creates a new one
  7. Supports - Spring first checks if an active transaction exists. If a transaction exists, then the existing transaction will be used. If there isn’t a transaction, it is executed non-transactional
61
Q

What is the difference between Dynamic Insert and Dynamic Update?

A

When the dynamic-insert property is set to true, Hibernate does not include null values for properties (for properties that aren’t set by the application) during an INSERT operation.

With the dynamic-update property set to true, Hibernate does not include unmodified properties in the UPDATE operation.

62
Q

What is a proxy?

A
  • Hibernate generates proxies to provide lazy loading for to-one associations, and you can use them to improve the performance of some of your write operations; generates the proxy class as a subclass of your entity class