It's my blog!

How many calories are in a drink from STARBUCKS?

Another interesting post from I love Coffee. See the entire post here

I love Coffee

** or Second cup etc….

Get auto generated keys with JdbcTemplate

Sometime you need to get the auto generated key of last record inserted into a table. It is possible to use Interface JdbcTemplate() and KeyHolder interface; this sample has been tested with mySql DB and Spring 3.2:

final String sqlCommand = new String("INSERT INTO Template_request(title, descriptio) VALUES (?, ?)");
KeyHolder holder = new GeneratedKeyHolder();
getJdbcTemplate().update(new PreparedStatementCreator() {           
    public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
        PreparedStatement ps = connection.prepareStatement(sqlCommand, Statement.RETURN_GENERATED_KEYS);
        ps.setString(1, templateRequest.getTitle());
        ps.setString(2, templateRequest.getDecription());        
        return ps;
}, holder);
Long request_id = holder.getKey().longValue();

This is the definition of Template_request table:

DROP TABLE IF EXISTS `Template_request`;
CREATE TABLE Template_request
    title				VARCHAR(256) NOT NULL,
    description			VARCHAR(2048),
    date_uprec 			TIMESTAMP DEFAULT now() ON UPDATE now(),
    CONSTRAINT PK_Template_request PRIMARY KEY (id_templaterequest)

interface KeyHolder
Interface for retrieving keys, typically used for auto-generated keys as potentially returned by JDBC insert statements.
Implementations of this interface can hold any number of keys. In the general case, the keys are returned as a List containing one Map for each row of keys.

Most applications only use on key per row and process only one row at a time in an insert statement. In these cases, just call getKey to retrieve the key. The returned value is a Number here, which is the usual type for auto-generated keys.

public class JdbcTemplate extends JdbcAccessor implements JdbcOperations
This is the central class in the JDBC core package. It simplifies the use of JDBC and helps to avoid common errors. It executes core JDBC workflow, leaving application code to provide SQL and extract results. This class executes SQL queries or updates, initiating iteration over ResultSets and catching JDBC exceptions and translating them to the generic, more informative exception hierarchy defined in the org.springframework.dao package.
Code using this class need only implement callback interfaces, giving them a clearly defined contract. The PreparedStatementCreator callback interface creates a prepared statement given a Connection, providing SQL and any necessary parameters. The ResultSetExtractor interface extracts values from a ResultSet. See also PreparedStatementSetter and RowMapper for two popular alternative callback interfaces.

Can be used within a service implementation via direct instantiation with a DataSource reference, or get prepared in an application context and given to services as bean reference. Note: The DataSource should always be configured as a bean in the application context, in the first case given to the service directly, in the second case to the prepared template.

Because this class is parameterizable by the callback interfaces and the SQLExceptionTranslator interface, there should be no need to subclass it.

All SQL operations performed by this class are logged at debug level, using “org.springframework.jdbc.core.JdbcTemplate” as log category.

Make jquery function run on page load

Load jQuery when the HTML document is loaded:

$(document).ready(function() {
	// business code

Load jQuery when all the images on a page have also loaded:

$(window).load(function() {
    // business code

Installing Parallels Tools in Linux Virtual Machine

Sometime happens you need to manually mount the cdrom to be able to install the Parallels Tools. Follow these instructions to do that:

1) Start the virtual machine. When the guest OS boots up, choose Install Parallels Tools from the Virtual Machine menu.

At this point, the prl-tools-lin.iso image file will be connected to the virtual machine’s CD/DVD drive.

2) Start a terminal in your Linux guest OS. Type the following command to gain the root privileges:

sudo su -

3) ount the Parallels Tools installation disc image, enter the following:

mount -o exec /dev/cdrom /media/cdrom

Note: /dev/cdrom is the virtual machine’s CD/DVD drive and /media/cdrom is the mount point for this device. In some of the Linux operating systems the virtual CD/DVD drive may appear as /dev/hdb and the mount point /mnt/cdrom. Some Linux OSs do not have the CD/DVD drive mount point. In this case, you should create the mount point directory manually.

4) When the installation disc image is mounted, change the directory to the CD/DVD drive directory using

cd /media/cdrom/

In the CD/DVD drive directory, enter the following to launch Parallels Tools installation:


Note: You must have the root privileges to run this command.

Follow the Parallels Tools Installer instructions to complete the installation.

Back in Toronto (3rd)

Here we are, back in Toronto for the third time, first time in winter. This city is really impressive, never seen something similar in North America (I guess New York it’s more or less similar). The City of Toronto is working on the extension of the northwest PATH* that will provide guests with additional connections to the world’s largest underground shopping complex.

Two things (except the Path) impressed me: the people is really nice and ready to help you every time you should be in pain and the number of food shops.

* PATH is downtown Toronto’s underground walkway linking 30 kilometres of shopping, services and entertainment. Follow PATH and you’ll reach your downtown destination easily in weatherproof comfort.

Prospettiva Nevski

Nevsky Avenue (Russian: Не́вский проспе́кт, tr. Nevsky Prospekt, IPA: [ˈnʲefskʲɪj prɐˈspʲekt]) is the main street in the city of St. Petersburg, Russia. Planned by Peter the Great as beginning of the road to Novgorod and Moscow, the avenue runs from the Admiralty to the Moscow Railway Station and, after making a turn at Vosstaniya Square, to the Alexander Nevsky Lavra. [wiki]

Inspirational Quotes from Sir Alex Ferguson

This is a really interesting post

My favorite quote is:

I’ve never played for a draw in my life

And Don’t Forget To Add Some “Fergie Time”

Results pagination with MongoDB and Java

To implement the MongoDB results pagination in Java, there are few parameters that need to be collected:

1) the order of results (ascending / descending)
2) the field used to order the results
3) the number of element and the page selected
4) the field and the value used to filter the results

As well as the results of query, the method needs to return the total number of elements. All returned elements will be saved in a HashMap.

HashMap<String, Object> resultMap = new HashMap<String, Object>();
Direction direction = Sort.DEFAULT_DIRECTION;
if (sortDirection > 0) {
	direction = Sort.Direction.ASC;
} else { 
	direction = Sort.Direction.DESC;

If a pagination is required, skip and limit are used

if (pageSize > 0) {
	query.skip((pageNum - 1 ) * pageSize);
if ( sortField != null && !sortField.equals("") ) {				
	query.with(new Sort(direction, sortField));
results = mongoTemplate.find(query, Object.class);

If a pagination is required, queryCounter (basically a version of query without pagination an limit) is used to calculate the total number of results. Of course, if pagination is not required, is possible to use directly the size of results.

if ( pageSize > 0 ) {
	resultMap.put("RESULT_SIZE", (int) mongoTemplate.count(queryCounter, Object.class));
} else {
	// If pagination is not required, the query is not re-executed
	resultMap.put("RESULT_SIZE", results.size());

mongoTemplate is a spring bean defined in this way on context configuration:

<bean id="mongoTemplate" class=""  c:mongo-ref="mongo" c:databaseName="${}">
	<property name="writeConcern" value="SAFE" />
« Older posts

Copyright © 2014 It's my blog!

Theme by Anders NorenUp ↑