Saturday, October 26, 2013

BoneCP connection pool


àBoneCP is a fast, free, open-source, Java database connection pool (JDBC Pool) library.
àThis is a library that will manage a database connection for you to get faster database access in your application.
Features:
·         Free, open source and written in 100% pure Java with complete Javadocs.
·         Highly scalable, fast connection pool
·         Partitioning capability to increase performance
·         Automatic resizing of pool
·         Statement caching support
·         Support for XML/property configuration
·         Idle connection timeouts / max connection age support
·         Debugging support to show stack locations of connections that were closed twice.
Configurations:
·         JdbcUrl:
o    The JDBC connection string URL.
o    Default: None
·         username:
o    The DB username to use.
o    Default: None
·         password:
o    The DB password to use.
o    Default: None
·         PartitionCount:
o    In order to reduce lock contention and thus improve performance, each incoming connection request picks off a connection from a pool that has thread-affinity, i.e. pool[threadId % partition_count]. The higher this number, the better your performance will be for the case when you have plenty of short-lived threads. Beyond a certain threshold, maintenence of these pools will start to have a negative effect on performance (and only for the case when connections on a partition start running out).
o    Default: 1, minimum: 1, recommended: 3-4 (but very app specific)
·         maxConnectionsPerPartition:
o    The number of connections to create per partition. Setting this to 5 with 3 partitions means you will have 15 unique connections to the database. Note that BoneCP will not create all these connections in one go but rather start off with minConnectionsPerPartition and gradually increase connections as required.
·         minConnectionsPerPartition:
o    The number of connections to start off with per partition.
·         acquireIncrement:
o    When the available connections are about to run out, BoneCP will dynamically create new ones in batches. This property controls how many new connections to create in one go (up to a maximum of maxConnectionsPerPartition). Note: This is a per partition setting.
o    Default: 10


·         idleMaxAge
·         statementsCacheSize
·         releaseHelperThreads
·         hibernate.connection.provider_class
o    com.jolbox.bonecp.provider.BoneCPConnectionProvider
·         statementsCacheSize
·         releaseHelperThreads
·         idleConnectionTestPeriod






Friday, October 25, 2013

HIBERNATE


What is Hibernate:

Hibernate is the ORM tool given to transfer the data between a java (object) application and a database (Relational) in the form of the objects.  Hibernate is the open source light weight tool given by Gavin King, actually JBoss server is also created by this person only.
Hibernate is a non-invasive framework,  means it wont forces the programmers to extend/implement any class/interface, and in hibernate we have all POJO classes so its light weight.
Hibernate can runs with in or with out server, i mean it will suitable for all types of java applications (stand alone or desktop or any servlets bla bla.)
Hibernate is purely for persistence (to store/retrieve data from Database).

Advantages of hibernates:

  • Hibernate supports InheritanceAssociationsCollections
  • In hibernate if we save the derived class object,  then its base class object will also be stored into the database, it means hibernate supporting inheritance
  • Hibernate supports relationships like One-To-Many,One-To-One, Many-To-Many-to-Many, Many-To-One
  • This will also supports collections like List,Set,Map (Only new collections)
  • In jdbc all exceptions are checked exceptions, so we must write code in try, catch and throws, but in hibernate we only have Un-checked exceptions, so no need to write try, catch, or no need to write throws.  Actually in hibernate we have the translator which converts checked to Un-checked ;)
  • Hibernate has capability to generate primary keys automatically while we are storing the records into database
  • Hibernate has its own query language, i.e hibernate query language which is database independent
  • So if we change the database, then also our application will works as HQL is database independent
  • HQL contains database independent commands
  • While we are inserting any record, if we don’t have any particular table in the database, JDBC will rises an error like “View not exist”, and throws exception, but in case of hibernate, if it not found any table in the database this will create the table for us ;)
  • Hibernate supports caching mechanism by this, the number of round trips between an application and the database will be reduced, by using this caching technique an application performance will be increased automatically.
  • Hibernate supports annotations, apart from XML
  • Hibernate provided Dialect classes, so we no need to write sql queries in hibernate, instead we use the methods provided by that API.
  • Getting pagination in hibernate is quite simple.

