-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 7 posts ] 
Author Message
 Post subject: Performance Problems
PostPosted: Thu Apr 28, 2011 8:38 am 
Newbie

Joined: Thu Apr 28, 2011 6:40 am
Posts: 3
Hi

Im doing some Performance testing on different ORM-tools and Im new to Hibernate. For my testing of Hibernate I have created two Classes: CustomerT and CustomerDetailsT and mapped them using JPA annotations.
relationship is One to Many that is: One CustomerT can have many CustomerDetailsT.

Now everything works fine and the tables are created (In MSSQL server) but my question is can I make Hibernete work faster? In my code I have set some timers to find out what takes longest to do. And it seems like it takes far to much time to get the Objects:

long startTimeGetCustomers = System.currentTimeMillis();
HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
customers =(List)HibernateUtil.getSessionFactory().getCurrentSession().createCriteria(CustomerT.class).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();

long stopTimeGetCustomers = System.currentTimeMillis();
long timeGetCustomers = stopTimeGetCustomers - startTimeGetCustomers;
System.out.println("Time to get all customers and customer details (using fetch type eager): " + timeGetCustomers+" ms");


Print out I get is :

Time to get all customers and customer details (using fetch type eager): 8364 ms
Time to call doGet method in servlet: 9284 ms

I have only 2002 CustomerT rows where each CustomerT has 30 CustomerDetailsT and it takes 8 seconds to just get the objects. (Calculations are done much faster). I need to be able to fetch all CustomerT and their CustomerDetailsT
and I need to use fetchtype Eager. Please check my Hibernate Conigurations or my HibernteUtil class. Can I make object fetching go faster if I change my Configurations somehow?

OBS I have to fetch objects every time I do the calculations that is a requisite !

Thank you for your help

Here are my Classes:

package com.hibernate.mssql;


import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.CascadeType;


