Thursday, May 31, 2012

What is Polymorphism?

If you think about the Greek roots of the term, it should become obvious.
  • Poly = many: polygon = many-sided, polystyrene = many styrenes, polyglot = many languages, and so on.
  • Morph = change or form: morphology = study of biological form, Morpheus = the Greek god of dreams able to take any form.
So polymorphism is the ability (in programming) to present the same interface for differing underlying forms (data types).
For example, integers and floats are implicitly polymorphic since you can add, subtract, multiply and so on, irrespective of the fact that the types are different. They're rarely considered as objects in the usual term.
But, in that same way, a class like BigDecimal or Rational or Imaginary can also provide those operations, even though they operate on different data types.
The classic example is the Shape class and all the classes that can inherit from it (square, circle, dodecahedron, irregular polygon, splat and so on).
With polymorphism, each of these classes will have different underlying data. A point shape needs only two co-ordinates (assuming it's in a two-dimensional space of course). A circle needs a center and radius. A square or rectangle needs two co-ordinates for the top left and bottom right corners (and possibly) a rotation. An irregular polygon needs a series of lines.
And, by making the class responsible for its code as well as its data, you can achieve polymorphism. In this example, every class would have its own Draw() function and the client code could simply do:
shape.Draw()
to get the correct behavior for any shape.
This is in contrast to the old way of doing things in which the code was separate from the data, and you would have had functions such as drawSquare() and drawCircle().
Object orientation, polymorphism and inheritance are all closely-related concepts and they're vital to know. There have been many "silver bullets" during my long career which basically just fizzled out but the OO paradigm has turned out to be a good one. Learn it, understand it, love it - you'll be glad you did :-)

http://stackoverflow.com/questions/1031273/what-is-polymorphism

Tuesday, May 29, 2012

Creating Mock Tests: Using Easy mock


Unit testing is now a "best practice" for software development. In this unit testing we have to face so many situations where we need to interact with Database or any other resources. But at the same time we need to make our Tests isolated too. Here comes the importance of Mock objects.
Mock objects are a useful way to write unit tests for objects that act as mediators. “Instead of calling the real domain objects, the tested object calls a mock domain object that merely asserts that the correct methods were called, with the expected parameters, in the correct order.”
Using EasyMock Framework
EasyMock is a framework for creating mock objects using the java.lang.reflect.Proxy object. When a mock object is created, a proxy object takes the place of the real object. The proxy object gets its definition from the interface or class you pass when creating the mock.
EasyMock is providing two APIs for creating mock objects that are based on interfaces, the other on classes (org.easymock.EasyMock and org.easymock. classextensions.EasyMockrespectively).
We can separate the EasyMock implementation into FOUR steps 
1. Creating a Mock Object using “EasyMock.createMock”.
Create Mock : Using this static method we are creating a mock object. And this is the first step which we need to do in mock testing.
When we creates this mock objects then we can follow three levels.
Regular: If we are expecting some methods to be executed then it was not executed then the test will fail.  And if any unexpected tests executed then also test will fail. Here the order of the method execution is not important.
Ex: EmpDAO empDAO = EasyMock.createMock(EmpDAO.class);
Nice: If we are expecting some methods to be executed then it was not executed then the test will fail. And if any unexpected tests executed then it will return a default value. Here also order is not important.
Ex: EmpDAO empDAO = EasyMock.createNiceMock(EmpDAO.class);
Strict: Same as regular but here the Order of the expected methods also important.
Ex: EmpDAO empDAO = EasyMock.createStrictMock(EmpDAO.class);
2. Expecting mock object method calls using “EasyMock.expect”.
This is used to expect some method calls from our mock object. Lets go through one example.
Lets assume we have the following methods which gets employee information from DB.
List employee = empDao.getEmpDetails();
List employee = empDao.getEmpDetailsByName(“bond”);
In the unit test we need to follow as follows…
EmpDao mockDao = EaskMock.createMock(EmpDao.class);
Employee mockEmp = new Employee();
mockEmp.setEmpName(“bond”);
mockEmp.setEmpCode(“007”);
List empList= new ArrayList(1);
empList.add(mockEmp);
expect(mockDao.getEmpDetails()).andReturn(empList);
expect(mockDao.getEmpDetailsByName(“bond”)).andReturn(empList);
replay(mockDao);
3. Registering/replaying expected methods using “EasyMock.replay”.
Once the behavior of the mock objects has been recorded with expectations, the mock objects must be prepared to replay those expectations. We are using replay() method for this purpose. EaskMock will stop the expecting behavior once this method calls.
EasyMock.replay(mockDao);
4. Verifying the expected methods using “EasyMock.verify”.
Veirfying the mock expectations is the final step which we need to follow. This includes validating that all methods that were expected to be called were called and that any calls that were not expected are also noted.
EasyMock.verify(mock);
Easymock is providing more functionalities like “Matchers” etc for more unit testing flexibility. EasyMock has been the first dynamic Mock Object generator, relieving users of hand-writing Mock Objects, or generating code for them. It helps us to increase our testing coverage a lot.

