- Inner class is a class defined inside other class and act like a member of the enclosing class.
- There are two main types of inner classes
- Static member class
- Inner class
- Member class
- Anonymous class
- Local class
- Static member class
- A static member class behaves much like an ordinary top-level class, except that it can access the static members of the outer.
- Outer class can access all inner class fields by referring Inner Class.(InnerA.printAnimal()). But inner class can access all static outer class properties and methods directly.
- Both inner and outer classes can access others private properties and methods.
- The static nested class can be accessed as the other static members of the enclosing class without having an instance of the outer class.
- The static class can contain non-static and static members and methods.
- InnerClassTest1.java
public class InnerClassTest1 { private static int out = 1; public static class innerA { private static int number = 10; static void printAnimal(String animal) { System.out.println(out); System.out.println(animal); test(); } } private static void test() { System.out.println(innerA.number); } }
- App.java
public class App { public static void main(String[] args) { InnerClassTest1.innerA.printAnimal("Tiger"); } }
- Member class
- Need to create Instance access properties and class out side the method.
- Need Outer class object to create inner class object.
- The member class can be declared as public, private, protected, final and abstract. E.g.
- InnerClassTest2.java
public class InnerClassTest2 { private int out = 1; public class MemberClass { private void showName() { System.out.println("Sonu"); System.out.println(out); } } public void test() { MemberClass m = new MemberClass(); m.showName(); } }
- App.java
public class App { public static void main(String[] args) { InnerClassTest2 o = new InnerClassTest2(); InnerClassTest2.MemberClass m = o.new MemberClass(); } }
- Local class
- It can be accessed only from same method.
- Local classes cannot be public, private, protected, or static. (No access modifiers)
- Local class can access all outer class properties and methods.
- local class can access local variables and parameters of the enclosing method that are effectively final.
- InnerClassTest3.java
public class InnerClassTest3 { int outerNumber = 1; public void methodTest() { int methodNumber = 2; class MethodLocalClass { private void showName() { System.out.println("SONU"); System.out.println(outerNumber); System.out.println(methodNumber); test(); } } methodNumber = 2; //error outerNumber =3; //will work MethodLocalClass m = new MethodLocalClass(); m.showName(); } public void test() { System.out.println("TEST"); } }
- Anonymous class
- These are local classes which are automatically declared and instantiated in the middle of an expression.
- Also, like local classes, anonymous classes cannot be public, private, protected, or static.
- They can define in the arguments to the constructor of the outerclass, but cannot otherwise have a constructor.
- They can implement only one interface or extend a class.
- Anonymous class cannot define any static fields, methods, or classes, except for static final constants.
- xxxx
Saturday, 29 December 2018
Java Innerclass
Friday, 21 December 2018
JDBC Interview Questions
- ACID Properties in DBMS?
- A transaction is a single logical unit of work which accesses and possibly modifies the contents of a database. Transactions access data using read and write operations.In order to maintain consistency in a database, before and after transaction, certain properties are followed. These are called ACID properties.
- Atomicity
- By this, we mean that either the entire transaction takes place at once or doesn’t happen at all. There is no midway i.e. transactions do not occur partially. Each transaction is considered as one unit and either runs to completion or is not executed at all.
- Consistency
- This means that integrity constraints must be maintained so that the database is consistent before and after the transaction. It refers to correctness of a database.
- Isolation
- This property ensures that multiple transactions can occur concurrently without leading to inconsistency of database state. Transactions occur independently without interference. Changes occurring in a particular transaction will not be visible to any other transaction until that particular change in that transaction is written to memory or has been committed. This property ensures that the execution of transactions concurrently will result in a state that is equivalent to a state achieved these were executed serially in some order.
- Durability
- This property ensures that once the transaction has completed execution, the updates and modifications to the database are stored in and written to disk and they persist even is system failure occurs. These updates now become permanent and are stored in a non-volatile memory.
- The effects of the transaction, thus, are never lost.
Hibernate Interview Questions
- filter employees with same salary count greater than five (group by salary) using hibernate criteria?
Session session = getCurrentSession(); ProjectionList projectionList = Projections.projectionList(); projectionList.add(Projections.groupProperty("totalCode")) .add(Projections.groupProperty("activityCode")) .add(Projections.sum("amount")) .add(Projections.rowCount()); Criteria criteria = session.createCriteria(Payment.class); criteria.setProjection(projectionList); List
- What is Hibernate N+1 Problems and its Solution?
- Hibernate n+1 problems only comes for one to many relationship.
- Let us see this problem by example – We have Department table with a one-to-many relationship with Employee. One Department may have many Employees.
- We have written the Hibernate Department Entity as below.
@Entity public class Department { private Long id; @OneToMany private Employee[] Employees; }
- So now you want to print out all the details of Employee models. A native O/R implementation would SELECT all Department and then do N additional SELECTs for getting the information of Employee for each department.
- -- To Get all Departments SELECT * FROM Department; -- To get each Employee, get Employee details SELECT * FROM Employee WHERE Employee.departmentId = ?
- As you see, the N+1 problem can happen if the first query populates the primary object and the second query populates all the child objects for each of the unique primary objects returned.
- Solution for Hibernate N+1 Problem
- Using HQL fetch join
- You can use the fetch while using the HQL as below example.
from Department d join fetch d.employees Employee
- Hibernate Generated SQL would be similer as –
SELECT * FROM Department d LEFT OUTER JOIN Employee e ON d.id = d.department_id
- Using Criteria query
Criteria criteria = session.createCriteria(Department.class); criteria.setFetchMode("employees", FetchMode.EAGER);
- In both above cases, the query returns a list of Department objects with the Employee initialized, and only one query needs to be run to return all the Department and Employee information required.
Friday, 7 December 2018
Java program to capitalize first letter of each word in string
public class FirstWordUpperCase {
public static void main(String[] args) {
System.out.println(changeString("how are you man"));
}
private static String changeString(String str) {
StringBuffer sb = new StringBuffer();
String[] arr = str.split("\\s");
for (int i = 0; i < arr.length; i++) {
sb.append(Character.toUpperCase(arr[i].charAt(0))).
append(arr[i].substring(1)).append(" ");
}
return sb.toString();
}
}
JSP Interview Questions
- How to disable caching on back button of the browser?
-
<% response.setHeader(“Cache-Control”,”no-store”); response.setHeader(“Pragma”,”no-cache”); response.setHeader (“Expires”, “0”); //prevents caching at the proxy server %>
Wednesday, 5 December 2018
Hibernate one to one mapping
- In this kind of association, a foreign key column is created in owner entity. For example, if we make EmployeeEntity owner, then a extra column "ACCOUNT_ID" will be created in Employee table. This column will store the foreign key for Account table.
- To make such association, refer the Account entity in EmployeeEntity class as follow:
@OneToOne @JoinColumn(name="ACCOUNT_ID") private AccountEntity account;
- @JoinColumn
- The join column is declared with the @JoinColumn annotation which looks like the @Column annotation, It is used in column owner column and mapped by used in other table. It has one more parameters named referencedColumnName. This parameter declares the column in the targeted entity that will be used to the join.
- mappedBy
- mappedBy is used. ‘mappedBy’ refers to the property name of the association on the owner side.AccountEntity.java
-
@OneToOne(mappedBy="account") private EmployeeEntity employee;
Hibernate Many-To-One Bidirectional
- One table has a foreign key column that references the primary key of associated table.In Bidirectional relationship, both side navigation is possible.
- We are discussing an example of Student and University relationship. Many student can enroll at one University. And one University can have many students.
@Entity @Table(name = "STUDENT") public class Student { @Id @GeneratedValue @Column(name = "STUDENT_ID") private long id; @Column(name = "FIRST_NAME") private String firstName; @ManyToOne(optional = false) @JoinColumn(name = "UNIVERSITY_ID") private University university; ------------------------ ------------------------ } @Entity @Table(name = "UNIVERSITY") public class University { @Id @GeneratedValue @Column(name = "UNIVERSITY_ID") private long id; @Column(name = "NAME") private String name; @Column(name = "COUNTRY") private String country; @OneToMany(mappedBy = "university", cascade = CascadeType.ALL) private List
students; } - @JoinColumn says that Student table will contain a separate column UNIVERSITY_ID which will eventually act as a foreign key reference to primary key of University table
Many to Many Annotation
- In this scenario, any given employee can be assigned to multiple projects and a project may have multiple employees working for it, leading to a many-to-many association between the two.
- We have an employee table with employee_id as its primary key and a project table with project_id as its primary key. A join table employee_project is required here to connect both sides.
- The model classes Employee and Project need to be created with JPA annotations:
@Entity @Table(name = "Employee") public class Employee { // ... @ManyToMany(cascade = { CascadeType.ALL }) @JoinTable( name = "Employee_Project", joinColumns = { @JoinColumn(name = "employee_id") }, inverseJoinColumns = { @JoinColumn(name = "project_id") } ) Set
projects = new HashSet<>(); // standard constructor/getters/setters } @Entity @Table(name = "Project") public class Project { // ... @ManyToMany(mappedBy = "projects") private Set employees = new HashSet<>(); // standard constructors/getters/setters } - Both the Employee class and Project classes refer to one another, which means that the association between them is bidirectional.
- In order to map a many-to-many association, we use the @ManyToMany, @JoinTable and @JoinColumn annotations.
- @ManyToMany
- The @ManyToMany annotation is used in both classes to create the many-to-many relationship between the entities.
- @JoinTable
- In our example, the owning side is Employee so the join table is specified on the owning side by using the @JoinTable annotation in Employee class
- @JoinColumn
- The @JoinColumn annotation is used to specify the join/linking column with the main table. Here, the join column is employee_id and project_id is the inverse join column since Project is on the inverse side of the relationship
- mappedBy
- In the Project class, the mappedBy attribute is used in the @ManyToMany annotation to indicate that the employees collection is mapped by the projects collection of the owner side