@Entity
public class CustomerT {


private int customerID;
private String customerName;
private String customerAddress;
private String customerEmailaddress;
private List<CustomerDetailT> custDetails = new ArrayList<CustomerDetailT>();

@OneToMany(fetch = FetchType.EAGER)
@JoinColumn(name = "customerID")

public List<CustomerDetailT> getCustDetails() {
return custDetails;
}
public void setCustDetails(List<CustomerDetailT> custDetails) {
this.custDetails = custDetails;
}
@Id
@GeneratedValue
public int getCustomerID() {
return customerID;
}
public void setCustomerID(int customerID) {
this.customerID = customerID;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerAddress() {
return customerAddress;
}
public void setCustomerAddress(String customerAddress) {
this.customerAddress = customerAddress;
}
public String getCustomerEmailaddress() {
return customerEmailaddress;
}
public void setCustomerEmailaddress(String customerEmailaddress) {
this.customerEmailaddress = customerEmailaddress;
}


}


package com.hibernate.mssql;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.CascadeType;
import javax.persistence.FetchType;
import java.util.ArrayList;
import java.util.Date;
import java.util.Calendar;

@Entity
public class CustomerDetailT {
private double creditStore;
private double rewardPoints;
private double amountSpent;
private double debt;

private Calendar custJoinDate;
private Date custLogintime;
private CustomerT customer;
private int customerDetailID;

//@ManyToOne
@Id
@GeneratedValue
public int getCustomerDetailID() {
return customerDetailID;
}
public void setCustomerDetailID(int customerDetailID) {
this.customerDetailID = customerDetailID;
}

@ManyToOne
@JoinColumn(name="customerId")
public CustomerT getCustomer() {
return customer;
}

public void setCustomer(CustomerT customer) {
this.customer = customer;
}
public double getCreditStore() {
return creditStore;
}
public void setCreditStore(double creditStore) {
this.creditStore = creditStore;
}
public double getRewardPoints() {
return rewardPoints;
}
public void setRewardPoints(double rewardPoints) {
this.rewardPoints = rewardPoints;
}
public double getAmountSpent() {
return amountSpent;
}
public void setAmountSpent(double amountSpent) {
this.amountSpent = amountSpent;
}
public double getDebt() {
return debt;
}
public void setDebt(double debt) {
this.debt = debt;
}
@Temporal(TemporalType.DATE)
public Calendar getCustJoinDate() {
return custJoinDate;
}
public void setCustJoinDate(Calendar custJoinDate) {
this.custJoinDate = custJoinDate;
}
@Temporal(TemporalType.TIMESTAMP)
public Date getCustLogintime() {
return custLogintime;
}
public void setCustLogintime(Date custLogintime) {
this.custLogintime = custLogintime;
}


}

Here are my Hibernate Configurations:

<?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>

<!-- Database connection settings -->
<property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="connection.url">jdbc:sqlserver://localhost:1433;databaseName=JProCo</property>
<property name="connection.username">dejan</property>
<property name="connection.password">h2c879hp</property>
<property name = "hibernate.default_schema">TESTSCHEMA</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">2</property>

<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.SQLServerDialect</property>

<!-- Enable Hibernate's current session context -->
<property name="current_session_context_class">thread</property>

<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property><!--

Drop and re-create the database schema on startup
<property name="hbm2ddl.auto">create</property>


--></session-factory>

</hibernate-configuration>

I m using this HibernateUtil class to get SessionFactory object:

package com.hibernate.mssql;


import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory() {

try {
Configuration config = new Configuration();

config.addAnnotatedClass(CustomerT.class);
config.addAnnotatedClass(CustomerDetailT.class);
config.configure("hibernate.cfg.xml");



return config.buildSessionFactory();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}

This is my Counter.java where I do some calculations using org.apache.commons.math.stat.descriptive.DescriptiveStatistics; (dont know if you need to see this code but just in case) here is where I get my CustomerT objects



package com.hibernate.mssql;

import java.util.List;

import org.apache.commons.math.stat.descriptive.DescriptiveStatistics;
import org.hibernate.Criteria;


class Counter {
List customers;
DescriptiveStatistics stats = new DescriptiveStatistics();
CountCreditStore countCreditStore;
CountDebt countDebt;
CountRewardPoints countRewardPoints;
CountAmountSpent countAmountSpent;

public Counter(){
long startTimeGetCustomers = System.currentTimeMillis();
HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();

customers = (List)HibernateUtil.getSessionFactory().getCurrentSession().createCriteria(CustomerT.class).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
System.out.println(customers.size());
long stopTimeGetCustomers = System.currentTimeMillis();
long timeGetCustomers = stopTimeGetCustomers - startTimeGetCustomers;
System.out.println("Time to get all customers and customer details (using fetch type eager): " + timeGetCustomers+" ms");


try{
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
} catch (Exception ex) {
System.out.println(ex);
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
System.out.println(ex);
}
countCreditStore = new CountCreditStore();
countDebt = new CountDebt();
countRewardPoints = new CountRewardPoints();
countAmountSpent = new CountAmountSpent();

}



public CountCreditStore getCountCreditStore() {
return countCreditStore;
}


public CountDebt getCountDebt() {
return countDebt;
}


public CountRewardPoints getCountRewardPoints() {
return countRewardPoints;
}


public CountAmountSpent getCountAmountSpent() {
return countAmountSpent;
}



public List<CustomerT> getCustomers() {
return customers;
}








class CountAmountSpent{

double amountSpentSum = 0;
double amountSpentMax = 0;
double amountSpentMin = 0;
double amountSpentMean= 0;
double amountSpentStandardDeviation=0;
double amountSpentSkewness=0;


public double getSum(int index){

CustomerT customer = (CustomerT)customers.get(index);
stats.clear();
for (int i = 0; i<customer.getCustDetails().size(); i++){
stats.addValue(customer.getCustDetails().get(i).getAmountSpent());
amountSpentSum = stats.getSum();

}
return amountSpentSum;

}

public double getMax(int index){

CustomerT customer = (CustomerT)customers.get(index);
stats.clear();
for (int i = 0; i<customer.getCustDetails().size(); i++){
stats.addValue(customer.getCustDetails().get(i).getAmountSpent());
amountSpentMax = stats.getMax();
}
stats.clear();
return amountSpentMax;

}


public double getMin(int index){
CustomerT customer = (CustomerT)customers.get(index);
stats.clear();
for (int i = 0; i<customer.getCustDetails().size(); i++){
stats.addValue(customer.getCustDetails().get(i).getAmountSpent());
amountSpentMin = stats.getMin();
}

stats.clear();
return amountSpentMin;
}


public double getMean(int index){
CustomerT customer = (CustomerT)customers.get(index);
stats.clear();
for (int i = 0; i<customer.getCustDetails().size(); i++){
stats.addValue(customer.getCustDetails().get(i).getAmountSpent());
amountSpentMean = stats.getMean();
}
stats.clear();
return amountSpentMean;

}
public double getStandardDeviation(int index){
CustomerT customer = (CustomerT)customers.get(index);
stats.clear();
for (int i = 0; i<customer.getCustDetails().size(); i++){
stats.addValue(customer.getCustDetails().get(i).getAmountSpent());
amountSpentStandardDeviation = stats.getStandardDeviation();
}
stats.clear();
return amountSpentStandardDeviation;

}

public double getSkewness(int index){
CustomerT customer = (CustomerT)customers.get(index);
stats.clear();
for (int i = 0; i<customer.getCustDetails().size(); i++){
stats.addValue(customer.getCustDetails().get(i).getCreditStore());
amountSpentSkewness = stats.getSkewness();
}
stats.clear();
return amountSpentSkewness;

}

}


class CountCreditStore{

double creditStoreSum = 0;
double creditStoreMax = 0;
double creditStoreMin = 0;
double creditStoreMean= 0;
double creditStoreStandardDeviation=0;
double creditStoreSkewness=0;


public double getSum(int index){

CustomerT customer = (CustomerT)customers.get(index);
stats.clear();
for (int i = 0; i<customer.getCustDetails().size(); i++){
stats.addValue(customer.getCustDetails().get(i).getCreditStore());
creditStoreSum = stats.getSum();

}
return creditStoreSum;

}

public double getMax(int index){

CustomerT customer = (CustomerT)customers.get(index);
stats.clear();
for (int i = 0; i<customer.getCustDetails().size(); i++){
stats.addValue(customer.getCustDetails().get(i).getCreditStore());
creditStoreMax = stats.getMax();
}
stats.clear();
return creditStoreMax;

}


public double getMin(int index){
CustomerT customer = (CustomerT)customers.get(index);
stats.clear();
for (int i = 0; i<customer.getCustDetails().size(); i++){
stats.addValue(customer.getCustDetails().get(i).getCreditStore());
creditStoreMin = stats.getMin();
}

stats.clear();
return creditStoreMin;
}


public double getMean(int index){
CustomerT customer = (CustomerT)customers.get(index);
stats.clear();
for (int i = 0; i<customer.getCustDetails().size(); i++){
stats.addValue(customer.getCustDetails().get(i).getCreditStore());
creditStoreMean = stats.getMean();
}
stats.clear();
return creditStoreMean;

}

public double getStandardDeviation(int index){
CustomerT customer = (CustomerT)customers.get(index);
stats.clear();
for (int i = 0; i<customer.getCustDetails().size(); i++){
stats.addValue(customer.getCustDetails().get(i).getCreditStore());
creditStoreStandardDeviation = stats.getStandardDeviation();
}
stats.clear();
return creditStoreStandardDeviation;
}

public double getSkewness(int index){
CustomerT customer = (CustomerT)customers.get(index);
stats.clear();
for (int i = 0; i<customer.getCustDetails().size(); i++){
stats.addValue(customer.getCustDetails().get(i).getCreditStore());
creditStoreSkewness = stats.getSkewness();
}
stats.clear();
return creditStoreSkewness;

}
}
class CountDebt{

double debtSum = 0;
double debtMax = 0;
double debtMin = 0;
double debtMean= 0;
double debtStandardDeviation=0;
double debtSkewness=0;


public double getSum(int index){
//CustomerT customer = (CustomerT)HibernateUtil.getSessionFactory().getCurrentSession().load(CustomerT.class,index);
CustomerT customer = (CustomerT)customers.get(index);
stats.clear();
for (int i = 0; i<customer.getCustDetails().size(); i++){
stats.addValue(customer.getCustDetails().get(i).getDebt());
debtSum = stats.getSum();

}
return debtSum;

}

public double getMax(int index){

CustomerT customer = (CustomerT)customers.get(index);
stats.clear();
for (int i = 0; i<customer.getCustDetails().size(); i++){
stats.addValue(customer.getCustDetails().get(i).getDebt());
debtMax = stats.getMax();
}
stats.clear();
return debtMax;

}


public double getMin(int index){
CustomerT customer = (CustomerT)customers.get(index);
stats.clear();
for (int i = 0; i<customer.getCustDetails().size(); i++){
stats.addValue(customer.getCustDetails().get(i).getDebt());
debtMin = stats.getMin();
}

stats.clear();
return debtMin;
}


public double getMean(int index){
CustomerT customer = (CustomerT)customers.get(index);
stats.clear();
for (int i = 0; i<customer.getCustDetails().size(); i++){
stats.addValue(customer.getCustDetails().get(i).getDebt());
debtMean = stats.getMean();
}
stats.clear();
return debtMean;

}

public double getStandardDeviation(int index){
CustomerT customer = (CustomerT)customers.get(index);
stats.clear();
for (int i = 0; i<customer.getCustDetails().size(); i++){
stats.addValue(customer.getCustDetails().get(i).getDebt());
debtStandardDeviation = stats.getStandardDeviation();
}
stats.clear();
return debtStandardDeviation;
}

public double getSkewness(int index){
CustomerT customer = (CustomerT)customers.get(index);
stats.clear();
for (int i = 0; i<customer.getCustDetails().size(); i++){
stats.addValue(customer.getCustDetails().get(i).getDebt());
debtSkewness = stats.getSkewness();
}
stats.clear();
return debtSkewness;

}


}

public class CountRewardPoints{

double rewardPointsSum = 0;
double rewardPointsMax = 0;
double rewardPointsMin = 0;
double rewardPointsMean= 0;
double rewardPointsStandardDeviation=0;
double rewardPointsSkewness=0;


public double getSum(int index){

CustomerT customer = (CustomerT)customers.get(index);
stats.clear();
for (int i = 0; i<customer.getCustDetails().size(); i++){
stats.addValue(customer.getCustDetails().get(i).getRewardPoints());
rewardPointsSum = stats.getSum();

}
stats.clear();
return rewardPointsSum;

}

public double getMax(int index){

CustomerT customer = (CustomerT)customers.get(index);
stats.clear();
for (int i = 0; i<customer.getCustDetails().size(); i++){
stats.addValue(customer.getCustDetails().get(i).getRewardPoints());
rewardPointsMax = stats.getMax();
}
stats.clear();
return rewardPointsMax;

}


public double getMin(int index){
CustomerT customer = (CustomerT)customers.get(index);
stats.clear();
for (int i = 0; i<customer.getCustDetails().size(); i++){
stats.addValue(customer.getCustDetails().get(i).getRewardPoints());
rewardPointsMin = stats.getMin();
}

stats.clear();
return rewardPointsMin;
}


public double getMean(int index){
CustomerT customer = (CustomerT)customers.get(index);
stats.clear();
for (int i = 0; i<customer.getCustDetails().size(); i++){
stats.addValue(customer.getCustDetails().get(i).getRewardPoints());
rewardPointsMean = stats.getMean();
}
stats.clear();
return rewardPointsMean;

}

public double getStandardDeviation(int index){
CustomerT customer = (CustomerT)customers.get(index);
stats.clear();
for (int i = 0; i<customer.getCustDetails().size(); i++){
stats.addValue(customer.getCustDetails().get(i).getRewardPoints());
rewardPointsStandardDeviation = stats.getStandardDeviation();
}
stats.clear();
return rewardPointsStandardDeviation;
}

public double getSkewness(int index){
CustomerT customer = (CustomerT)customers.get(index);
stats.clear();
for (int i = 0; i<customer.getCustDetails().size(); i++){
stats.addValue(customer.getCustDetails().get(i).getRewardPoints());
rewardPointsSkewness = stats.getSkewness();
}
stats.clear();
return rewardPointsSkewness;

}



}

}

And finally I show everything using a simple java servlet:


package com.hibernate.mssql;



import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;







public class ShowCountServlet extends HttpServlet {



protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

long startTime = System.currentTimeMillis();
Counter counter = new Counter();

try{
// Write HTML header
PrintWriter out = response.getWriter();
out.println("<html><head><title>Object Counter</title></head><body>");
printCountAction(out);

// Handle actions
if ( "credit store".equals(request.getParameter("actionCreditStore3")) ) {


out.println("<h2> Customers in database:</h2>");
out.println("<table border='1'>");
out.println("<tr>");
out.println("<th>Customer name</th>");
out.println("<th>Customer Id</th>");
out.println("<th>total credit store</th>");
out.println("<th>max credit store</th>");
out.println("<th>min credit store</th>");
out.println("<th>mean credit store</th>");
out.println("<th> credit store standard deviation </th>");
out.println("<th> credit store skewness </th>");
out.println("</tr>");

for (int i = 0; i< counter.getCustomers().size(); i++) {

out.println("<tr>");
out.println("<td>" + counter.getCustomers().get(i).getCustomerName() + "</td>");
out.println("<td>" + counter.getCustomers().get(i).getCustomerID() + "</td>");
out.println("<td>" + counter.getCountCreditStore().getSum(i) + "</td>");
out.println("<td>" + counter.getCountCreditStore().getMax(i) + "</td>");
out.println("<td>" + counter.getCountCreditStore().getMin(i) + "</td>");
out.println("<td>" + counter.getCountCreditStore().getMean(i)+ "</td>");
out.println("<td>" + counter.getCountCreditStore().getStandardDeviation(i)+ "</td>");
out.println("<td>" + counter.getCountCreditStore().getSkewness(i) + "</td>");
}


out.println("</table>");

}




if ( "amount spent".equals(request.getParameter("actionAmountSpent3")) ) {



out.println("<h2> Customers in database:</h2>");
out.println("<table border='1'>");
out.println("<tr>");
out.println("<th>Customer name</th>");
out.println("<th>Customer Id</th>");
out.println("<th>total amount spent</th>");
out.println("<th>max amount spent</th>");
out.println("<th>min amount spent</th>");
out.println("<th>mean amount spent</th>");
out.println("<th>amount spent standard deviation </th>");
out.println("<th> skewness </th>");
out.println("</tr>");

for (int i = 0; i< counter.getCustomers().size(); i++) {

out.println("<tr>");
out.println("<td>" + counter.getCustomers().get(i).getCustomerName() + "</td>");
out.println("<td>" + counter.getCustomers().get(i).getCustomerID() + "</td>");
out.println("<td>" + counter.getCountAmountSpent().getSum(i) + "</td>");
out.println("<td>" + counter.getCountAmountSpent().getMax(i) + "</td>");
out.println("<td>" + counter.getCountAmountSpent().getMin(i) + "</td>");
out.println("<td>" + counter.getCountAmountSpent().getMean(i)+ "</td>");
out.println("<td>" + counter.getCountAmountSpent().getStandardDeviation(i)+ "</td>");
out.println("<td>" + counter.getCountAmountSpent().getSkewness(i) + "</td>");
}


out.println("</table>");

}



if ( "debt".equals(request.getParameter("actionDebt3")) ) {



out.println("<h2> Customers in database:</h2>");
out.println("<table border='1'>");
out.println("<tr>");
out.println("<th>Customer name</th>");
out.println("<th>Customer Id</th>");
out.println("<th>total debt </th>");
out.println("<th>max debt</th>");
out.println("<th>min debt </th>");
out.println("<th>mean debt</th>");
out.println("<th> debt standard deviation </th>");
out.println("<th> debt skewness </th>");
out.println("</tr>");

for (int i = 0; i< counter.getCustomers().size(); i++) {

out.println("<tr>");
out.println("<td>" + counter.getCustomers().get(i).getCustomerName() + "</td>");
out.println("<td>" + counter.getCustomers().get(i).getCustomerID() + "</td>");
out.println("<td>" + counter.getCountDebt().getSum(i) + "</td>");
out.println("<td>" + counter.getCountDebt().getMax(i) + "</td>");
out.println("<td>" + counter.getCountDebt().getMin(i) + "</td>");
out.println("<td>" + counter.getCountDebt().getMean(i)+ "</td>");
out.println("<td>" + counter.getCountDebt().getStandardDeviation(i)+ "</td>");
out.println("<td>" + counter.getCountDebt().getSkewness(i) + "</td>");
}


out.println("</table>");

}




if ( "reward points".equals(request.getParameter("actionRewardPoints3")) ) {


out.println("<h2> Customers in database:</h2>");
out.println("<table border='1'>");
out.println("<tr>");
out.println("<th>Customer name</th>");
out.println("<th>Customer Id</th>");
out.println("<th>total reward points</th>");
out.println("<th>max reward points</th>");
out.println("<th>min reward points</th>");
out.println("<th>mean reward points</th>");
out.println("<th> standard deviation </th>");
out.println("<th> skewness </th>");
out.println("</tr>");

for (int i = 0; i< counter.getCustomers().size(); i++) {

out.println("<tr>");
out.println("<td>" + counter.getCustomers().get(i).getCustomerName() + "</td>");
out.println("<td>" + counter.getCustomers().get(i).getCustomerID() + "</td>");
out.println("<td>" + counter.getCountRewardPoints().getSum(i) + "</td>");
out.println("<td>" + counter.getCountRewardPoints().getMax(i) + "</td>");
out.println("<td>" + counter.getCountRewardPoints().getMin(i) + "</td>");
out.println("<td>" + counter.getCountRewardPoints().getMean(i)+ "</td>");
out.println("<td>" + counter.getCountRewardPoints().getStandardDeviation(i)+ "</td>");
out.println("<td>" + counter.getCountRewardPoints().getSkewness(i) + "</td>");
}

out.println("</table>");

}






// Print page
// Write HTML footer
out.println("</body></html>");
out.flush();
out.close();

} catch (Exception ex) {
System.out.println(ex);
throw new ServletException();

}
long stopTime = System.currentTimeMillis();
long doGetTime = stopTime - startTime;
System.out.println("Time to call doGet method in servlet: " +doGetTime+" ms");
}



private void printCountAction(PrintWriter out) {
out.println("<h2>Count customer reward points:</h2>");
out.println("<form>");
out.println("<input type='submit' name='actionAmountSpent3' value='amount spent'/>");
out.println("<input type='submit' name='actionCreditStore3' value='credit store'/>");
out.println("<input type='submit' name='actionDebt3' value='debt'/>");
out.println("<input type='submit' name='actionRewardPoints3' value='reward points'/>");
out.println("</form>");
}


}


Top
 Profile  
 
