Adding internationalization support to spring mvc with thymeleaf

For basic Thymeleaf configuration check Spring MVC with Thymeleaf

Thymeleaf uses Standerd messange resolver unless specified which on to use. We can also use Spring internationalization support which will be supported by default by Thymeleaf.

Steps:

  1. Add messages_en file to src/main/resources/
  2. Add spring beans those will support internationalization.
  3. LocaleChangeInterceptor is handler mapping that need to supports the multiple languages. The “paramName” is the parameter value that’s used to set the locale.
  4. Use ?lang=fr to change language to French from default English.

Source: Source Code

Java Concurrency – Processes and Threads

Process

Process is self contained environment meaning it got its own basic resources importantly own memory space. For communication between processes we need interprocess communication (sockets, pipes etc) provide by operating system.

Most implementations of JMV runs as single process. Java application can create multiple or additional processes by using java.lang.ProcessBuilder object.

Threads

Threads exists within process and every process has at least one thread. Thread share process’s resources that includes memory, open files etc; hence creating new thread requires few resources. Threads sometime called as lightweight process. Each thread is associated with instance of class Thread.

Their are two strategies of  Thread
1. Manual – Control thread creation and management by instantiating Thread each time application want to perform asynchronous task
2. Executors – Separate thread management from application by passing tasks to Executor.

Defining and starting a thread

1. Provide Runnable object – Implement Runnable interface which defines a single method run()
2. Subclass Thread class – Extends Thread class.

It will be wise to implement Runnable interface instated of extending Thread class. Coz we can extend other classes if required if we implement Runnable interface but we can not if we extend Thread class.

Thread.sleep(long miliSeconds) causes current thread to suspend execution for specific time. Sleep timings are not guarantied to be precise as it depends on facilities provided by underlaying operating system.

Good example of basic thread working

Ref: Java SE tutorials

Design Pattern – Singleton

Singleton is simple pattern which guaranty  only one instance of object is present. Singleton is term taken from mathematical concept “Singleton is a set with exactly one element”

Singleton is achieved in java by

  1. By making default constructor private – hence you can not initialised the class .
  2. Having static method that can return you instance – control over how to create object
  3. Having self instance private static and volatile – Thread safe unique instance.

Note: volatile from Java 5 means value of variable will not be tread-locally cached. Value will be updated directly in main memory. Variable will act like its synchronised on its self.

Below is sample for double check singleton:

Reference:  WikiHead First Design Patterns

StringBuffer vs StringBuilder

To check StringBuffer vs StringBuilder we must check AbstractStringBuffer first coz both StringBuffer and StringBuilder extends AbstractStringBuilder.

AbstractStringBuilder

AbstractStringBuilder has ‘char value[]’ that is used for holding string in from of char sequence. ‘int count’ is used for storing number of characters stored.

Important methods in AbstractStringBuilder:

  1. capacity(): Capacity is amount of store available for newly inserted characters
  2.  insert(int, <T>): insert <T> into character sequence at int.
  3. reverse(): Reverse of the character sequence
  4. append(): Append to the character sequence
  5.  toString(): Only abstract method in AbstractStringBuilder
  6. getValue(): This is a final method that returns char value[];

In simple words all operations are done on array of characters which is present in AbstractStringBuilder.

Now StringBuffer vs StringBuilder

  1. StringBuffer and StringBuilder extends AbastractStringBuilder
  2. Both use AbastractStringBuilder for logical operation and has minimal code written in them
  3. Both implements toString() where they create new String and do not share char value[] with String.
  4. Both implements writeObject() &  readObject()

Now the major and important difference is all important methods in StringBuffer are synchronized. Due to non synchronized methonds StringBuilder performs better than StringBuffer.

String Basics

Strings: String is a class used for manipulating strings. String is character array and implemented in same way. String is object in java.

Creating String:
String can be created in multiple ways

  1. By using one of thirteen constructors provided by String class (or using new keyword)
  2. By using ‘=’ operator (or String literal)

Important difference between them is when we create String object using String literal JVM checks string pool if found string object will be returned else new object will be created; but in case of new JVM will create new object without checking in string pool.

String equality:
String equal method check each character in character array that is present inside String; where as ‘==’ checks object memory location.

String pool:
String pool is special memory location where JVM keeps all string objects