Disadvantages of hibernates:

  • I don’t think there are disadvantages in hibernate
  • You know some thing.., Its saying hibernate is little slower than pure JDBC, actually the reason being hibernate used to generate many SQL statements in run time, but i guess this is not the disadvantage :-)
  • But there is one major disadvantage, which was boilerplate code issue, actually we need to writesame code in several files in the same application, but spring eliminated this.

Configuration:

Configuration is the file loaded into an hibernate application when working with hibernate, this configuration file contains 3 types of information..
  • Connection Properties
  • Hibernate Properties
  • Mapping file name(s)
We must create one configuration file for each database we are going to use, suppose if we want to connect with 2 databases, like OracleMySql, then we must create 2 configuration files.

Syntax Of Configuration xml:



Steps To Use Hibernate In Any Java Application


Whether the java application will run in the server or without server, and the application may be desktop or stand alone, swing, awt, servlet…what ever, but the steps are common to all.

In order to work with hibernate we don’t required any server as mandatory but we need hibernate software (.jar(s) files).

Follow The Steps:


1. Import the hibernate API, they are many more, but these 2 are more than enough…

import org.hibernate.*;
import org.hibernate.cfg.*;

2. Among ConfigurationMapping xml files, first we need to load configuration xml, because once we load the configuration file, automatically mapping file will be loaded as we registered this mapping xml in the configuration file.

So to load configuration xml, we need to create object of Configuration class, which is given inorg.hibernate.cfg.*;  and we need to call configure() method in that class, by passing xml configuration file name as parameter.
Eg:
Configuration cf = new Configuration();
cf.configure(“hibernate.cfg.xml”);
Hear our configuration file name is your choice, but by default am have been given hibernate.cfg.xml,  so once this configuration file is loaded in our java app, then we can say that hibernate environment isstarted in our program.
So once we write the line_ cf.configure(“hibernate.cfg.xml”), configuration object cf will reads this xml file hibernate.cfg.xml, actually internally cf will uses DOM parsers to read the file.
Finally…
  • cf will reads data from hibernate.cfg.xml
  • Stores the data in different variables
  • And finally all these variables are grouped and create one high level hibernate object we can call as SessionFactory object.
  • So Configuration class only can create this SessionFactory object
likeSessionFactory sf =  cf.buildSessionFactory();
Actually SessionFactory is an interface not a class, and SessionFactoryImpl is the implimented class for SessionFactory, so we are internally creating object of SessionFactoryImpl class and storing in the interface reference, so this SessionFactory object sf contains all the data regarding the configuation file so we can call sf as heavy weight object.
3. Creating an object of session,
  • Session is an interface and SessionImpl is implemented class, both are given in org.hibernate.*;
  • When ever session is opened then internally a database connection will be opened, in order to get a session or open a session we need to call openSession() method in SessionFactory, it means SessionFactory produces sessions.
Session session = sf.openSession();
sf = SessfionFactory object
4. Create a logical transaction
While working with insertupdatedelete, operations from an hibernate application onto the database then hibernate needs a logical Transaction, if we are selecting an object from the database then we donot require any logical transaction in hibernate.  In order to begin a logical transaction in hibernate then we need to call a method beginTransaction() given by Session Interface.
Transaction tx = session.beginTransaction();
session is the object of Session Interface
5. Use the methods given by Session Interface,  to move the objects from application to database and  from database to application
session .save(s)-Inserting object ‘s’ into database
session.update(s)-Updating object ‘s’ in the database
session.load(s)-Selecting objcet ‘s’ object
session.delete(s)-Deletig object ‘s’ from database
  • So finally we need to call commit() in Transaction, like tx.commit();
  • As i told earlier,  when we open session a connection to the database will be created right, so we must close that connection as session. close().
  • And finally close the SessionFactory as sf.close()
  • That’s it.., we are done.
Final flow will be______________
Configuration
SessionFactory
Session
Transaction
Close Statements


Transient, Persistent, Detaiched States

1.Transient State:
A New instance of  a persistent class which is not associated with a Session, has no representation in the database and no identifier value is considered transient by Hibernate:


UserDetail user = new UserDetail();
user.setUserName("Dinesh Rajput");
// user is in a transient state


2. Persistent State:

A persistent instance has a representation in the database , an identifier value and is associated with a Session. You can make a transient instance persistent by associating it with a Session:

Long id = (Long) session.save(user);
// user is now in a persistent state



3. Detached State:

Now, if we close the Hibernate Session, the persistent instance will become a detached instance: it isn’t attached to a Session anymore (but can still be modified and reattached to a new Session later though).

session.close();
//user in detached state




Hibernate Caching Mechanism, Hibernate Cache


Every fresh session having its own cache memory, Caching is a mechanism for storing the loaded objects into a cache memory.  The advantage of cache mechanism is, whenever again we want to load the same object from the database then instead of hitting the database once again, it loads from the local cache memory only, so that the no. of round trips between an application and a database server got decreased.  It means caching mechanism increases the performance of the application.
Caching is all about application performance optimization and it sits between your application and the database to avoid the number of database hits as many as possible to give a better performance for performance critical applications
In hibernate we have two levels of caching
·         First Level Cache [ or ] Session Cache
·         Second Level Cache [ or ] Session Factory Cache [ or  ] JVM Level Cache


Refer: Hibernate Caching Mecanishm




One-To-One 






Mapping


<many-to-one name="studentAddress"class="com.vaannila.student.Address" column="STUDENT_ADDRESS" not-null="true" cascade="all" unique="true" />

using Annotations 
@Entity
@Table(name = "STUDENT")
public class Student {
   @OneToOne(cascade = CascadeType.ALL)
   public Address getStudentAddress() {
      return this.studentAddress;
   }
   public void setStudentAddress(Address studentAddress) {
      this.studentAddress = studentAddress;
   }
}


 One-To-Many


 



Mapping


<set name="studentPhoneNumbers" table="STUDENT_PHONE" cascade="all">
<key column="STUDENT_ID" />
<many-to-many column="PHONE_ID" unique="true"class="com.vaannila.student.Phone" />
</set>

using Annotations 
@Entity
@Table(name = "STUDENT")
public class Student {

private Set<Phone> studentPhoneNumbers = new HashSet<Phone>(0);
@OneToMany(cascade = CascadeType.ALL)
@JoinTable(name = "STUDENT_PHONE", joinColumns = { @JoinColumn(name ="STUDENT_ID") }, inverseJoinColumns = { @JoinColumn(name ="PHONE_ID") })

   public Set<Phone> getStudentPhoneNumbers() {
      return this.studentPhoneNumbers;
   }
   public void setStudentPhoneNumbers(Set<Phone> studentPhoneNumbers) {
      this.studentPhoneNumbers = studentPhoneNumbers;
   }


}

Many-To-One 















Mapping

<many-to-one name="studentAddress"class="com.vaannila.student.Address" column="STUDENT_ADDRESS"cascade="all" not-null="true" />

using Annotations
@Entity
@Table(name = "STUDENT")
public class Student {

private Set<Phone> studentPhoneNumbers = new HashSet<Phone>(0);
@ManyToOne(cascade = CascadeType.ALL)

   public Address getStudentAddress() {
      return this.studentAddress;
   }
   public void setStudentAddress(Address studentAddress) {
      this.studentAddress = studentAddress;
   }


}


Many-To-Many 



Mapping

<set name="courses" table="STUDENT_COURSE" cascade="all">
<key column="STUDENT_ID" />
<many-to-many column="COURSE_ID" class="com.vaannila.student.Course" />
</set>

using Annotations 

@Entity
@Table(name = "STUDENT")
public class Student {
private Set<Course> courses = new HashSet<Course>(0);
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "STUDENT_COURSE", joinColumns = { @JoinColumn(name ="STUDENT_ID") }, inverseJoinColumns = { @JoinColumn(name ="COURSE_ID") })

   public Set<Course> getCourses() {
      return this.courses;
   }
   public void setCourses(Set<Course> courses) {
      this.courses = courses;
   }
}




Security Certificates

  1. Cryptography Basics Understand Key Concepts : Encryption, decryption, hashing, and digital signatures. Key terms: confidentiality, inte...