 Post subject: Re: Performance Problems
PostPosted: Thu May 19, 2011 6:14 pm 
Beginner
Beginner

Joined: Wed Jun 15, 2005 1:28 pm
Posts: 39
Location: United States
Add this annotation to your OneToMany association, and reply with your new performance numbers:

@BatchSize(size=100)


Top
 Profile  
 
 Post subject: Re: Performance Problems
PostPosted: Thu May 19, 2011 7:31 pm 
Hibernate Team
Hibernate Team

Joined: Fri Oct 05, 2007 4:47 pm
Posts: 2536
Location: Third rock from the Sun
Quote:
long startTimeGetCustomers = System.currentTimeMillis();
HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();

Did you start the SessionFactory before the timing?
The SessionFactory needs to be started only once, and lives until your application is closed. it's multithreaded.
Sessions are not multithreaded, but you're still supposed to reuse them consistently.

I'd add that there's no great value in trying to benchmark different ORMs unless you're an expert on each of them, as it doesn't look like you'd use them as an expert would do ;) No offence intended, it's just a fact that it's not an easy task to learn quickly, but it can still be very powerful to know.
Performance is really not measured in objects loaded per second, you'd consider longer running operations, possibly conflicting transactions and how clever it can be to avoid clashes, deadlocks, clever database indexes, distributed caches for horizontal scalability..
I saw some interesting benchmarks running around 5000 transactions per second, using an untuned MySQL on a laptop.. unlikely to be the number you're looking for, but you could take it as a rough estimate so that you know that if you're this far, there's something wrong in your test.
BTW, a single Hibernate query is too fast to be properly measured with System.currentTimeMillis() (unless it's a very complex query and your database can't handle it quickly); and looping it a 1000 times is pointless as that's not a real world scenario: it would be optimized in unrealistic ways.

_________________
Sanne
http://in.relation.to/


Top
 Profile  
 