http://orangeslate.com/2009/01/02/creating-mock-tests-using-easy-mock/

Monday, May 28, 2012

Differences between Ant and Maven

In Maven: The Definitive Guide, I wrote about the differences between Maven and Ant in the introduction the section title is "The Differences Between Ant and Maven". Here's an answer that is a combination of the info in that introduction with some additional notes.
A Simple Comparison
I'm only showing you this to illustrate the idea that, at the most basic level, Maven has built-in conventions. Here's a simple Ant build file:
 name="my-project" default="dist" basedir=".">
    
        simple example build file
       
       
     name="src" location="src/main/java"/>
     name="build" location="target/classes"/>
     name="dist"  location="target"/>

     name="init">
      
      
      
       dir="${build}"/>   
    

     name="compile" depends="init"
        description="compile the source " >
      
       srcdir="${src}" destdir="${build}"/>  
    

     name="dist" depends="compile"
        description="generate the distribution" >
      
       dir="${dist}/lib"/>

      
       jarfile="${dist}/lib/MyProject-${DSTAMP}.jar" basedir="${build}"/>
   

    name="clean"
        description="clean up" >
     
      dir="${build}"/>
      dir="${dist}"/>
   
 
In this simple Ant example, you can see how you have to tell Ant exactly what to do. There is a compile goal which includes the javac task that compiles the source in the src/main/java directory to the target/classes directory. You have to tell Ant exactly where your source is, where you want the resulting bytecode to be stored, and how to package this all into a JAR file. While there are some recent developments that help make Ant less procedural, a developer's experience with Ant is in coding a procedural language written in XML.
Contrast the previous Ant example with a Maven example. In Maven, to create a JAR file from some Java source, all you need to do is create a simple pom.xml, place your source code in ${basedir}/src/main/java and then run mvn install from the command line. The example Maven pom.xml that achieves the same results.

  4.0.0
  org.sonatype.mavenbook
  my-project
  1.0

That's all you need in your pom.xml. Running mvn install from the command line will process resources, compile source, execute unit tests, create a JAR, and install the JAR in a local repository for reuse in other projects. Without modification, you can run mvn site and then find an index.html file in target/site that contains links to JavaDoc and a few reports about your source code.
Admittedly, this is the simplest possible example project. A project which only contains source code and which produces a JAR. A project which follows Maven conventions and doesn't require any dependencies or customization. If we wanted to start customizing the behavior, our pom.xml is going to grow in size, and in the largest of projects you can see collections of very complex Maven POMs which contain a great deal of plugin customization and dependency declarations. But, even when your project's POM files become more substantial, they hold an entirely different kind of information from the build file of a similarly sized project using Ant. Maven POMs contain declarations: "This is a JAR project", and "The source code is in src/main/java". Ant build files contain explicit instructions: "This is project", "The source is in src/main/java", "Run javac against this directory", "Put the results in target/classses", "Create a JAR from the ....", etc. Where Ant had to be explicit about the process, there was something "built-in" to Maven that just knew where the source code was and how it should be processed.
High-level Comparison
The differences between Ant and Maven in this example? Ant...
  • Ant doesn't have formal conventions like a common project directory structure, you have to tell Ant exactly where to find the source and where to put the output. Informal conventions have emerged over time, but they haven't been codified into the product.
  • Ant is procedural, you have to tell Ant exactly what to do and when to do it. You had to tell it to compile, then copy, then compress.
  • Ant doesn't have a lifecycle, you had to define goals and goal dependencies. You had to attach a sequence of tasks to each goal manually.
Where Maven...
  • Maven has conventions, it already knew where your source code was because you followed the convention. It put the bytecode in target/classes, and it produced a JAR file in target.
  • Maven is declarative. All you had to do was create a pom.xml file and put your source in the default directory. Maven took care of the rest.
  • Maven has a lifecycle, which you invoked when you executed mvn install. This command told Maven to execute the a series of sequence steps until it reached the lifecycle. As a side-effect of this journey through the lifecycle, Maven executed a number of default plugin goals which did things like compile and create a JAR.
