Amigos, estou comecando a mexer tanto com Mongodb como com VRaptor e tenho uma duvida, como eu faco para que nao seja aberto varias conexoes a medida que vou recebendo usuario no meu site??
eu fiz um singleton para a conexao
package com.noname.dao;
import java.util.List;
import br.com.caelum.vraptor.ioc.Component;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.query.Query;
import com.mongodb.Mongo;
@Component
public class ConexaoDao {
private static ConexaoDao myInstance = null;
private Mongo mongo = null;
private static Datastore datastore = null;
private ConexaoDao() throws Exception {
mongo = new Mongo();
datastore = new Morphia().createDatastore(mongo, "noname");
datastore.ensureIndexes();
}
public synchronized static ConexaoDao getInstance() throws Exception{
if(myInstance == null){
myInstance = new ConexaoDao();
}
return myInstance;
}
public Datastore getDatastore() throws Exception{
if(datastore == null){
getInstance();
}
return datastore;
}
public Object save(Object object){
datastore.save(object);
return object;
}
}
e na minha classe de controler ficou assim
package com.noname.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import static br.com.caelum.vraptor.view.Results.json;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import com.google.code.morphia.Datastore;
import com.noname.dao.ConexaoDao;
import com.noname.entity.Product;
@Resource
public class ProductController {
@Autowired
private Result result;
private Datastore ds;
private void abreConexao() throws Exception{
ds = ConexaoDao.getInstance().getDatastore();
}
@Get
@Path("/product/getProduct")
public void getProduct(String nmProduct) throws Exception{
abreConexao();
List<Product> productList = ds.createQuery(Product.class).field("nmProduct").containsIgnoreCase(nmProduct).asList();
result.use(json()).from(productList, "productList").serialize();
}
@Get
@Path("/product/addProduct")
public void addProduct(String nmProduct) throws Exception{
abreConexao();
Product product = null;
if(nmProduct == null){
throw new Exception("Product name cannot be null");
}
nmProduct = nmProduct.toUpperCase();
product = getProductByName(nmProduct);
if(product == null){
product = new Product();
product.setNmProduct(nmProduct);
ConexaoDao.getInstance().save(product);
}
result.use(json()).from(product, "product").serialize();
}
private Product getProductByName(String nmProduct){
return ds.createQuery(Product.class).field("nmProduct").equal(nmProduct).get();
}
}
Esta correto?? tenho que implementar alguma coisa diferente disso??