 Post subject: Re: Performance Problems
PostPosted: Tue Aug 16, 2011 7:34 am 
Newbie

Joined: Thu Apr 28, 2011 6:40 am
Posts: 3
Hi
I m new to Hibernate and my goal is not to do serious benchmarking testing on Hibernate. It is just to get an idea of how fast you can group data and do calculations in application layer using an ORM tool as oppose to in database. My goal is not to get perfect performance results but reasonable once for Hibernate. In other words, I just want to know that I m not way off concerning performance. However I have now changed my approach and used Spring to configure Hibernate and I think I m getting good results. I have two classes: Customer and CustomerDetail (association one to many) and I m doing grouping and calculations on data in CustomerDetail objects. In the most resent test I have run I have following situation: 1000 Customers and 1000 CustomerDetails for each Customer. The result I m getting is:

Total time to do all calculations: 2810.0 ms
Time to get customers and customerdetails: 40558 ms

This means that I m getting 1000 0000 CustomerDetails in 40 sec that is not good right?
Calculations don’t have anything to do with Hibernate but I m wondering if I can do something to make fetching of objects go even faster. Is there any transaction scope setting or Hibernate configuration I can make that is good for the kind of task that I m performing.
Here are my classes and interfaces and DAO implementations:

package se.dsv.su.dao;

import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

import org.apache.commons.math.stat.descriptive.SummaryStatistics;
import org.springframework.beans.factory.annotation.Configurable;

@Entity
@Table(name = "Customer",schema = "Office")
public class Customer {
transient double stoptime=0;
transient double starttime=0;
transient static double totaltime;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "CustomerId")
private int customerId;

@OneToMany(mappedBy = "customerId")
private Set<CustomerDetail> customerDetails;

@ManyToOne
@JoinColumn(name = "DepartmentId", referencedColumnName = "DepartmentId", nullable = false)
private Department departmentId;

@Column(name = "customerEmailaddress", length = 255)
@NotNull
private String customerEmailaddress;

@Column(name = "customerAddress", length = 255)
@NotNull
private String customerAddress;

@Column(name = "customerName", length = 255)
@NotNull
private String customerName;

public Set<CustomerDetail> getCustomerDetails() {
return this.customerDetails;
}

public void setCustomerDetails(Set<CustomerDetail> customerDetails) {
this.customerDetails = customerDetails;
}

public Department getDepartmentId() {
return this.departmentId;
}

public void setDepartmentId(Department departmentId) {
this.departmentId = departmentId;
}

public String getCustomerEmailaddress() {
return this.customerEmailaddress;
}

public void setCustomerEmailaddress(String customerEmailaddress) {
this.customerEmailaddress = customerEmailaddress;
}

public String getCustomerAddress() {
return this.customerAddress;
}

public void setCustomerAddress(String customerAddress) {
this.customerAddress = customerAddress;
}

public String getCustomerName() {
return this.customerName;
}

public void setCustomerName(String customerName) {
this.customerName = customerName;
}

public int getCustomerId() {
return this.customerId;
}

public void setCustomerId(int id) {
this.customerId = id;
}


public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("CustomerAddress: ").append(getCustomerAddress()).append(", ");
sb.append("CustomerDetails: ").append(getCustomerDetails() == null ? "null" : getCustomerDetails().size()).append(", ");
sb.append("CustomerEmailaddress: ").append(getCustomerEmailaddress()).append(", ");
sb.append("CustomerId: ").append(getCustomerId()).append(", ");
sb.append("CustomerName: ").append(getCustomerName()).append(", ");
sb.append("DepartmentId: ").append(getDepartmentId());
return sb.toString();
}