What About Ivy?
Right, so someone like Steve Loughran is going to read that comparison and call foul. He's going to talk about how the answer completely ignores something called Ivy and the fact that Ant can reuse build logic in the more recent releases of Ant. This is true. If you have a bunch of smart people using Ant + antlibs + Ivy, you'll end up with a well designed build that works. Even though, I'm very much convinced that Maven makes sense, I'd happily use Ant + Ivy with a project team that had a very sharp build engineer. That being said, I do think you'll end up missing out on a number of valuable plugins such as the Jetty plugin and that you'll end up doing a whole bunch of work that you didn't need to do over time.
More Important than Maven vs. Ant
  1. Is that you use a Repository Manager to keep track of software artifacts. I'd suggest downloading Nexus. You can use Nexus to proxy remote repositories and to provide a place for your team to deploy internal artifacts.
  2. You have appropriate modularization of software components. One big monolithic component rarely scales over time. As you project developers, you'll want to have the concept of modules and sub-modules. Maven lends itself to this approach very well.
  3. You adopt some conventions for your build. Even if you use Ant, you should strive to adopt some form of convention that is consistent with other projects. When a project uses Maven, it means that anyone familiar with Maven can pick up the build and start running with it without having to fiddle with configuration just to figure out how to get the thing to compile.
http://stackoverflow.com/questions/603189/differences-between-ant-and-maven

Sunday, May 27, 2012

JDBC - Statement, PreparedStatement, CallableStatement and caching

Statement vs PreparedStatement
  1. Performance can be better with PreparedStatement but is database dependent.
  2. With PreparedStatement you avoid SQL injection. How does a PreparedStatement avoid or prevent SQL injection?
  3. Better type check with preparedStatement by setInt, setString where as statement you just keep appending to the main SQL.
Similar Post:
CallableStatement - Java answer to access StoredProcedures across all databases.
Similar post
With PreparedStatement and Callable you already have caching, also caching is a big topic in its own, you wouldn't like to do all of that instead look at ehcache
You should almost always prefer PreparedStatement over Statement
If you have to operate over StoredProcedure you have just one option CallableStatement.

Saturday, May 26, 2012

How to use Ant?

Ant is a build tool. Say for example you have several projects in your Eclipse workspace, all of which are pieces of a larger application. To build it all into a jar file with dependencies included, you could select all the projects and export them as a jar file, but that's somewhat cumbersome.
Ant is an extensible solution. You define the build process in XML, and ant compiles your java files according to this recipe.
Ant can do more than building, too. I worked at a company where the mechanism for deployment was Debian packages in our own repository. We had Ant scripts that would build the jar files, arrange them and some metadata files into a Debian package, put them into the repository, and re-generate the repository manifest.
As with anything Java, there's a lot of configuration you need to get your head around before you're proficient with Ant, but some of the basic tutorials should give you an idea of what you're getting yourself into.

Maven or Ant?

Contrary to what @Joe Skora has said, with Maven 2 I have rarely needed to use ant in combination with Maven. Maven 1 was built on top of ant, so you often found yourself dropping down into ant related things. I rarely have, however, with Maven.
These are the reasons I advocate Maven:
  • Repeatable builds / Dependency Management. All it takes is a check out of your source and, if necessary, a Maven configuration file, and you can issue one command and all of the dependencies for your project will be downloaded and then the project will be built. No checking of binary jars into your source control, or manually copying things, or whatever. Also, it handles transitive dependencies. If you depend directly on one library, you don't have to list its dependencies as well. Maven automatically figures that out for you.
  • Versioned artifacts This is an extension of the above point. Any given Maven project is required to have a version number. When you deploy built resources to your internal Maven repositories, it is easy to point to any given version. After getting used to this method of development, it doesn't make sense to me any longer to not have versions of both the built artifacts and its dependencies when doing development.
  • Convention and configuration over scripting. Maven has set conventions for project layout. It constructs classpaths based upon your declared dependencies and their transitive dependencies. With ant, you have to explicitly write out XML "code" for the steps to compile, to construct jars, to set up your classpaths, etc. Maven is much more declarative.
  • IDEs Yes, many ides have Ant integration or are based upon ant. Yet, I find that many people who use ant built scripts tend to check in IDE project files (.project for Eclipse, for example) into source control. This is often bad because of pathnames and so forth. With Maven, out of the box you can generate project files for Eclipse and IDEA, and other IDE's like Netbeans can simply open existing Maven projects. No need to check configuration files into source control.
