Revised
Revised
Revised
Java 8 Features
Lambda expression
@FunctionalInterface
Change to interface syntax
- Ambiguity
forEach
Streams
-Changes to Collection:
1. removeIf() to Collection
2. forEachRemaining() to Iterator
3. sort(Comparator) to List
4. HashMap improvements - it now uses "Balanced Tree" insteadof LinkedList.
5. new methods added to HashMap
6. forEach
7. Arrays.parallelSort()
8. SplitIterator
-StringJoiner
-Optional
-Java Nashorn
Nashorn is a JavaScript engine.
2. Stream operations
Streams are sequence of elements which are retrived from the underlying
Collection - on which we can apply sequence/parallel of operations.
These operations are of 2 types
1. Intermediate operation - results in Stream by which we can form pipeline
of intermediate operations
2. Terminate operation
1. Intermediate operations
filter() - to filter based on condition
map() - apply given statement
flatMap()
unsorted()
sorted()
sorted(Comparator)
distinct()
limit(max)
2. Terminal operations
count()
sum()
average()
Optional max(Comparator)
Optional min(Comparator)
findFirst()
findAny()
orElse()
mapToInt()
collector(
Collectors.toList()
.toSet()
.toMap()
.summingInt(...)
.averagingInt(...)
.joining(", ")
)
___________________________________________________________________________________
____________
1: Skip access-specifier
2: Skip return-type (Java knows it by refering the related
@FunctionalInterface)
3: Skip method-name
4: Lambda syntax: () -> {};
5: for one-liner Skip {}
6: for one-liner Skip return
7: Skip argument types (Java knows it by refering the related
@FunctionalInterface)
8: for one-argument we can also Skip ()
Eg: s -> s.length()
9: Method Reference
Eg: System.out::println
___________________________________________________________________________________
____________
4. Hibernate Topics
What is Hibernate? ORM?
Hibernate architecture
Hibernate features
Hibernate Dialects
Advantage of Hibernate over JDBC?
Key interfaces of Hibernate
--Persistent Life cycle
Configuration in Hibernate
- Hibernate sample code
Criteria
Query
session.createQuery
session.createSQLQuery
.list()
.scroll()
.executeUpdate()
get() vs load()
persist() vs save() vs saveOrUpdate()
update() vs merge()
update() vs lock()
openSession() vs getCurrentSession() ?
Fetching strategies
Hibernate Caching
- Caching strategies
@Immutable
How to show generated Hibernate SQL?
Composite Primary-Key
How to call SP?
How to connect Multiple DBs?
Hibernate Pagination?
___________________________________________________________________________________
____________
5. Spring Topics
What is Spring Framework?
Spring is an light-weight open-source framework that facilitates easy
Java/J2EE development.
Spring Framework is created to address the complexity involved in the
Java/J2EE application development.
Spring framework is very popular in the market because of its features like
DI
AOP
Light-weight POJO based development.
Spring is layered architecture that comes with various Modules and we can
choose on our project demand.
Spring is considered as Frameworks of Framework.
Spring features?
Spring Modules?
DI? advantages?
IoC Container
<beans>
-BeanFactory
-ApplicationContext
Types of injection
- Constructor Injection
- Setter Injection
Autowired?
different Modes of Autowiring?
What is Spring configuration file?
What is a Spring Bean?
What are different ways to configure a class as Spring Bean?
<bean> scope?
<context:annotation-config/>
<context:component-scan base-package="base.package">
@Qualifier
@Required
Steps to create J2EE application using Spring
PropertyPlaceholderConfigurer
- Java 6
Common Annotations (JSR 250)
Java API for XML Based Web Services – 2.0 (JSR 224)
JAXB 2.0 (JSR 222)
Web Services Metadata (JSR 181)
Streaming API for XML (JSR 173)
- Java 7
1. String literal in switch
2. Binary literal
int mask = Integer.parseInt("10001", 2); // old_way
int mask1 = 0b10001; // new way
3. Underscore between numeric literals
int oneMillion_ = 1_000_000; // new_way
4. Diamond Syntax - Simplifies Collection declaration
Map<Integer, List<String>> list = new HashMap<Integer,
List<String>>();
// new way
Map<Integer, List<String>> list1 = new HashMap<>();
5. Catching Multiple Exception Types
6. Try with Resource
___________________________________________________________________________________
____________
8. MongoDB Operations
- Show all Databases
- Current Database
- Create Database
- Drop Database
- Create Collection
- Delete Collection
- Insert Document to Collection
- Query Documents - AND, OR, Logical-Operator
- Delete Document
- Update Document
@Field
@Id
@Indexed
@Indexed(unique=true)
___________________________________________________________________________________
____________
9. Hibernate Annotation
@Entity
@Table (name="USER_DETAILS")
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="BOOK_NAME",
length=80,
nullable=false,
unique=true)
String bookName;
@Temporal (TemporalType.DATE)
- TemporalType.TIME
- TemporalType.TIMESTAMP - // default
@Lob
@Transient
@OrderBy
@SequenceGenerator
@DynamicUpdate
@DynamicInsert
@SelectBeforeUpdate
@Immutable
@Embeddable
@Embedded
@EmbeddedId
-----
@JoinColumn(name="DEPT_CODE", referencedColumnName="DEPT_ID")
@JoinColumns({
@JoinColumn(name="ADDR_ID", referencedColumnName="ID"),
@JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP")
})
Emp {
...
@OneToOne
@JoinColumn(name="EMP_DET_ID")
EmpDetails empDetails;
}
Emp {
...
@ManyToOne
@JoinColumn(name="DEPT_ID")
Dept dept;
}
Dept {
...
@OneToMany
@JoinColumn(name="EMP_ID")
Set<Emp> emps;
}
@JoinTable
@ManyToMany
@Component
@Service
@Controller
@Repository
@Autowired
@Qualifier
@Inject
@PostConstruct
@PreDestroy
@Lazy
@DependsOn
@ProperySource
PropertyPlaceHolderConfigurer
@Value
@Configuration
@ComponentScan
@Bean
@Import
@ImportResource
<context:annotation-config/>
<context:component-scan base-package="base.package">
@Async
@Scheduled
// To Enable Spring TaskExecutor
<task:annotation-driven>
@Transactional
<tx:annotation-driven />
JUnit
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
-----
@RestController
@RequestMapping
@RequestParam
@ResponseBody
@RequestBody
@PathVariable
@RequestHeader
@ModelAttribute
___________________________________________________________________________________
____________
@Test
@Before
@After
@Ignore
---
@RunWith(org.junit.runner.JUnitCore) // default
---
Spring
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={AppConfig.class, TestConfig.class})
---
@Mock
@InjectMock
@RunWith(MockitoJUnitRunner.class)
___________________________________________________________________________________
____________
12. REST
What is REST?
REST stands for REprestational State Transfer is an architectual style
(set of principles) to develop distributed systems.
REST style is well utilized by Webservice and REST Service are more
popular now and fastly replaced (heavy-weight) SOAP Webservices.
REST is not very new technology - its a set of principle applied over
the existing technologies to create better and faster services..
HTTP, HTTP Methods, URI.
With REST everything is considered as a Resource - an Object, DB Table,
Image..
and each Resource is given an unique URI.
HTTP Methods are well utilized for Resource exposure.
Idempotence
REST principles on HTTP Methods?
JAX-RS?
JAX-RS implementation?
Jersey
RESTEasy
JAX-RS Annotations?
@Path @Get @Post @Delete @Put @Cosumes @Produce @PathParam @QueryParam
REST Client?
HttpURLConnection
RestTemplate
GSON
___________________________________________________________________________________
____________
13. SOAP
___________________________________________________________________________________
____________
SOAP vs REST
___________________________________________________________________________________
____________
14. J2EE
___________________________________________________________________________________
____________
-Creational Pattern
1. Singleton Pattern
java.lang.Runtime.getRuntime()
Spring Container default
2. Factory Pattern
Integer.valueOf()
java.util.Calendar.getInstance()
3. Abstract Factory Pattern
Factory of Factory Pattern
4. Prototype Pattern
java.lang.Object#clone()
5. Builder Pattern
java.lang.StringBuilder#append() (unsynchronized)
java.lang.StringBuffer#append() (synchronized)
-Structural Pattern
1. Adapter Pattern
Wrapper classes (Integer) - the Primary types are handled as
Objects
2. Decorator Pattern
java.util.Collections, the checkedXXX(), synchronizedXXX() and
unmodifiableXXX() methods.
javax.servlet.http.HttpServletRequestWrapper and
HttpServletResponseWrapper.
3. Facade Pattern
Facade Design Pattern is one of the Structural design patterns.
Facade design pattern is used to help client applications to easily interact with
the system.
4. Filter Pattern
"Criteria" object in Hibernate is a best example.
5. Flyweight Pattern
Java String literal pool
String str = "Raja";
java.lang.Integer.valueOf(int)
6. Proxy pattern
java.lang.reflect.Proxy
java.rmi.*
javax.persistence.PersistenceContext
7. Composite pattern
-Behavioral Pattern
1. Chain of Responsibility pattern
Servlet Filters
try-catch (multiple catch)
2. Iterator pattern
3. Memento pattern
java.io.Serializable
4. Observer pattern
Event Listeners:
javax.servlet.http.HttpSessionBindingListener
javax.servlet.http.HttpSessionAttributeListener
5. Strategy pattern
java.util.Comparator#compare(), executed by among others
Collections#sort().
6. State pattern
Java Threads life-cycle
7. Command Pattern
-J2EE Patterns
1. Front Controller
2. MVC
3. Business Object Pattern (BOM)
4. Data Transfer Object (DTO)
5. Data Access Object (DAO)
6. Intercepting Filter
___________________________________________________________________________________
____________
JCF?
List
Set
How Hashtable works?
equals() vs hashcode()
iterator -- Traversing object
- remove()
ArrayList vs Vector
LinkedList use case -- ToDo List
What is Fail Fast in Iterator?
ListIterator
How to convert array to List?
How do you traverse through a collection using its Iterator?
Map implementations
Hashtable is a Map implementations
Hashtable vs HashMap
• Iterator in HashMap is fail-fast where as enumerator for the Hashtable
is not.
keySet()
values()
entrySet()
ConcurrentHashMap
CopyOnWriteArray
BlockingQueue
___________________________________________________________________________________
____________
What is MultiThreading?
What is Thread?
How to create Threads in Java?
--Thread life-cycle
Java synchronization
Class level synchronization
Deadlock?
- Sample code
- How to avoid it?
Demon Thread
wait() vs sleep()
Inter-thread communication
wait(), notify() and notifyAll()
Executor Framework
- ExecutorSevice
newCachedThreadPool
fixedCachedThreadPool
___________________________________________________________________________________
____________
Learnings:
2. Streams
So, its wise to use parallelStream() for operating huge amount of data.
- flatMap()
flatMap converts the Stream of collections, say Stream<Set<String>>
into a flat Stream Stream<String>.
3. MongoDB handling in Spring Boot
- The APIs to handle MongoDB connection are directly from 'Spring Boot
Framework' itself - it is no way related to JPA.
Annotations such as
@Document
@Id (_id)
@Indexed
are from Spring libraries.
4. POST vs PUT
- save() vs saveOrUpdate()
---
Microservice - Each of the 'Service' in a Microservice Architecture is Autonomous -
means it can independendly Developed, Deployed, Managed and Scaled, without
affecting the functioning of other services.
Each Service owns its data (DB) which is not shared with other services.
If any other service needs to access these data, it must communicate with the
owning service.
Advantages:
Flexible Scaling