Galera, estou fazendo uma aplicação simples com uso de proxy para testar se com ou sem proxy o carregamento de uma classe funciona mais rápido.
Tenho duas classes Cliente e Pedidocliente, a primary key idcliente, está ligada com pedidocliente. ligação um para muitos.
Estou fazendo alguns testes inserindo um Pedidocliente carregando o cliente através de uma hora com o método load (com proxy) e outra com get (acesso a banco), para ver
em qual deles a inserção é mais rápida, mas não estou obtendo resultados satisfatórios, pois o tempo para inserir, vários objetos no banco, é praticamente o mesmo, com ou sem proxy, alguém tem alguma idéia para ajudar???
Esta é minha classe cliente mapeada com annotations
@Entity
@Table(name = "cliente")
@org.hibernate.annotations.Proxy(lazy=true)
@NamedQueries( {
@NamedQuery(name = "Cliente.findByIdcliente", query = "SELECT c FROM Cliente c WHERE c.idcliente = :idcliente"),
@NamedQuery(name = "Cliente.findByNome", query = "SELECT c FROM Cliente c WHERE c.nome = :nome"),
@NamedQuery(name = "Cliente.findByIdade", query = "SELECT c FROM Cliente c WHERE c.idade = :idade"),
@NamedQuery(name = "Cliente.findByCidade", query = "SELECT c FROM Cliente c WHERE c.cidade = :cidade")
})
public class Cliente implements Serializable {
@Id
@Column(name = "idcliente", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer idcliente;
[/code]
Esta é minha classe Pedidocliente
[code]@Entity
@Table(name = "pedidocliente")
@NamedQueries( {
@NamedQuery(name = "Pedidocliente.findByIdpedido", query = "SELECT p FROM Pedidocliente p WHERE p.idpedido = :idpedido"),
@NamedQuery(name = "Pedidocliente.findByValor", query = "SELECT p FROM Pedidocliente p WHERE p.valor = :valor"),
@NamedQuery(name = "Pedidocliente.findByData", query = "SELECT p FROM Pedidocliente p WHERE p.data = :data")
})
public class Pedidocliente implements Serializable {
@Id
@Column(name = "idpedido", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer idpedido;[/code]
Este é minha classe genérica do hibernate para operações com o banco.
/*
* HibenrateUtil.java
*
* Created on 2 de Abril de 2008, 23:40
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package banco;
import java.io.Serializable;
import model.Cliente;
import model.Pedidocliente;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
/**
*
* @author Berdam
*/
//Classe que inicializar a SessionFactory, que é a fábrica de Session,
//deve ser usada para startar a aplicação e somente quando finaliza.
public class HibernateUtil {
private static SessionFactory sessionfactory;
private Session session;
private Transaction tx;
static {
try {
AnnotationConfiguration cfg = new AnnotationConfiguration();
cfg.addAnnotatedClass(Cliente.class);
cfg.addAnnotatedClass(Pedidocliente.class);
sessionfactory = new AnnotationConfiguration().configure("banco/hibernate.cfg.xml").buildSessionFactory();
} catch (Throwable t){
throw new ExceptionInInitializerError(t);
}
}
public static SessionFactory getSessionFactory(){
return sessionfactory;
}
public static void shutdown(){
getSessionFactory().close();
}
public void AbreSession(){
try {
//abre uma unidade de trabalho, a partir da SessionFactory que é global
session = HibernateUtil.getSessionFactory().openSession();
tx = session.beginTransaction();
} catch (Exception e) {
System.err.println("Erro abrindo Session "+e.getMessage());
}
}
public void FechaSession(){
try {
tx.commit();
session.close();
} catch (Exception e) {
tx.rollback();
System.err.println("Erro fechando Session "+e.getMessage());
}
}
public boolean Salva(Object obj){
boolean inseriu = false;
AbreSession();
try {
session.save(obj);
inseriu = true;
} catch (Exception e) {
System.out.println("Erro salvando "+e.getMessage());
inseriu = false;
}
FechaSession();
return inseriu;
}
public Object load(Class classe, Serializable id) {
Object obj = null;
AbreSession();
try {
obj = session.load(classe, id);
} catch (Exception e) {
// trap ObjectNotFoundException and return null instead. this is
// the expected behavior for most methods that use this method
System.out.println(e.getMessage());
obj = null;
}
FechaSession();
return obj;
}
public Object get(Class classe, Serializable id) {
Object obj = null;
AbreSession();
try {
obj = session.get(classe, id);
} catch (Exception e) {
// trap ObjectNotFoundException and return null instead. this is
// the expected behavior for most methods that use this method
System.out.println(e.getMessage());
obj = null;
}
FechaSession();
return obj;
}
}
Minha classe Main
[code] public static void main(String[] args) throws IOException {
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Digite 1 ou 2 para com ou sem proxy");
String texto = buf.readLine();
//com proxy
if (texto.equals("1")) {
HibernateUtil.getSessionFactory();
HibernateUtil hb = new HibernateUtil();
Pedidocliente pedidocliente = new Pedidocliente();
Timestamp data = new Timestamp(System.currentTimeMillis());
long time = System.currentTimeMillis();
System.out.println("Com proxy");
for (int i = 0; i <= 4000; i++) {
Cliente cliente = (Cliente) hb.load(Cliente.class,1);
// cliente.getIdcliente();
//cliente.getNome();
pedidocliente.setValor(100.5);
pedidocliente.setIdcliente(cliente);
pedidocliente.setData(data);
hb.Salva(pedidocliente);
}
System.out.println("Com proxy demorou");
System.out.println(time = System.currentTimeMillis() - time);
HibernateUtil.shutdown();
}
//sem proxy
if (texto.equals("2")){
HibernateUtil.getSessionFactory();
HibernateUtil hb = new HibernateUtil();
Pedidocliente pedidocliente = new Pedidocliente();
Timestamp data = new Timestamp(System.currentTimeMillis());
long time = System.currentTimeMillis();
System.out.println("Sem proxy");
for (int i = 0; i <= 4000; i++) {
Cliente cliente = (Cliente) hb.get(Cliente.class,1);
//cliente.getIdcliente();
//2cliente.getNome();
pedidocliente.setValor(100.5);
pedidocliente.setIdcliente(cliente);
pedidocliente.setData(data);
hb.Salva(pedidocliente);
}
System.out.println("Sem proxy demorou");
System.out.println(time = System.currentTimeMillis() - time);
HibernateUtil.shutdown();
}
}
}