Those are my main reasons for advocating Maven. However, as others have noted, it is far from perfect:
  • The documentation is lacking in places.
  • Sometimes you have to do silly things to work around bugs in the dependency calculation mechanism.
  • It can be slow at times (though I hear this is being worked on).
The declarative dependency management and version artifacts alone have got me sold on Maven.

Unable to locate the Javac Compiler with Maven and Eclipse

Unable to locate the Javac Compiler in:
C:\Program Files\Java\jre6\..\lib\tools.jar
Please ensure you are using JDK 1.4 or above and
not a JRE (the com.sun.tools.javac.Main class is required).
In most cases you can change the location of your Java
installation by setting the JAVA_HOME environment variable.
The solution that worked for me (tested on both 32- and 64-bit Eclipse/Java) was not to change theeclipse.ini, but to instead set the Runtime JRE on the JRE tab of the Run/Debug Configuration dialog to use the appropriate JDK, either as the “Workspace default JRE” or the “Alternate JRE”


Designing with interfaces

Separation of interface and implementation is central to Java's spirit, and the Java interface construct enables you to achieve this separation in your designs. Two major activities of any software system design are identifying parts (the subsystems within a program or system of programs) and specifying the interfaces between the parts. In designing a Java-based system, you should use Java interfaces to represent abstract interfaces -- the ways in which the parts will interact with each other.
So this is how I ended up thinking about Java's interfaces: as the preferred means of communicating with the parts of your program that represent abstractions that may have several implementations. For example, two parts of a program I describe in my September Design Techniques installment, "The Event Generator Idiom", were TelephoneListener and Telephone. In this design, I decided that the "telephone listener" represented an abstraction that could have multiple implementations, but thatTelephone did not. Thus, I made Telephone a class that didn't implement any interfaces, and defined TelephoneListener as an interface. Telephone, an event source, passed events to (communicated with) listeners through the TelephoneListenerinterface.
I see interfaces as a fundamental tool for achieving flexibility in the design of Java-based systems. Any class can provide an implementation of an interface. As long as you don't change the interface itself, you can make all kind of changes to the implementing classes, or plug in new classes, without impacting code that depends only on the interface. Thus, if you have a subsystem that represents an abstraction that may have multiple implementations, whether the subsystem is a single object, a group of objects, an entire Java applet or application, you should define Java interfaces through which the rest of the world communicates with that subsystem. When you use interfaces in this way, you decouple the parts of your system from each other and generate code that is more flexible: more easily changed, extended, and customized.

Friday, May 25, 2012

Inner Join for three tables?

You can use parenthesis:
Code:
Dim strsql2 = "SELECT employe.*, location.*, job.*
 FROM 
  (employe INNER JOIN location
   ON employe.ID_employe = location.ID_employe)
  INNER JOIN job
   ON employe.ID_employe = job.ID_employe 
 WHERE employe.ID_employe = " & Form3.manipulatedRow & " "
Or you can use the old method, preferred by many programmers, including myself:
Code:
Dim strsql2 = "SELECT employe.*, location.*, job.*
 FROM employe, location, job
 WHERE employe.ID_employe = location.ID_employe
   AND employe.ID_employe = job.ID_employe 
   AND employe.ID_employe = " & Form3.manipulatedRow & " "
http://forums.codeguru.com/showthread.php?t=382050

Wednesday, May 23, 2012

SQL SERVER – Union vs. Union All – Which is better for performance?

