Thursday, October 18, 2012

How to get a FaceBook comment count for a page?

Face open graph api has relevant info, to send you the facebook comment count for a particular page. Below is the sample code, which will return you the JSON response of the page details, from where you can fetch comments count, you just need to pass the URL.

Note: Your page URL is the unique identifier.

$json = json_decode(file_get_contents('https://graph.facebook.com/?ids=' . $url));
return ($json->$url->comments) ? $json->$url->comments : 0;


Tuesday, October 2, 2012

How to retrieve the auto-generated key after an INSERT in Spring

When you insert a record with a primary key field set as auto_increment in MYSQL, it will generate ID automatically, though Spring's RdbmsOperation class has two methods with encouraging names setGeneratedKeyColumnName and setReturnGeneratedKeys, at the time of writing the child class SqlUpdate doesn't not use them to return the value of the generated keys. If our table has a foreign relation, and related data needs to be inserted at the time of creation, we need the primary key field data of the insert statement.

To get the generated id, we have to use the JdbcTemplate.update method which is overloaded JdbcTemplate.update(PreparedStatementCreator psc, KeyHolder k)
The key returned from the insert is injected into the KeyHolder object. Implementation of this interface KeyHolder 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. Below is the sample implementation to get the auto generated ids, this works fine in MYSQL

public int add(BaseObject obj) {
 final Dealer dealer = (Dealer) obj;
 dealerJdbcTemplate.update(psc, generatedKeyHolder)
 KeyHolder keyHolder = new GeneratedKeyHolder();
 dealerJdbcTemplate.update(new PreparedStatementCreator()
  {
   public PreparedStatement createPreparedStatement(Connection connection) throws SQLException 
   {     
    PreparedStatement ps = connection.prepareStatement("INSERT INTO DEALER (NAME, ADDRESS, CITY, STATE, COUNTRY, ZIP, CONTACTPERSONNAME, MOBILENUMBER, PHONENUMBER) VALUES (?,?,?,?,?,?,?,?,?)" , Statement.RETURN_GENERATED_KEYS);
    ps.setString(1, dealer.getName());
    ps.setString(2, dealer.getAddress());
    ps.setString(3, dealer.getCity());
    ps.setString(4, dealer.getState());
    ps.setString(5, dealer.getCountry());
    ps.setInt(6, dealer.getZip());
    ps.setString(7, dealer.getContactPersonName());
    ps.setString(8, dealer.getMobileNumber());
    ps.setString(9, dealer.getPhoneNumber());            
    return ps;
   }    
  },
  keyHolder
 );
 return keyHolder.getKey().intValue(); 
}
Happy Programming...!!