public Double getTotalRewardPoints(){

starttime = (double)System.currentTimeMillis();
SummaryStatistics stats = new SummaryStatistics();
for(CustomerDetail cd : customerDetails){
stats.addValue(cd.getRewardPoints().doubleValue());

}
return stats.getSum();
}



public Double getMaxRewardPoints(){
SummaryStatistics stats = new SummaryStatistics();
for(CustomerDetail cd : customerDetails){
stats.addValue(cd.getRewardPoints().doubleValue());
}
return stats.getMax();

}
public Double getMinRewardPoints(){


SummaryStatistics stats = new SummaryStatistics();
for(CustomerDetail cd : customerDetails){
stats.addValue(cd.getRewardPoints().doubleValue());

}

return stats.getMin();

}

public Double getMeanRewardPoints(){


SummaryStatistics stats = new SummaryStatistics();
for(CustomerDetail cd : customerDetails){
stats.addValue(cd.getRewardPoints().doubleValue());

}
stoptime = (double)System.currentTimeMillis();
return stats.getMean();

}







public Double getTotalDebt(){
starttime = (double)System.currentTimeMillis();

SummaryStatistics stats = new SummaryStatistics();
for(CustomerDetail cd : customerDetails){
stats.addValue(cd.getDebt().doubleValue());

}

return stats.getSum();

}

public Double getMaxDebt(){


SummaryStatistics stats = new SummaryStatistics();
for(CustomerDetail cd : customerDetails){
stats.addValue(cd.getDebt().doubleValue());

}

return stats.getMax();

}
public Double getMinDebt(){


SummaryStatistics stats = new SummaryStatistics();
for(CustomerDetail cd : customerDetails){
stats.addValue(cd.getDebt().doubleValue());

}

return stats.getMin();

}