This article is completely re-written with better example SQL SERVER – Difference Between Union vs. Union All – Optimal Performance Comparison. I suggest all of my readers to go here for update article.
UNION
The UNION command is used to select related information from two tables, much like the JOIN command. However, when using the UNION command all selected columns need to be of the same data type. With UNION, only distinct values are selected.
UNION ALL
The UNION ALL command is equal to the UNION command, except that UNION ALL selects all values.
The difference between Union and Union all is that Union all will not eliminate duplicate rows, instead it just pulls all rows from all tables fitting your query specifics and combines them into a table.
A UNION statement effectively does a SELECT DISTINCT on the results set. If you know that all the records returned are unique from your union, use UNION ALL instead, it gives faster results.
Example:
Table 1 : First,Second,Third,Fourth,Fifth
Table 2 : First,Second,Fifth,Sixth
Result Set:
UNION: First,Second,Third,Fourth,Fifth,Sixth (This will remove duplicate values)
UNION ALL: First,First,Second,Second,Third,Fourth,Fifth,Fifth,Sixth,Sixth (This will repeat values)
Reference : Pinal Dave (http://blog.SQLAuthority.com)

What is the difference between Join and Union?


UNION puts lines from queries after each other, while JOIN makes a cartesian product and subsets it -- completely different operations. Trivial example of UNION:
mysql> SELECT 23 AS bah
    -> UNION
    -> SELECT 45 AS bah;
+-----+
| bah |
+-----+
|  23 | 
|  45 | 
+-----+
2 rows in set (0.00 sec)
similary trivial example of JOIN:
mysql> SELECT * FROM 
    -> (SELECT 23 AS bah) AS foo 
    -> JOIN 
    -> (SELECT 45 AS bah) AS bar
    -> ON (33=33);
+-----+-----+
| bah | bah |
+-----+-----+
|  23 |  45 | 
+-----+-----+
1 row in set (0.01 sec)
http://stackoverflow.com/questions/905379/what-is-the-difference-between-join-and-union 

REST and SOAP

Both methods are used by many of the large players. It's a matter of preference. My preference is REST because it's simpler to use and understand.
SOAP:
  • SOAP builds an XML protocol on top of HTTP or sometimes TCP/IP.
  • SOAP describes functions, and types of data.
  • SOAP is a successor of XML-RPC and is very similar, but describes a standard way to communicate.
  • Several programming languages have native support for SOAP, you typically feed it a web service URL and you can call its web service functions without the need of specific code.
  • Binary data that is sent must be encoded first into a format such as base64 encoded.
  • Has several protocols and technologies relating to it: WSDL, XSDs, SOAP, WS-Addressing
Representational state transfer (REST):
  • REST need not be over HTTP but most of my points below will have an HTTP bias.
  • REST is very lightweight, it says wait a minute, we don't need all of this complexity that SOAP created.
  • Typically uses normal HTTP methods instead of a big XML format describing everything. For example to obtain a resource you use HTTP GET, to put a resource on the server you use HTTP PUT. To delete a resource on the server you use HTTP DELETE.
  • REST is a very simple in that it uses HTTP GET, POST and PUT methods to update resources on the server.
  • REST typically is best used with Resource Oriented Architecture (ROA). In this mode of thinking everything is a resource, and you would operate on these resources.
  • As long as your programming language has an HTTP library, and most do, you can consume a REST HTTP protocol very easily.
  • Binary data or binary resources can simply be delivered upon their request.
There are endless debates on REST vs SOAP on google.
My favorite is this one.

http://stackoverflow.com/questions/209905/rest-and-soap

Why do so few people use Maven? Are there alternative tools?

I like Maven and use it almost exclusively in my company. But I'd justify my reasons for doing so:
  1. I run a team of developers and we need structure. I need most of my developers to follow a certain set of conventions down to project layouts. This is to make it easier for handovers when attrition occurs.
  2. Maven archetypes are a major blessing in this regard. The seniors would just create specific archetypes for certain project templates which all developers just base their projects on. There's a really simple generic one for those cases where we didn't manage to cater for. Checking out an ant-based layout from SVN is less intuitive in this regard as the developer will still need to remove the original .svn metadata once it's checked out.
  3. Maven helps us remain IDE-agnostic. I don't want to base any of my hiring policies on what IDE the developer prefers to use. At least 2 major IDEs (Eclipse and NetBeans) have pretty good integration to Maven already such that a pom.xml file already is the definition of an IDE project. I can tell any new developer that he can use whatever IDE he prefers as long as the build system itself is based on Maven.
  4. I found that the development bootstrap process for picking up things midway was drastically cut down when I switched to Maven. New developers, even those unfamiliar with the project at hand, was able to at least compile, package and deploy within half hour of briefing them of the project. Support staff (who are typically not as technically adept) were able to concentrate on troubleshooting and not fret about building the project, which is an unnecessary irritation.
All in all, Maven suits my needs perfectly. I do agree to a certain extent that an independent developer who has his own workflow and project management practices may not derive much benefit from it, but none of us over here work in a void by ourselves.

http://stackoverflow.com/questions/1077477/why-do-so-few-people-use-maven-are-there-alternative-tools

Tuesday, May 22, 2012

Difference between final, finally and finalize()

  • final ? constant declaration.
  • finally ? The finally block always executes when the try block exits, except System.exit(0) call. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling ? it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
  • finalize() ? method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize() method.

Monday, May 21, 2012

Difference between Java SE/EE/ME?

JavaSE = Standard Edition. This is the core Java programming platform. It contains all of the libraries and APIs that any Java programmer should learn (java.lang, java.io, java.math, java.net, java.util, etc...).
JavaEE = Enterprise Edition. From wikipedia: "The Java platform (Enterprise Edition) differs from the Java Standard Edition Platform (Java SE) in that it adds libraries which provide functionality to deploy fault-tolerant, distributed, multi-tier Java software, based largely on modular components running on an application server." In other words, if your application demands a very large scale, distributed system, then you should consider using JavaEE. Built on top of JavaSE, it provides libraries for database access (JDBC, JPA), remote method invocation (RMI), messaging (JSM), web services, XML processing, and defines standard APIs for Enterprise JavaBeans, servlets, portlets, JavaServer Pages, etc...
JavaME = Micro Edition. This is the platform for developing applications for mobile devices and embedded systems such as set-top boxes. JavaME provides a subset of the functionality of JavaSE, but also introduces libraries specific to mobile devices. Because JavaME is based on an earlier version of JavaSE, some of the new language features introduced in Java 1.5 (eg. generics) are not available.
If you are new to Java, definitely start with JavaSE.
I would also recommend using Eclipse instead of Komodo IDE, since this is the most widely used editor within the industry. Because it has built in support for Java, you will benefit from all the usual advantages of using an IDE: code assist, syntax highlighting, auto compile, etc...
Good luck!

http://stackoverflow.com/questions/2857376/difference-between-java-se-ee-me

Saturday, May 19, 2012

Thursday, May 17, 2012

Can’t start Mysql error 1067

If you install under windows system, sometime it will suddenly unable to start the service,
i face this issue quite a few times already, finally i found a solution for it,
1st step check the error, under your installation path for mysql, check the data/mysql.err, it the error showing you something like this ..
050213 20:43:37 InnoDB: Starting shutdown…
050213 20:43:40 InnoDB: Shutdown completed; log sequence number 0 1051715
050213 20:43:40 [Note] C:Webmysqlbinmysqld-nt: Shutdown complete
this should be the log file having problem !
2nd step remove the ib_logfile0 or ib_logfile1 in the same folder
3rd step restart the mysql …
da da da … mysql service is running again

http://imknight.net/development/cant-start-mysql-error-1067/

Sunday, May 13, 2012

Difference between commit and flush in Hibernate

Commit will make the database commit
- Flushing is the process of synchronizing the underlying persistent
store with persistable state held in memory.
ie. it will update or insert into your tables in the running
transaction, but it _may_ not commit those changes (this depends on
your flush mode). When you have a persisted object and you change a
value on it, it becomes dirty and hibernate needs to flush these
changes to your persistence layer. It may do this automatically for
you or you may need to do this manually, that depends on your flush
mode, check http://www.hibernate.org/hib_docs/v3/api/org/hibernate/FlushMode.html
for further details on which flush mode is the right one for you.

http://www.coderanch.com/t/218534/ORM/java/Difference-between-commit-flush-Hibernate

How does Hibernate detect dirty state of an entity object?

Hibernate uses a strategy called inspection, which is basically this: when an object is loaded from the database a snapshot of it is kept in memory. When the session is flushed Hibernate compares the stored snapshot with the current state. If they differ the object is marked as dirty and a suitable SQL command is enqueued. If the object is still transient then it is always dirty.
Source: book Hibernate in Action (appendix B: ORM implementation strategies)
It's important to notice however that Hibernate's dirty-checking is independent of the methods equals/hascode. Hibernate does not look at these methods at all (except when using java.util.Set's, but this is unrelated to dirty-checking, only to the Collections API) The state snapshot I mentioned earlier is something similar to an array of values. It would be a very bad decision to leave such a core aspect of the framework in the hands of developers (to be honest, developers should not care about dirty-checking). Needless to say that equals/hascode can be implemented in many ways according to your needs. I recommend you to read the cited book, there the author discuss equals/hascode implementation strategies. Very insightful reading.
EDIT: fixed typos
http://stackoverflow.com/questions/5268466/how-does-hibernate-detect-dirty-state-of-an-entity-object