Sunday, August 26, 2012

Most Java objects are not immutable

For many junior programmers fact that Java objects are not immutable is like a science. Recently, our junior programmer has asked me to debug the next code as he was so confused about the output:

private SomeObject{

private AnotherObject anObj;

public setAnotherObject (AnotherObject anObj){
  this.anObj = anObj;
}

useObject(){
System.out.println("Object value is " + this.anObj.getX()); // line 15
}

}


private ActionObjet{

private someMethod(){
     private AnotherObject anObj = new AnotherObject();
     anObj.setX(55);
     SomeObject sm = SomeObjec();
     sm.setAnotherObjec(anObj);
//here goes stupidity
     anObj.setX(999);
//here goes another stupidity
     sm.useObject();
// he gets that output is 999
// oh my God he says, its something unrealistic and so on...IT SHOULD BE 55. I AN CERTAIN
}

}

Main problem is if you give an object to another object instance variable and change that object somewhere in the future the object instance variable refers to the change object.

In order not to make so stupid mistakes give your junior programmers a book about Java language!

Tuesday, August 14, 2012

H2, Spring Framework configuration

In order to simplify communication with database sometimes we use light-weight databases. That databases could be started in embedded mode(you do not have to install database at all). I will show how   to configure H2 database for using with Spring Framework and IBatis(MyBatis).

First of all, define sqlSessionFactory bean.


        <bean id= "sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" >
              <property name= "dataSource" ref ="dataSource" />
              <property name= "configLocation" value="WEB-INF/mybatis/sqlmap-config.xml" />
        </bean>
 
So, define dataSource

<jdbc:embedded-database id ="dataSource" type= "H2">
              <jdbc:script location= "/WEB-INF/table_data.sql" />
    </jdbc:embedded-database>
 
And declare transaction manager
        
        <bean id= "transactionManager"
               class= "org.springframework.jdbc.datasource.DataSourceTransactionManager"
              p:dataSource-ref="dataSource" />

    

And of course, we need SQL statements in file table_data.sql 


DROP TABLE IF EXISTS User;

CREATE TABLE User(
ID INTEGER AUTO_INCREMENT PRIMARY KEY ,
NAME VARCHAR(50),
ADDRESS VARCHAR (50),
AGE INTGERE
);

INSERT INTO User (ID, NAME, ADDRESS, AGE) VALUES (1, 'Jevgeni', 'Rae XX' , '34'); 

Use with pleasure!