IQ, Java

OneLine - Java

|
Divnesh BLOG


JPA Hibernate
Java Persistence API (JPA) defines the management of relational data in the Java applications. Hibernate is an Object-Relational Mapping (ORM) tool which is used to save the state of Java object into the database.
It is just a specification. Various ORM tools implement it for data persistence. It is one of the most frequently used JPA implementation.
It is defined in javax.persistence package. It is defined in org.hibernate package.
The EntityManagerFactory interface is used to interact with the entity manager factory for the persistence unit. Thus, it provides an entity manager. It uses SessionFactory interface to create Session instances.
It uses EntityManager interface to create, read, and delete operations for instances of mapped entity classes. This interface interacts with the persistence context. It uses Session interface to create, read, and delete operations for instances of mapped entity classes. It behaves as a runtime interface between a Java application and Hibernate.
It uses Java Persistence Query Language (JPQL) as an object-oriented query language to perform database operations. It uses Hibernate Query Language (HQL) as an object-oriented query language to perform database operation

Transaction

A Transaction is a unit of work in which all the operations must be executed or none of them. To understand the importance of transaction, think of an example which applies on all of us i.e. Transferring Amount from one account to another as this operation includes the below two steps:

  • Deduct the balance from the sender’s bank account
  • Add the amount to the receiver’s bank account
Now think a situation where the amount is deducted from sender’s account but is not delivered to receiver’s account due to some errors. Such issues are managed by the transaction management where both steps are performed in a single unit. In the case of a failure, the transaction should be roll-backed.
It maintains the abstraction from the transaction implementation (JTA, JDBC). A Transaction is associated with Hibernate Session and instantiated by calling the 
sessionObj.beginTransaction()

ACID

  • Atomicity: Is defined as either all operations can be done or all operation can be undone
  • Consistency: After a transaction is completed successfully, the data in the datastore should be a reliable data. This reliable data is also called as consistent data
  • Isolation: If two transactions are going on the same data then one transaction will not disturb the other transaction
  • Durability: After a transaction is completed, the data in the datastore will be permanent until another transaction is going to be performed on that data
Hibernate :

Create :  
sessionFactory=HibernateUtility.createSessionFactory();
session=sessionFactory.openSession();
CustomerEntity ce=new CustomerEntity();
ce.setCustomerId(5004);
ce.setCustomerName("Kiran");
session.getTransaction().begin();
session.persist(ce);
session.getTransaction().commit();

Integer customerPK = (Integer)session.save(ce);
Read :
 CustomerEntity ce=(CustomerEntity) session.get(CustomerEntity.class, customerId);
 return null if not found
CustomerEntity ce=(CustomerEntity) session.load(CustomerEntity.class, customerId);
throws exception
Update :
CustomerEntity ce=(CustomerEntity) session.get(CustomerEntity.class, id);
if(ce!=null){
      customerId=ce.getCustomerId();
      session.getTransaction().begin();
      ce.setContactNumber(newPhoneNumber);
      session.getTransaction().commit();
}

Delete  :
session.delete(ce);
blob : 
Blob image=Hibernate.getLobCreator(session).createBlob(fis, file.length());

@GenericGenerator(name="generatorName",strategy="sequence")
@GeneratedValue(generator="generatorName")

@GenericGenerator(name="generatorName",strategy="sequence",
parameters={@Parameter(name="sequence",value="DB_CustomerId_PK")})

Strategy -- sequence , increment , native , assigned (default)

