01 11 2009

Hibernate Criteria API and Projections

1. Group by

ProjectionList proList = Projections.projectionList();
proList.add(Projections.property("companyname"));
proList.add(Projections.count("companyname"));
proList.add(Projections.groupProperty("companyname"));

Criteria criteria = session.createCriteria(Customers.class);
criteria.setProjection(proList);

List groupedCompanyNames = criteria.list();

Output :


image


2. Distinct




ProjectionList proList = Projections.projectionList();
proList.add(Projections.distinct(Projections.property("companyname")));
Criteria criteria = session.createCriteria(Customers.class);
criteria.setProjection(proList);

List distinctdCompanyNames = criteria.list();







Output:

image


3. setResultTransformer




ProjectionList proList = Projections.projectionList();
proList.add(Projections.distinct(Projections.property("companyname")));
proList.add(Projections.count("companyname"));
proList.add(Projections.groupProperty("companyname"));
Criteria criteria = session.createCriteria(Customers.class);
criteria.setProjection(proList);

List<Customers> customerList = criteria
.setResultTransformer(new AliasToBeanResultTransformer(Customers.class)).list();

4. where in = subqueries



DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Orders.class);
detachedCriteria.setProjection(Projections.distinct(Property.forName(("customers"))));

ProjectionList proList = Projections.projectionList();
proList.add(Projections.distinct(Projections.property("companyname")));
proList.add(Projections.property("customerid"));
proList.add(Projections.count("companyname"));
proList.add(Projections.groupProperty("companyname"));
proList.add(Projections.groupProperty("customerid"));
Criteria criteria = session.createCriteria(Customers.class);


criteria.add(Property.forName("customerid").in(detachedCriteria));
criteria.setProjection(proList);


List<Customers> customerList = criteria
.setResultTransformer(new AliasToBeanResultTransformer(Customers.class)).list();



image



Technorati Tags: ,,

30 10 2009

JxInsight – How many times i’ve connected a database ?

If you enable jdbinsight, you can trace your database activities from jxinsight console. To do this configuration copy
{jxinsight}\lib\jxinsight-jdbc-drivers.jar,
{jxinsight}\lib\jjxinsight-ext-aj-jdbc-namedprobes.jar files to your application server’s lib directory.
Add jxinsight.aspectj.filters oracle.
After doing that configuration you will see that url tab is enabled in jxInsight console.
image

From JxInsight’s profile section, you will see JDBC Resources. From this tab looking at the picture below it is easily understood that, a piece of code is executed 100 times over a connection.
image

29 10 2009

JxInsight – Where in my code is executed most of the time

In JxInsight just looking at Percentage Total Inherent column you can watch where in your code is executed in most of the time. Just to show, i developed a sample Hibernate application which opens and closes  a connection in hundred times.

