Tuesday 25 February 2020

6 years exp java interview preparation_DataBase_Hibernate_jpa_SpringJpa

DataBase:


Connection pool:
Establishig a connection to the database before executing the sql quereis
instead of opening a connection every time and then connect to db and executing sql stmts and then closing it, We can use connection pooling which improves perpormance. Connection pooling  is a feature or service provieded by most of the applicaiton servers and webcontainers where in they create a set of or pool of connections and then our program (client) one of those connections can use of them.
for exmpll one servlet or one part is using one connection. 
other part or servlet can resuse the same thing once first part is done and put it back in pool.

to configure.
1) Copy the driver jar to tomcat/lib folder

2)Add the resource element to context.xml fle under tomcat/conf folder
<Resource name ="jdbc/mydb"
type= "javax.sql.DataSource"
username=""
password=""
driverClassName=""
url=""/>

So that JNDI (Java Naming and Directory Interface)

DataSoruce creates factory of connnections will put into the JNDI SERVER Using the name jdbc/mydb 

we can retryive data source in our program using JNDI  API by passing the "jdbc/mydb" 
If we give the name we  will get the JNDI  value object of datasource then we can say  ds.getconnection then it will get you one connection from the pool. datasourc e is a factory of connections. in this way we can improve performacne.






select Nth highest salary of an employee.


select name,salry from Employee e1
where N-1=(select count(disctinct salary) from Employee e2
where e2.salary>e1.salary)

SpringDataJPA:

sample example


Persistnace context

Sesssion s = sessionFactory.getSession();
tx=s.beginTransaction();
User u = s.get(User.class, 1L);

u.setName("updteName");.

User u2 =session.get(User.class, 1L)
updteName-->will be updated in DB





Hibernate Criteria Projections and restricitons
https://www.youtube.com/watch?v=DeBR9__zgRs



First Level Cache:

1 user 1 session hit s applicaiotn select query hits db and returns records and stores in First level cahce by default in Hibernate.

1 user or same session hits the same query again then, it will fetch from first level cache instead of hittign db.

2 user or 2 session hits the same query but it will again hit the db because it is different session.

Secondlevel Cache:
if we enable 2nd level cache in Hibernate , all sessions can use the second levle cache and fetch the data if the same query with out hitting the db. first time hits the db.

3 configs: 1. pom.xml hibenate-ehcache(os,swarm) 
                2. hib.conf.xml  need to enable 2nd level cache and say use ehcache
                3.  In Entiry we need to mention
                   @Cachable
                   @Cache (read or write stratagies)

ACID properties
A:Atomicity: Either to all stpes in transaction means complete transation or roll back if any problem in between.

C: Consistancy:  Before starting the operations in transation and After the all operations Total of those transation should be same.

I: Isolation: Transactions should know each other so that no insufficent balance error.

Durability: done all steps in Transaction and before saving it to disk power gone, we should maintain a durablity to store all transation detailsin in DISK, even this situation as well.




The dialect specifies the type of database used in hibernate so that hibernate generate appropriate type of SQL statements


Sr. No.Keysave()persist()
1
Basic 
 It stores object in database
It also stores object in database
2
Return Type 
It return generated id and return type is serializable 
It does not return anything. Its void return type. 
3
Transaction Boundaries 
It can save object within boundaries and outside boundaries 
It can only save object within the transaction boundaries 
4.
Detached Object 
It will create a new row in the table for detached object  
It will throw persistence exception for detached object 
5.
Supported by 
It is only supported by Hibernate 
It is also supported by JPA


All JPA-specific cascade operations are represented by the javax.persistence.CascadeType enum containing entries:
  • ALL
  • PERSIST
  • MERGE
  • REMOVE
  • REFRESH
  • DETACH
Cascading is about persistence actions involving one object propagating to other objects via an association. Cascading can apply to a variety of Hibernate actions, and it is typically transitive. The "cascade=..." attribute of the annotation that defines the association says what actions should cascade for that association.
Cascade = "all" means to apply all primary cascade types. As of Hibernate 5.3, these types are:
  • "delete" / "remove",
  • "detach" / "evict",
  • "merge",
  • "lock",
  • "persist",
  • "refresh",
  • "replicate",
  • "save_update" / "update"

@Transactional means
means


@Transactional
public void businessLogic() {
... use entity manager inside a transaction ...
}

UserTransaction utx = entityManager.getTransaction(); 

try { 
    utx.begin(); 
    businessLogic();
    utx.commit(); 
} catch(Exception ex) { 
    utx.rollback(); 
    throw ex; 
} 

@EnableTransactionManagement does exactly what it says: Enables Spring's annotation-driven transaction management capability, similar to the support found in Spring's XML namespace. Yes, you should still use @Transactional annotation on methods that you want to wrap in a transaction.

No comments:

Post a Comment