String and security:
If we keep sensitive data in String due to immutable nature we can’t erase that data. Someone who got access to java memory like access to heap dump can read that information.
We should keep password in char array and reset them once they are no longer needed.

Character encoding:
By default String will use same encoding as underlaying platform i.e. character encoding of server. This can cause issues if server is not supporting unicode encoding like UTF-8 or UTF-16. This can be changed by using system property “file.encoding”

Java Database Connectivity (JDBC) basics

Simple JDBC program demonstrating java connectivity with database.

Drivers:
The DriverManager will try to load as many drivers as it can find and then for any given connection request, it will ask each driver in turn to try to connect to the target URL.

When a Driver class is loaded, it should create an instance of itself and register it with the DriverManager. This means that a user can load and register a driver by calling

Class.forName(“foo.bah.Driver”)

Connection:
A Connection is like a session with database. Applications should not invoke SQL commands directly to change the connection’s configuration when there is a JDBC method available. By default a Connection object is in auto-commit mode, which means that it automatically commits changes after executing each statement. If auto-commit mode has been disabled, the method commit must be called explicitly in order to commit changes; otherwise, database changes will not be saved. Following code is used for getting connection.

Note:In JDBC 4.0, we no longer need to explicitly load JDBC drivers using Class.forName().

Statement:
Statements are  used for executing a static SQL statement and returning the results it produces.

By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment’s current ResultSet object if an open one exists.

ResultSet:
ResultSet is a table of data representing a database result set.
A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set.
A default ResultSet object is not updatable and has a cursor that moves forward only. Thus, you can iterate through it only once and only from the first row to the last row. It is possible to produce ResultSet objects that are scrollable and/or updatable.

 

Hibernate entity manager and persistence.xml

Hibernate entity manager and persistence.xml 

javax.persistence.jdbc.driver: The JDBC driver class
H2 – org.h2.Driver
Oracle – oracle.jdbc.driver.OracleDriver
MySql – com.mysql.jdbc.Driver

javax.persistence.jdbc.url: The JDBC URL to the database instance.
H2 – jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE
Oracle – jdbc:oracle:thin:@127.0.0.1:1521:DBNAME
MySql – jdbc:mysql://localhost/DBNAME

javax.persistence.jdbc.user: The database user name

javax.persistence.jdbc.password: The database user password

Other hibernate properties can be used as required like below
<property name=”hibernate.show_sql” value=”true” />

Example:

Source: Employee Manager

Hibernat basic: annotations

Hibernate basic without annotations

@Entity [javax.persistence.Entity]: Specifies that the class is an entity
-name: (Optional) The entity name. Defaults to the unqualified name of the entity class. This name is used to refer to the entity in queries. The name must not be a reserved literal in the Java Persistence query language

@Table [javax.persistence.Table]: Specifies the primary table for the annotated entity. Additional tables may be specified using SecondaryTable or SecondaryTables annotation. If no Table annotation is specified for an entity class, the default values apply.
-name: (Optional) The name of the table
-catalog: (Optional) The catalog of the table
-schema: (Optional) The schema of the table.
-uniqueConstraints: (Optional) Unique constraints that are to be placed on the table.

@Column [javax.persistence.Column]: Specifies the mapped column for a persistent property or field.
-String name: (Optional) The name of the column. Defaults to the property or field name.
-boolean unique: (Optional) Whether the column is a unique key. This is a shortcut for the UniqueConstraint annotation at the table level and is useful for when the unique key constraint corresponds to only a single column. This constraint applies in addition to any constraint entailed by primary key mapping and to constraints specified at the table level.
-boolean nullable: (Optional) Whether the database column is nullable.
-int length: (Optional) The column length. (Applies only if a string-valued column is used.) Default 255
-int precision: (Optional) The precision for a decimal (exact numeric) column. (Applies only if a decimal column is used.) Value must be set by developer if used when generating the DDL for the column.
-int scale: (Optional) The scale for a decimal (exact numeric) column. (Applies only if a decimal column is used.)
-String table: (Optional) The name of the table that contains the column. If absent the column is assumed to be in the primary table.
-String columnDefinition: (Optional) The SQL fragment that is used when generating the DDL for the column. Defaults to the generated SQL to create a column of the inferred type.
-boolean insertable: (Optional) Whether the column is included in SQL INSERT statements generated by the persistence provider.
-boolean updatable: (Optional) Whether the column is included in SQL UPDATE statements generated by the persistence provider.