public Double getMeanDebt(){


SummaryStatistics stats = new SummaryStatistics();
for(CustomerDetail cd : customerDetails){
stats.addValue(cd.getDebt().doubleValue());

}
stoptime = (double)System.currentTimeMillis();
return stats.getMean();

}




public Double getTotalCreditStore(){
starttime = (double)System.currentTimeMillis();

SummaryStatistics stats = new SummaryStatistics();
for(CustomerDetail cd : customerDetails){
stats.addValue(cd.getCreditStore().doubleValue());

}

return stats.getSum();

}

public Double getMaxCreditStore(){


SummaryStatistics stats = new SummaryStatistics();
for(CustomerDetail cd : customerDetails){
stats.addValue(cd.getCreditStore().doubleValue());

}

return stats.getMax();

}
public Double getMinCreditStore(){


SummaryStatistics stats = new SummaryStatistics();
for(CustomerDetail cd : customerDetails){
stats.addValue(cd.getCreditStore().doubleValue());

}

return stats.getMin();

}

public Double getMeanCreditStore(){


SummaryStatistics stats = new SummaryStatistics();
for(CustomerDetail cd : customerDetails){
stats.addValue(cd.getCreditStore().doubleValue());

}
stoptime = (double)System.currentTimeMillis();
return stats.getMean();

}



public Double getTotalAmountSpent(){
starttime = (double)System.currentTimeMillis();

SummaryStatistics stats = new SummaryStatistics();
for(CustomerDetail cd : customerDetails){
stats.addValue(cd.getAmountSpent().doubleValue());

}

return stats.getSum();

}

public Double getMaxAmountSpent(){


SummaryStatistics stats = new SummaryStatistics();
for(CustomerDetail cd : customerDetails){
stats.addValue(cd.getAmountSpent().doubleValue());

}

return stats.getMax();

}
public Double getMinAmountSpent(){


SummaryStatistics stats = new SummaryStatistics();
for(CustomerDetail cd : customerDetails){
stats.addValue(cd.getCreditStore().doubleValue());

}

return stats.getMin();

}

public Double getMeanAmountSpent(){


SummaryStatistics stats = new SummaryStatistics();
for(CustomerDetail cd : customerDetails){
stats.addValue(cd.getAmountSpent().doubleValue());

}
stoptime = (double)System.currentTimeMillis();
return stats.getMean();

}

public Double getTimeToDoCalculations(){

totaltime+=(stoptime -starttime);

return (stoptime -starttime);
}

public static Double getTimeToDoAllCalculations(){

return totaltime;
}

public static void clearTimeToDoAllCalculations(){
totaltime = 0;

}

}
//Customer

package se.dsv.su.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

public interface ICustomerDAO {
public List<Customer> findAllCustomers();
}
//DAO interface

package se.dsv.su.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

@Repository
public class CustomerDAO implements ICustomerDAO {

@PersistenceContext
private EntityManager entityManager;

public List<Customer> findAllCustomers() {
return entityManager.createQuery("SELECT o FROM Customer o", Customer.class).getResultList();
}
}

//DAO


package se.dsv.su.dao;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.PersistenceContext;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;

@Entity
@Table(name = "CustomerDetail",schema = "Office")
public class CustomerDetail {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "CustomerDetailID")
private int customerDetailID;

@ManyToOne
@JoinColumn(name = "CustomerId", referencedColumnName = "CustomerId", nullable = false)
private Customer customerId;

@Column(name = "AmountSpent", precision = 9, scale = 2)
@NotNull
private BigDecimal amountSpent;

@Column(name = "CreditStore", precision = 10, scale = 4)
@NotNull
private BigDecimal creditStore;

@Column(name = "CustJoinDate")
@NotNull
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(style = "S-")
private Date custJoinDate;

@Column(name = "CustLogintime")
@NotNull
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(style = "S-")
private Date custLogintime;

@Column(name = "Debt", precision = 11, scale = 5)
@NotNull
private BigDecimal debt;

@Column(name = "RewardPoints", precision = 12, scale = 6)
@NotNull
private BigDecimal rewardPoints;

public int getCustomerDetailId() {
return this.customerDetailID;
}

public void setCustomerDetailId(int id) {
this.customerDetailID = id;
}

public Customer getCustomerId() {
return this.customerId;
}

public void setCustomerId(Customer customerId) {
this.customerId = customerId;
}

public BigDecimal getAmountSpent() {
return this.amountSpent;
}

public void setAmountSpent(BigDecimal amountSpent) {
this.amountSpent = amountSpent;
}

public BigDecimal getCreditStore() {
return this.creditStore;
}

public void setCreditStore(BigDecimal creditStore) {
this.creditStore = creditStore;
}

public Date getCustJoinDate() {
return this.custJoinDate;
}

public void setCustJoinDate(Date custJoinDate) {
this.custJoinDate = custJoinDate;
}

public Date getCustLogintime() {
return this.custLogintime;
}

public void setCustLogintime(Date custLogintime) {
this.custLogintime = custLogintime;
}

public BigDecimal getDebt() {
return this.debt;
}

public void setDebt(BigDecimal debt) {
this.debt = debt;
}

public BigDecimal getRewardPoints() {
return this.rewardPoints;
}

public void setRewardPoints(BigDecimal rewardPoints) {
this.rewardPoints = rewardPoints;
}

public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("AmountSpent: ").append(getAmountSpent()).append(", ");
sb.append("CreditStore: ").append(getCreditStore()).append(", ");
sb.append("CustJoinDate: ").append(getCustJoinDate()).append(", ");
sb.append("CustLogintime: ").append(getCustLogintime()).append(", ");
sb.append("CustomerDetailId: ").append(getCustomerDetailId()).append(", ");
sb.append("CustomerId: ").append(getCustomerId()).append(", ");
sb.append("Debt: ").append(getDebt()).append(", ");
sb.append("RewardPoints: ").append(getRewardPoints());
return sb.toString();
}
}
//CustomerDetail