for(int i = 0; i < 100; ++i)
{
Session session = HibernateUtil.getSession();
Criteria criteria = session.createCriteria(Customers.class);
criteria.setProjection(Projections.projectionList().
add(Projections.count("customerid")).
add(Projections.groupProperty("customerid"))
);


criteria.add(Expression.eq("customerid", "ALFKI"));
criteria.setComment("Sample Comment");

List<Object> list = criteria.list();





For that code, JxInsight shows me that most of the connection is the most significant time consuming code as you can see from the picture below.



image



From the snapshot, it can be easily understood that what it have to be done is managing the connection. 

Profiling with JxInsight

Nowadays most of my time, i’m dealing with profiling to optimize our code. Previous week i met William Louth who is the founder of Jinspired company. Today’s post is about his software jxinsight which i like to work on.

Profiling is a topic of performance engineering.  First of all you have to learn what the system is made of and what is the key components which have been used. With JxInsight you have a chance to see which components are used.
image

20 10 2009

Organic Software Days

organik15

13 10 2009

Hibernate and NHibernate Configuration : Step 1

Today’s post is about configuring NHibernate and Hibernate.  In Eclipse, i haven’t configured my eclipse environment by hibernate tools so i created a project with Netbeans and then copied all necessary files to eclipse’s workspace.

1. Configure hbm files
Java Verion :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Oct 6, 2009 1:42:21 AM by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
<class name="com.montoya.orm.Customers" schema="SYSTEM" table="CUSTOMERS">
<id name="customerid" type="string">
<column length="5" name="CUSTOMERID"/>
<generator class="assigned"/>
</id>
<property name="companyname" type="string">
<column length="40" name="COMPANYNAME" not-null="true"/>
</property>
<property name="contactname" type="string">
<column length="30" name="CONTACTNAME"/>
</property>
<property name="contacttitle" type="string">
<column length="30" name="CONTACTTITLE"/>
</property>
<property name="address" type="string">
<column length="60" name="ADDRESS"/>
</property>
<property name="city" type="string">
<column length="15" name="CITY"/>
</property>
<property name="region" type="string">
<column length="15" name="REGION"/>
</property>
<property name="postalcode" type="string">
<column length="10" name="POSTALCODE"/>
</property>
<property name="country" type="string">
<column length="15" name="COUNTRY"/>
</property>
<property name="phone" type="string">
<column length="24" name="PHONE"/>
</property>
<property name="fax" type="string">
<column length="24" name="FAX"/>
</property>
<set inverse="true" name="orderses">
<key>
<column length="5" name="CUSTOMERID"/>
</key>
<one-to-many class="com.montoya.orm.Orders"/>
</set>
<set inverse="false" name="customerdemographicses" table="CUSTOMERCUSTOMERDEMO">
<key>
<column length="5" name="CUSTOMERID" not-null="true"/>
</key>
<many-to-many entity-name="com.montoya.orm.Customerdemographics">
<column length="10" name="CUSTOMERTYPEID" not-null="true"/>
</many-to-many>
</set>
</class>
</hibernate-mapping>

.NET Version





<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Montoya.Core" namespace="Montoya.Core">
<class name="Montoya.Core.Customer,Montoya.Core" schema="SYSTEM" table="CUSTOMERS">
<id name="CustomerId" column="CUSTOMERID" type="System.String" unsaved-value="1">
<column length="5" name="CUSTOMERID"/>
<generator class="assigned"/>
</id>
<property name="CompanyName" column="COMPANYNAME" type="System.String" length="40" not-null="true"></property>
<property name="ContactName" column="CONTACTNAME" type="System.String" length="255" not-null="true"></property>
<property name="ContactTitle" column="CONTACTTITLE" type="System.String" length="255" not-null="true"></property>
<property name="Address" column="ADDRESS" type="System.String" length="255" not-null="true"></property>
<property name="City" column="CITY" type="System.String" length="255" not-null="true"></property>
<property name="Region" column="REGION" type="System.String" length="255" not-null="true"></property>
<property name="PostalCode" column="POSTALCODE" type="System.String" length="255" not-null="true"></property>
<property name="Country" column="COUNTRY" type="System.String" length="255" not-null="true"></property>
<property name="Phone" column="PHONE" type="System.String" length="255" not-null="true"></property>
<property name="Fax" column="FAX" type="System.String" length="255" not-null="true"></property>

</class>

</hibernate-mapping>





2. Configure hibernate.cfg.xml

java version



<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:testDB</property>
<property name="hibernate.connection.username">system</property>
<property name="hibernate.connection.password">xxx</property>
<mapping resource="com/montoya/orm/Region.hbm.xml"/>
<mapping resource="com/montoya/orm/Employees.hbm.xml"/>
<mapping resource="com/montoya/orm/Territories.hbm.xml"/>
<mapping resource="com/montoya/orm/Customerdemographics.hbm.xml"/>
<mapping resource="com/montoya/orm/Orderdetails.hbm.xml"/>
<mapping resource="com/montoya/orm/Categories.hbm.xml"/>
<mapping resource="com/montoya/orm/Orders.hbm.xml"/>
<mapping resource="com/montoya/orm/Products.hbm.xml"/>
<mapping resource="com/montoya/orm/Suppliers.hbm.xml"/>
<mapping resource="com/montoya/orm/Shippers.hbm.xml"/>
<mapping resource="com/montoya/orm/Customers.hbm.xml"/>
</session-factory>
</hibernate-configuration>





.Net Version







<?xml version="1.0" encoding="UTF-8"?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory name="Montoya.Core.Test">
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="show_sql">true</property>
<property name="connection.driver_class">NHibernate.Driver.OracleClientDriver</property>
<property name="connection.connection_string">Data Source=testDB;User Id=system;Password=xxx;</property>
<property name="dialect">NHibernate.Dialect.Oracle10gDialect</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
<mapping assembly="Montoya.Core"/>
</session-factory>
</hibernate-configuration>



3. Configure Hibernate Session





Java Version





public class HibernateUtil {
private static final SessionFactory sessionFactory;

static {
try {

sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}

public static Session getSession()
{
return getSessionFactory().openSession();
}
}



.Net Version





NHibernate.Cfg.Configuration cfg = new Configuration();
cfg.Configure();

ISessionFactory sessionFactory = cfg.BuildSessionFactory();
ISession session = sessionFactory.OpenSession();






 

04 10 2009

Unit Testing & Mocking with Easy Mock

If you are a fresh graduate worker for a corporate  company ,probably all dirty jobs that effect whole system are assigned to you. With an afraid of changing  the code, you read the code to find out where will be effected. Especially legacy systems can be so sophisticated that changing a piece of code, can make the whole system down in a second.

Testers, developers, project managers and customers do testing but the way of their tests are different. In this post i will not tell  how you can test whole system as a single entity, in direct contradiction I'm going to tell how you can test individual classes, methods by unit testing and dependent objects by mocking.

Eclipse provides  jUnit as a  default testing framework for  developers to write test codes in a little time by defining  just simple annotations. Fundamentally, JUnit provides three annotations; @setup which prepares pre testing conditions, @Test  which defines Service UnderTest, @After which prepares postConditions of the test.

To demostrate how it works, firstly i developed a single math class and a add method.

public class Math
{
public int add(int a, int b)
{
return a + b;
}
}



and wrote a three lines of code to test.




public class MathTest
{
private com.demo.dao.Math sut = null; //Service Under Test (SUT)

@Before
public void setup()
{
this.sut = new com.demo.dao.Math();
System.out.println("MathTest.setup()");
}


@Test
public void Add()
{
int a,b;
a = 10;
b = 30;

Assert.assertEquals(40, this.sut.add(a,b));
System.out.println("MathTest.Add()");


}

@After
public void tearDown()
{
this.sut = null;
System.out.println("MathTest.tearDown()");
}

}





So far so good. Think that days after days, you hire a new worker and assigned a issue to develop multiply function. Our worker will probably copy/paste the add code and will forget the change the + signal to *;  If our dummy worker can write test code for this math class he will see that multiply method does not work as he expected.




This is the easiest way of describing testing but in complex architectures it is not simple as i told. Because test code is optional (it is not what the customer wants), most of the developers will just develop automated tests for single, simple tests to satisfy project manager.





As you understand Unit testing helps developers the test the functionality of a function and class. Mocking means moving sophisticated dependencies from test code. Instead of initializing some objects and binding these objects to other objects  bore developers. By creating dummy mock objects, you make the class  tend to be the object that the SUT needs. But be careful mocking is not for testing functionality of a SUT, it is for testing the dependency of SUT.








package com.demo.dao;

public interface IUser
{
public void setLoginDao(IUserLoginDao dao);
public boolean login(String userName,String password);
}






package com.demo.dao;

public interface IUserLoginDao
{
public boolean login(String userName,String password);
}






package com.demo.dao;

public class UserService implements IUser
{


private IUserLoginDao userDao = null;

@Override
public boolean login(String userName, String password)
{
return this.userDao.login(userName, password);
}

@Override
public void setLoginDao(IUserLoginDao dao)
{
this.userDao = dao;

}
}

Easy Mock


1. It' is proxy based, so it is used to imitate the real object that SUT needs


2. Just writing 3 lines of code you initialize the proxy object.


image 
3. it is really easy.[http://www.jmock.org/easymock-comparison.html]