@GeneratedValue [javax.persistence.GeneratedValue]:  Provides for the specification of generation strategies for the values of primary keys.
-GenerationType strategy: (Optional) The primary key generation strategy that the persistence provider must use to generate the annotated entity primary key.
-String generator: (Optional) The name of the primary key generator to use as specified in the SequenceGenerator or TableGenerator annotation. Default:javax.persistence.GenerationType.AUTO

javax.persistence.GenerationType
-AUTO: Indicates that the persistence provider should pick an appropriate strategy for the particular database.
-IDENTITY: Indicates that the persistence provider must assign primary keys for the entity using a database identity column.
-SEQUENCE: Indicates that the persistence provider must assign primary keys for the entity using a database sequence.
-TABLE: Indicates that the persistence provider must assign primary keys for the entity using an underlying database table to ensure uniqueness.

@Id [javax.persistence.Id]: Specifies the primary key of an entity. The field or property to which the Id annotation is applied should be one of the following types: any Java primitive type; any primitive wrapper type; String; java.util.Date; java.sql.Date; java.math.BigDecimal; java.math.BigInteger. The mapped column for the primary key of the entity is assumed to be the primary key of the primary table. If no Column annotation is specified, the primary key column name is assumed to be the name of the primary key property or field.

@Temporal [javax.persistence.Temporal]: This annotation must be specified for persistent fields or properties of type java.util.Date and java.util.Calendar. It may only be specified for fields or properties of these types.
-TemporalType value: The type used in mapping java.util.Date or java.util.Calendar.
javax.persistence.TemporalType: Type used to indicate a specific mapping of java.util.Date or java.util.Calendar.
DATE: Map as java.sql.Date
TIME: Map as java.sql.Time
TIMESTAMP: Map as java.sql.Timestamp

Example:

Source: Employee Manager

Details of hibernate.cfg.xml

Details of hibernate.cfg.xml

hibernate.connection.driver_class: The JDBC driver class
H2 – org.h2.Driver
Oracle – oracle.jdbc.driver.OracleDriver
MySql – com.mysql.jdbc.Driver

hibernate.connection.url: The JDBC URL to the database instance.
H2 – jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE
Oracle – jdbc:oracle:thin:@127.0.0.1:1521:DBNAME
MySql – jdbc:mysql://localhost/DBNAME

hibernate.dialect: This property makes Hibernate generate the appropriate SQL for the chosen database.
H2 – org.hibernate.dialect.H2Dialect
Oracle – org.hibernate.dialect.OracleDialect
MySql – org.hibernate.dialect.MySQLDialect

hibernate.cache.provider_class: Caching implementation to use
No Cache – org.hibernate.cache.internal.NoCacheProvider
EHCache – org.hibernate.cache.EhCacheProvider
OSCache – org.hibernate.cache.OSCacheProvider
SwarmCache – org.hibernate.cache.SwarmCacheProvider
JBoss TreeCache – org.hibernate.cache.TreeCacheProvider

hibernate.connection.username: The database user name

hibernate.connection.password: The database user password

hibernate.connection.pool_size: Limits the number of connections waiting in the Hibernate database connection pool.

hibernate.show_sql: Echo all executed SQL to stdout

hibernate.hbm2ddl.auto: Automatically validates or exports schema DDL to the database
create: creates the schema, destroying previous data
create-drop: drop the schema at the end of the session
validate: validate the schema, makes no changes to the database
update: update the schema

mapping resource: Resource mapping files

Sample XML

 

 

 

Hibernate Basics

Hibernate may not be the best solution for data-centric applications that only use stored-procedures to implement the business logic in the database, it is most useful with object-oriented domain models and business logic in the Java-based middle-tier.

Hibernate can certainly help you to remove or encapsulate vendor-specific SQL code and will help with the common task of result set translation from a tabular representation to a graph of objects.

Basic example
Pre-req: Spring STS

  1. Create new maven project (File > new > Maven Project)
  2. Add dependancies
  3. Add Employee entity class
  4. Add hibernate mapping class for Employee (Employee.hbm.xml)
  5. Add hibernate configuration (hibernate.cfg.xml)
  6. Test Add and list employees

Source: Employee Manager

Ref: Hibernate User dev guide

My techno blog