Webb application is using MVC pattern, here is my Controller class where I have set timestamps

package se.dsv.su.web;




import java.util.List;
import java.util.Map;

import java.lang.System;




import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import se.dsv.su.dao.Customer;
import se.dsv.su.dao.ICustomerDAO;



@RequestMapping("/customers")
@Controller
public class CustomerController {

@Autowired
private ICustomerDAO customerDAO;

private long timetogetcustomers;

public static long timetogetcustomerobjects;



@RequestMapping(method = RequestMethod.GET)
public String customer(Model uiModel) {
/*Affärslogik*/
Long getcustomersstart = System.currentTimeMillis();
List<Customer> customers = customerDAO.findAllCustomers();
Long getcustomersstop = System.currentTimeMillis();
timetogetcustomerobjects = 0;
timetogetcustomers = (getcustomersstop - getcustomersstart);
timetogetcustomerobjects = timetogetcustomers;
uiModel.addAttribute("timetogetcustomers", timetogetcustomers);
uiModel.addAttribute("customers", customers);

return "customers";
}





@RequestMapping(value ="/rewardpoints" , method = RequestMethod.GET)
public String rewardpoints(Model uiModel) {
Long getcustomersstart = System.currentTimeMillis();
List<Customer> customers = customerDAO.findAllCustomers();
System.out.println(customers);
Long getcustomersstop = System.currentTimeMillis();
timetogetcustomerobjects = 0;
timetogetcustomers = (getcustomersstop - getcustomersstart);
timetogetcustomerobjects = timetogetcustomers;
uiModel.addAttribute("timetogetcustomers", timetogetcustomers);
uiModel.addAttribute("customers", customers);

return "showrewardpoints";
}

@RequestMapping(value ="/creditstore" , method = RequestMethod.GET)
public String creditstore(Model uiModel) {

Long getcustomersstart = System.currentTimeMillis();
List<Customer> customers = customerDAO.findAllCustomers();
Long getcustomersstop = System.currentTimeMillis();
timetogetcustomerobjects = 0;
timetogetcustomers = (getcustomersstop - getcustomersstart);
timetogetcustomerobjects = timetogetcustomers;
uiModel.addAttribute("timetogetcustomers", timetogetcustomers);
uiModel.addAttribute("customers", customers);
return "showcreditstore";
}

@RequestMapping(value ="/debt" , method = RequestMethod.GET)
public String debt(Model uiModel) {
Long getcustomersstart = System.currentTimeMillis();
List<Customer> customers = customerDAO.findAllCustomers();
Long getcustomersstop = System.currentTimeMillis();
timetogetcustomerobjects = 0;
timetogetcustomers = (getcustomersstop - getcustomersstart);
timetogetcustomerobjects = timetogetcustomers;
uiModel.addAttribute("timetogetcustomers", timetogetcustomers);
uiModel.addAttribute("customers", customers);
return "showdebt";
}

@RequestMapping(value ="/amountspent" , method = RequestMethod.GET)
public String amountspent(Model uiModel) {
Long getcustomersstart = System.currentTimeMillis();
List<Customer> customers = customerDAO.findAllCustomers();
Long getcustomersstop = System.currentTimeMillis();
timetogetcustomerobjects = 0;
timetogetcustomers = (getcustomersstop - getcustomersstart);
timetogetcustomerobjects = timetogetcustomers;
uiModel.addAttribute("timetogetcustomers", timetogetcustomers);
uiModel.addAttribute("customers", customers);
return "showamountspent";
}


@RequestMapping(value ="/clearlists" , method = RequestMethod.POST)
public String clearLists(Model uiModel) {
TimerUtil.clearLists();
System.out.println("listorna har rensats");

return "chart";
}



@RequestMapping(value ="/showchart" , method = RequestMethod.POST)
public String showchart(Model uiModel) {
Map <Number,String> timetodocalculationsmap = TimerUtil.getTimestodocalculations();
Map <Number,String> timetogetobjectsmap = TimerUtil.getTimestogetobjects();
Map <Number,String> totaltimemap = TimerUtil.getTotaltime();
Map <Number, String> timestogetJDBCresultset = TimerUtil.getTimestogetJDBCresultset();
uiModel.addAttribute("timetodocalculationsmap", timetodocalculationsmap);
uiModel.addAttribute("timetogetobjectsmap", timetogetobjectsmap);
uiModel.addAttribute("totaltimemap", totaltimemap);
uiModel.addAttribute("timetogetJDBCresultsetmap", timestogetJDBCresultset);
System.out.println("Mapparna läggs in");

return "chart";
}








}
Dont worry I m showing timeing results only once on each JSP

Here is My Hibernate Spring configured XML file:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/ ... ce_2_0.xsd">
<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect"/>
<!-- value="create" to build a new database on each run; value="update" to modify an existing database; value="create-drop" means the same as "create" but also drops tables when Hibernate closes; value="validate" makes no changes to the database -->
<property name="hibernate.hbm2ddl.auto" value="validate"/>
<property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.DefaultNamingStrategy"/>
<property name="hibernate.connection.charSet" value="UTF-8"/>
<!-- Uncomment the following two properties for JBoss only -->
<!-- property name="hibernate.validator.apply_to_ddl" value="false" /-->
<!-- property name="hibernate.validator.autoregister_listeners" value="false" /-->
</properties>
</persistence-unit>
</persistence>

And here is my spring ApplicationContext XML file where I m configuring datasource. I m guessing that EntetyManager is wrapper class for Hibernate Session class and EntityManagerFactory is like Hibernates SessionFactory class. Don’t worry about JdbcTemplate bean I m using it for something else.