Composite primary  key
@idClass
@EmbeddedId
table: Customer / Loan / CustomerLoan
==========================
@Entity(name="customerLoan")
@IdClass(CustomerLoanPK.class)
public class CustomerLoanEntity {
 @Id
 private Integer customerId;
 @Id
 private String loanId;
----
public class CustomerLoanPK implements Serializable {
 private Integer customerId;
 private String loanId; 
====================================
@Entity(name="customerLoan")
public class CustomerLoanEntity {
 @EmbeddedId
 private CustomerLoanPK pk;
 private Double eligibleAmount;

@Embeddable
public class CustomerLoanPK implements Serializable {
 private Integer customerId;
 private String loanId;
=======================================
Customer - Locker
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="lockerId", unique=true)


-------------------------------------------------------------------------
Customer - account --- many accounts can be held by a customer
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="customerId")
-----------------------------------------------------------------------
table: Customer / Loan / CustomerLoan @ManyToMany(cascade=CascadeType.ALL)
@JoinTable(name="customerLoan",
joinColumns=@JoinColumn(name="
customerId", referencedColumnName="customerId"),
inverseJoinColumns=@JoinColumn(name="
loanId", referencedColumnName="loanId")) CustomerLoan table Inheritance
@Inheritance(strategy=InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name="accountType")Entity @DiscriminatorValue("SavingsAccount") HQL Query query = session.createQuery(hql); List list = query.list() @NamedQuery(name ="CustomerEntity.retrieve", query ="from CustomerEntity") session.getNamedQuery("CustomerEntity.retrieve"); @NamedQueries({ @NamedQuery(name ="CustomerEntity.update", query ="update CustomerEntity CE set CE.address=?,
        CE.contactNumber=? where CE.customerName=? and CE.dateOfBirth=?") ,@NamedQuery(name="CustomerEntity.retreive", query="from CustomerEntity") })

Criteria criteria=session.createCriteria(CustomerEntity.class);
Criterion condition1 = Restrictions.like("address", searchString+"%");
Criterion condition2 = Restrictions.isNotNull("contactNumber");                   
criteria.add(Restrictions.and(condition1,condition2));
ProjectionList requiredColumns = Projections.projectionList();
requiredColumns.add(Projections.property("customerName"));
requiredColumns.add(Projections.property("address")); 
criteria.setProjection(requiredColumns);
   
List Object[] cusList=criteria.list()
@Cacheable
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
TRANSACTIONAL
READ_WRITE
NONSTRICT_READ_WRITE
READ_ONLY void SessionFactory.getCache.evictEntity(EntityClass.class, primarykey) 


SpringBoot :

Bean Scope :

The lifetime of a bean depends on its scope. Bean's scope can be defined while declaring it in the configuration metadata file.

A bean can be in singleton or prototype scope. A bean with the "singleton" scope is initialized during the container starts up and the same bean instance is provided for every bean request from the application. However, in the case of the "prototype" scope, a new bean instance is created for every bean request from the application.

@Scope("singleton")

@Scope("prototype")

@Value annotation is used to insert values into variables and method arguments. Using @Value we can either read spring environment variables or system variables. 

If more than one beans of the same type are available in the container, then the framework throws an exception indicating that more than one bean is available for autowiring. To handle this @Qualifier annotation is used

public class CustomerServiceImpl {
@Autowired
        @Qualifier("custRepo")
private CustomerRepository customerRepository;
AOP :
AOP ensures that cross cutting concerns are kept separate from the core business logic.

Type Of Execution

Execution Point

Before

Before advice is executed before the Joinpoint execution.

After

 After advice will be executed after the execution of Joinpoint whether it returns with or without exception. Similar to finally block in exception handling.

AfterReturning

 AfterReturning advice is executed after a Joinpoint executes and returns successfully without exceptions

AfterThrowing

 AfterThrowing advice is executed only when a Joinpoint exits by throwing an exception

Around

Around advice is executed around the Joinpoints which means Around advice has some logic which gets executed before Joinpoint invocation and some logic which gets executed after the Joinpoint returns successfully


BASE OF COMPARISON

FAIL FAST ITERATOR

FAIL SAFE ITERATOR

Exception                         

It throws a ConcurrentModificationException in modifying the object during the iteration process.

It does not throw Exception.

Clone Object

No clone object is created during the iteration process.

A copy or clone object is created during the iteration process.

Memory utilization

It requires low memory during the process.

It requires more memory during the process.

Modification

It does not allow modification during iteration.

It allows modification during the iteration process.

Performance

It is fast.

It is slightly slower than Fail Fast.

Examples

HashMap, ArrayList, Vector, HashSet, etc

CopyOnWriteArrayList, ConcurrentHashMap, etc.





Authentication and authorization might sound similar, but they are distinct security processes in the world of identity and access management (IAM). Authentication confirms that users are who they say they are. Authorization gives those users permission to access a resource

Hystrix – the fault tolerance library. We’ll use the library and implement the Circuit Breaker enterprise pattern
Hystrix is watching methods for failing calls to related services. If there is such a failure, it will open the circuit and forward the call to a fallback method.

The library will tolerate failures up to a threshold. Beyond that, it leaves the circuit open. Which means, it will forward all subsequent calls to the fallback method, to prevent future failures. This creates a time buffer for the related service to recover from its failing state.

Inversion of Control (IoC) means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside source (for example, an xml configuration file).

Dependency Injection (DI) means that this is done without the object intervention, usually by a framework component that passes constructor parameters and set properties.

Just-in-time compilation is a way of executing computer code that involves compilation during execution of a program – at run time – rather than before execution

lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.

The @SpringBootApplication is a combination of three annotations @Configuration (used for Java-based configuration), @ComponentScan (used for component scanning), and @EnableAutoConfiguration (used to enable auto-configuration in Spring Boot)

Different ways to run method after startup in spring boot link
  • Using CommandLineRunner interface
  • With ApplicationRunner interface
  • Spring boot Application events
  • @Postconstruct annotation on a method
  • The InitializingBean Interface
  • Init attribute of @bean annotation
Optional is a container object which may or may not contain a non-null value. You must import java.util package to use this class. If a value is present, isPresent() will return true and get() will return the value. Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() which returns a default value if value not present and ifPresent() which executes a block of code if the value is present. This is a value-based class, i.e their instances are :
  • Final and immutable (though may contain references to mutable objects).
  • Considered equal solely based on equals(), not based on reference equality(==).
  • Do not have accessible constructors.



import java.util.Optional;
public class OptionalExample {
    public static void main(String[] args) {
        String[] str = new String[10];
str[5] = "JAVA OPTIONAL CLASS EXAMPLE"; // Setting value for 5th index
// It returns an empty instance of Optional class
Optional<String> empty = Optional.empty();
System.out.println(empty);
// It returns a non-empty Optional
Optional<String> value = Optional.of(str[5]);
// If value is present, it returns an Optional otherwise returns an empty Optional
System.out.println("Filtered value: "+value.filter((s)->s.equals("Abc")));
System.out.println("Filtered value: "+value.filter((s)->s.equals("JAVA OPTIONAL CLASS EXAMPLE")));
// It returns value of an Optional. if value is not present, it throws an NoSuchElementException
System.out.println("Getting value: "+value.get());
// It returns hashCode of the value
System.out.println("Getting hashCode: "+value.hashCode());
// It returns true if value is present, otherwise false
System.out.println("Is value present: "+value.isPresent());
// It returns non-empty Optional if value is present, otherwise returns an empty Optional
System.out.println("Nullable Optional: "+Optional.ofNullable(str[5]));
// It returns value if available, otherwise returns specified value,
System.out.println("orElse: "+value.orElse("Value is not present"));
System.out.println("orElse: "+empty.orElse("Value is not present"));
value.ifPresent(System.out::println); // printing value by using method reference 
    }
}

Optional.empty
Filtered value: Optional.empty
Filtered value: Optional[JAVA OPTIONAL CLASS EXAMPLE]
Getting value: JAVA OPTIONAL CLASS EXAMPLE
Getting hashCode: -619947648
Is value present: true
Nullable Optional: Optional[JAVA OPTIONAL CLASS EXAMPLE]
orElse: JAVA OPTIONAL CLASS EXAMPLE
orElse: Value is not present
JAVA OPTIONAL CLASS EXAMPLE

Streams

//employee name whose salary is greater than 50k
List<Employee> list = new ArrayList<>(); 
list.add(new Employee("vikki",67000)); 
list.add(new Employee("divya",35000)); 
list.add(new Employee("divya",30000));

long t1 = System.currentTimeMillis(); 
List<String> finall = list.stream().filter(p->p.getSalary()>50000).map(p ->p.getName()) .collect(Collectors.toList()); finall.stream().forEach(x->System.out.println(x)); 
long t2 = System.currentTimeMillis(); 
System.out.println("Sequential Stream Time taken:" + (t2 - t1));

t1 = System.currentTimeMillis(); 
List<String> finall1 = list.parallelStream().filter(p->p.getSalary()>50000).map
(p->p.getName()).collect(Collectors.toList()); finall1.stream().forEach(x->System.out.println(x)); t2 = System.currentTimeMillis(); 
System.out.println("Parallel Stream Time taken:" + (t2 - t1)); 

double total = list.stream().collect(Collectors.summingInt(Employee::getSalary)); System.out.println(total); 

--------------------------------------------------------------------------------------------------------------------------
//frequenct of character
 List<String> value = new ArrayList<>(); 
 value.add("a"); 
 value.add("b"); 
 value.add("c"); 
 value.add("a"); 
 List<String> listof = Arrays.asList("B", "A", "A", "C", "B", "A"); 
 Set<String> distinct = new HashSet<>(listof); 
 for (String s: distinct) { 
     System.out.println(s + ": " + Collections.frequency(listof, s)); 
 } 
--------------------------------------------------------------------------------------------------------------------------
//Frequency of each character in a string

Map<String,Long> mapper = listof.stream().collect(Collectors.groupingBy
(x->x,Collectors.counting())); 
mapper.entrySet().stream().forEach(System.out::println);

String str = "malayalam"; 
List<String> chararray = Arrays.asList(str.split("")); chararray.parallelStream().collect(Collectors.groupingBy(x->x,Collectors.counting()))
.entrySet().stream().sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
.forEach(System.out::println);

str.chars().mapToObj(c->(char)c).collect(Collectors.groupingBy(c->c,Collectors.counting())).entrySet().forEach(System.out::println);

String s = "malayalam";
List<Integer> integers = IntStream.range(0,s.length()).boxed().collect(Collectors.toList());
HashMap<Character,Integer> hashMap = new HashMap<>();
integers.forEach(s1->
        {
            if (hashMap.containsKey(s.charAt(s1))) {
                int cnt = hashMap.get(s.charAt(s1));
                hashMap.put(s.charAt(s1),++cnt);
            }
            else {
                hashMap.put(s.charAt(s1),1);
            }
        });
        System.out.println(hashMap);
    }
--------------------------------------------------------------------------------------------------------------------------
//To remove duplicates

List<Department> deptList = new ArrayList<>();
deptList.add(new Department(1, "IT"));
deptList.add(new Department(2, "HR"));
deptList.add(new Department(1, "IT"));
deptList.add(new Department(4, "Development"));
deptList.add(new Department(2, "HR"));
deptList.stream().collect(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Department::getDeptName))))  .forEach(x->System.out.println(x.getDeptId()+x.getDeptName()));
--------------------------------------------------------------------------------------------------------------------------
String[] aa = {"a:apple","a:am","b:ball","b:bat","c:cat"};

Arrays.stream(aa).map(x -> String.valueOf(x)).map(x -> x.split(":"))
.collect(Collectors.groupingBy(x -> x[0], Collectors.mapping(x -> x[1], Collectors.toList())))
.entrySet().forEach(System.out::println);
--------------------------------------------------------------------------------------------------------------------------

Map<String, Long> m3 = Stream.concat(m1.entrySet().stream(), m2.entrySet().stream()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(v1,v2)->v1+v2));

m3.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).forEach(System.out::println);
m3.entrySet().stream().map(x->x.getValue()).collect(Collectors.toSet()).forEach(System.out::println);
--------------------------------------------------------------------------------------------------------------------------
String[] aa = {"a:apple","a:am","b:ball","b:bat","c:cat"};

List<String> ss = Arrays.stream(aa).map(x -> String.valueOf(x)).map(x -> x.split(":"))
.collect(Collectors.groupingBy(x -> x[0], Collectors.mapping(x -> x[1], Collectors.toList())))
.values().stream().flatMap(Collection::stream).collect(Collectors.toList());
--------------------------------------------------------------------------------------------------------------------------
//How to find third highest salary in below array list using Java8 streams

employeeList.stream().sorted(Comparator.comparing(Employee::getSalary).reversed()).skip(2).limit(1).map(Employee::getName).collect(Collectors.toList()).forEach(System.out::println);
--------------------------------------------------------------------------------------------------------------------------
//To  get first highest salary by each dept

employeeList.stream()
.collect(
Collectors.groupingBy(Employee::getDepartment,
Collectors.collectingAndThen(
Collectors.maxBy(Comparator.comparing(Employee::getSalary)), Optional::get)))
.entrySet().stream().forEach(System.out::println);
--------------------------------------------------------------------------------------------------------------------------
//To  get secound highest salary by each dept

employeeList.stream()
.collect(Collectors.groupingBy(Employee::getDepartment,
Collectors.collectingAndThen(Collectors.toList(),
e -> e.stream().sorted(Comparator.comparing(Employee::getSalary).reversed())
.skip(1)
.limit(1)
.map(Employee::getName)
.collect(Collectors.toList()))))
.entrySet().stream().forEach(System.out::println);
---------------------------------------------------------------------------------------------------------------

String s = "I am a happy_bear and I sk@8 because it's gr8";

String d = s.codePoints()
    .filter(c -> Character.isLetter(c) || c == '_' || c == ' ')
    .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
    .toString();

--------------------------------------------------------------------------------------------------------------------------
// return employee name based on gender
employeeList.stream().collect(Collectors.partitioningBy(x->  x.getGender().equals("Male"),Collectors.mapping(Employee::getName, Collectors.toList()))).entrySet().stream().filter(x->x.getKey()).map(x-> x.getValue()).forEach(System.out::println);;

employeeList.stream().collect(Collectors.partitioningBy(x -> x.getGender().equals("Male"))).entrySet().stream()
.filter(x -> x.getKey())
.map(x -> x.getValue().stream().map(Employee::getName).collect(Collectors.joining(",")))
.forEach(System.out::println);    

---------------------------------------------------------------------------------

public static void main(String[] args) {
String input = "({)}[]";
Map<String, String> map = new HashMap<String, String>();
map.put("}", "{");
map.put("]", "[");
map.put(")", "(");
boolean isvalid = true;
Stack<String> stack = new Stack<String>();
if (input.length() % 2 == 0) {
for (String s : input.split("")) {
if (s.equals("{") || s.equals("[") || s.equals("(")) {
stack.push(s);
} else if (!map.get(s).equals(stack.pop())) {
isvalid = false;
break;
}
}
}else {
isvalid=false;
}
System.out.println(isvalid?"balanced":"not balanced");

}


--------------------------------------------------------------------------------------------------------------------------

@SuppressWarnings({ "unchecked", "rawtypes" })
public class SingleLinkedList {

private Node head;

public static void main(String[] args) {
SingleLinkedList linkedlist = getDefaultList();
System.out.println("linked list before reversing : " + linkedlist);
System.out.println(linkedlist.getLastNode(2));
linkedlist.reverseIteratively();
System.out.println("linked list after reversing : " + linkedlist);
System.out.println(linkedlist.getLastNode(2));
System.out.println(linkedlist.getmiddle());
}

private static SingleLinkedList getDefaultList() {
SingleLinkedList linkedlist = new SingleLinkedList();
linkedlist.append("A");
linkedlist.append("B");
linkedlist.append("C");
linkedlist.append("D");
linkedlist.append("E");
linkedlist.append("F");
return linkedlist;
}

public <T> void append(T data) {
if (head == null) {
head = new Node(data);
return;
}
tail().next = new Node(data);
}

private Node tail() {
Node tail = head;

while (tail.next != null) {
tail = tail.next;
}
return tail;
}

public int length() {
int length = 0;
Node current = head;
while (current != null) {
length++;
current = current.next;
}
return length;
}

public  String getLastNode(int n) {
Node fast = head;
Node slow = head;
int start = 1;
while (fast.next != null) {
fast = fast.next;
start++;
if (start > n) {
slow = slow.next;
}
}
return (String) slow.data;
}
public  String getmiddle() {
Node fast = head;
Node slow = head;
int start = 1;
while (fast.next != null) {
fast = fast.next;
start++;
if (start%2==0) {
slow = slow.next;
}
}
return (String) slow.data;
}

@Override
public String toString() {
StringBuilder sb = new StringBuilder();
Node current = head;
while (current != null) {
sb.append(current).append("-->");
current = current.next;
}
System.out.println(sb.toString() + " : " + sb.length());
if (sb.length() >= 3) {
sb.delete(sb.length() - 3, sb.length());
}
return sb.toString();
}
public void reverseIteratively() {
Node current = head;
Node previous = null;
Node forward = null;
while (current.next != null) {
forward = current.next; //b c d e f
System.out.println("forward"+forward);
current.next = previous; //null a b c d
System.out.println("current.next"+current.next);
previous = current; // a b c d e
System.out.println("previous"+previous);
current = forward; // b c d e f
System.out.println("current"+current);
System.out.println("-----------");
}
head = current;
head.next = previous;
}
private static class Node<T> {
private Node next;
private T data;
public Node(T data) {
this.data = data;
}
@Override
public String toString() {
return data.toString();
}
}

}

--------------------------------------------------------------------------------------------------------------------------

static void printSubsets(char set[]) {
int n = set.length;
for (int i = 0; i < Math.pow(2, n); i++) {
for (int j = 0; j < n; j++) {
if ((i & (1 << j)) > 0) {
System.out.print(set[j] + " ");
}
}
System.out.println();
}
}
static Queue<Integer> queue;

// Function to reverse the first
// K elements of the Queue
static void reverseQueueFirstKElements(int k) {
if (queue.isEmpty() == true || k > queue.size())
return;
if (k <= 0)
return;

Stack<Integer> stack = new Stack<Integer>();

// Push the first K elements into a Stack
for (int i = 0; i < k; i++) {
stack.push(queue.peek());
queue.remove();
}

// Enqueue the contents of stack
// at the back of the queue
while (!stack.empty()) {
queue.add(stack.peek());
stack.pop();
}

// Remove the remaining elements and enqueue
// them at the end of the Queue
for (int i = 0; i < queue.size() - k; i++) {
queue.add(queue.peek());
queue.remove();
}
}

// Utility Function to print the Queue
static void Print() {
while (!queue.isEmpty()) {
System.out.print(queue.peek() + " ");
queue.remove();
}
}

static void powerSet(String str, int index, String curr)

{
int n = str.length();
// base case
if (index == n) {
System.out.println(curr);
return;
}

/**
* Two cases for every character (i) We consider the character as part of current subset
* (ii) We do not consider current character as part of current subset
**/
powerSet(str, index + 1, curr + str.charAt(index));
powerSet(str, index + 1, curr);

}
2^n
--------------------------------------------------------------------------------------------------------------------------




Featured Post

HTML cheetsheet

List: Link tgs Dropdown

Popular Post

(C) Copyright 2018, All rights resrved InShortView. Template by colorlib