<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/a ... op-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/b ... ns-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/c ... xt-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/j ... ee-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/t ... tx-3.0.xsd">
<!--
This will automatically locate any and all property files you have
within your classpath, provided they fall under the META-INF/spring
directory. The located property files are parsed and their values can
then be used within application context files in the form of
${propertyKey}.
-->
<context:property-placeholder location="classpath*:META-INF/spring/*.properties"/>
<!--
Turn on AspectJ @Configurable support. As a result, any time you
instantiate an object, Spring will attempt to perform dependency
injection on that object. This occurs for instantiation via the "new"
keyword, as well as via reflection. This is possible because AspectJ
is used to "weave" Roo-based applications at compile time. In effect
this feature allows dependency injection of any object at all in your
system, which is a very useful feature (without @Configurable you'd
only be able to dependency inject objects acquired from Spring or
subsequently presented to a specific Spring dependency injection
method). Roo applications use this useful feature in a number of
areas, such as @PersistenceContext injection into entities.
-->
<context:spring-configured/>
<!--
This declaration will cause Spring to locate every @Component,
@Repository and @Service in your application. In practical terms this
allows you to write a POJO and then simply annotate the new POJO as an
@Service and Spring will automatically detect, instantiate and
dependency inject your service at startup time. Importantly, you can
then also have your new service injected into any other class that
requires it simply by declaring a field for your service inside the
relying class and Spring will inject it. Note that two exclude filters
are declared. The first ensures that Spring doesn't spend time
introspecting Roo-specific ITD aspects. The second ensures Roo doesn't
instantiate your @Controller classes, as these should be instantiated
by a web tier application context. Refer to web.xml for more details
about the web tier application context setup services.

Furthermore, this turns on @Autowired, @PostConstruct etc support. These
annotations allow you to use common Spring and Java Enterprise Edition
annotations in your classes without needing to do any special configuration.
The most commonly used annotation is @Autowired, which instructs Spring to
dependency inject an object into your class.
-->
<context:component-scan base-package="se.dsv" />

<bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="dataSource">
<property name="driverClassName" value="${database.driverClassName}"/>
<property name="url" value="${database.url}"/>
<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}"/>
<property name="testOnBorrow" value="true"/>
<property name="testOnReturn" value="true"/>
<property name="testWhileIdle" value="true"/>
<property name="timeBetweenEvictionRunsMillis" value="1800000"/>
<property name="numTestsPerEvictionRun" value="3"/>
<property name="minEvictableIdleTimeMillis" value="1800000"/>
</bean>

<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>

<bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>


<tx:annotation-driven transaction-manager="transactionManager"/>

<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
<property name="persistenceUnitName" value="persistenceUnit"/>
<property name="dataSource" ref="dataSource"/>
</bean>




</beans>

Thank you for your help


Last edited by Dejan Marlovic on Sat Sep 10, 2011 9:45 am, edited 1 time in total.

Top
 Profile  
 
 Post subject: Re: Performance Problems
PostPosted: Tue Aug 16, 2011 10:44 am 
Newbie

Joined: Mon Aug 16, 2010 12:32 pm
Posts: 12
Hi,

We seem to have the same problem my thread is here viewtopic.php?f=1&t=1012233


Top
 Profile  
 
 Post subject: Re: Performance Problems
PostPosted: Tue Aug 16, 2011 11:12 am 
Hibernate Team
Hibernate Team

Joined: Fri Oct 05, 2007 4:47 pm
Posts: 2536
Location: Third rock from the Sun
Quote:
Calculations don’t have anything to do with Hibernate but I m wondering if I can do something to make fetching of objects go even faster.

most performance problems are related to the number of round-trips to the database, so you can either fetch needed data in bulk (queries for multiple entities instead of loading one by one) or enable a second level cache. Second level cache is my favourite option as it's totally transparent to the business logic, but is not safe if other processes change the data in the database.

_________________
Sanne
http://in.relation.to/


Top
 Profile  
 
 Post subject: Re: Performance Problems
PostPosted: Sat Sep 10, 2011 11:21 am 
Newbie

Joined: Thu Apr 28, 2011 6:40 am
Posts: 3
Quote:
most performance problems are related to the number of round-trips to the database, so you can either fetch needed data in bulk (queries for multiple entities instead of loading one by one)


Hi

Can you show me an example of how I can I do that in my example please? I think that right now it is fetching CustomerDetail objects for each Customer when it needs the data for calculations. This I think is because I use fetch type LAZY.


so here is where in the code it is fetching CustomerDetails objects when I use LAZY

SummaryStatistics stats = new SummaryStatistics();

for(CustomerDetail cd : customerDetails){
stats.addValue(cd.getCreditStore().doubleValue());

}

return stats.getMean();

}

As you can see I m adding, for example creditstore value of each CustomerDetail object of one particular Customer to the SummaryStatistics object that then returns for example mean value of all creditstore values of all CustomerDetail objects associated to that Customer.

the result I get is:
Total time to do all calculations and get customerdetail objects: 3598.0 ms (3 sec)
Time to get Customer objects: 16 ms


if I change the fetch type to EAGER it will swap and fetch CustomerDetail objects when it gets Customers and I will get different time when it gets Customer objects

Total time to do all calculations: 228.0 ms
Time to get Customer and CustomerDetail objects: 3956 ms ( now it takes 3 sec to get Customer and CustomerDetail objects)

so it does not seam to matter if I fetch all customerdetails when I get Customer objects or if this is done when each calculation is performed.

right now I have 100 Customers and 1000 CustomerDetails objects for each Customer

if I do the same when I have 1000 Customer and 1000 CustomerDetails objects for each Customer it takes 30 sec to show the result set. Is this expected`? After all I m fetching 1000000 CustomerDetails objects. :) By the way I m using only one query to fetch my Customer objects as you can see bellow or in my code.


public interface ICustomerDAO {
public List<Customer> findAllCustomers();
}
//DAO interface


public class CustomerDAO implements ICustomerDAO {
@PersistenceContext
private EntityManager entityManager;

public List<Customer> findAllCustomers() {
return entityManager.createQuery("SELECT o FROM Customer o", Customer.class).getResultList();
}//class implementing the interface

and then in my Controller I call the method:

List<Customer> customers = customerDAO.findAllCustomers();

and get all the Customer and CustomerDetails objects if I use fetchtype eager right?


Also how do I get Hibernate/Java to release RAM memory when I want because this seems to have huge inpact on performance .

P.S I m now using System.nanoTime() to measure time to fetch objects

Best regards

Thank you for your help


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 7 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.