Exemplo de pesistência com hibernate conectando com SqlServer
Jares necessários hibernate3.jar
hibernate-annotations.jar
hibernate-commons-annotations.jar
SessionFactory
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateSessionFactory {
private static Logger log = Logger.getLogger(HibernateSessionFactory.class);
private static SessionFactory sessionFactory;
static {
rebuildSessionFactory();
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void setSessionFactory(SessionFactory sessionFactory) {
HibernateSessionFactory.sessionFactory = sessionFactory;
}
private HibernateSessionFactory() {
}
public static Session getSession() {
Session session = null;
try {
session = sessionFactory.getCurrentSession();
} catch (Exception e) {
log.info("Abrindo nova sessão: "+ e.getMessage());
session = sessionFactory.openSession();
}
if (session == null || !session.isOpen()) {
session = sessionFactory.openSession();
}
return session;
}
public static void rebuildSessionFactory() {
try {
PoolProperties poolProperties = new PoolProperties("MyProjetct");
poolProperties.read();
AnnotationConfiguration configuration = (AnnotationConfiguration) new AnnotationConfiguration()
.configure("hibernate.cfg.xml");
sessionFactory = configuration
.setProperty("hibernate.connection.url","jdbc:jtds:sqlserver://localhost:1433/MyProject")
.setProperty("hibernate.connection.username", "user")
.setProperty("hibernate.connection.password", "password")
.setProperty("hibernate.dialect", "org.hibernate.dialect.SQLServerDialect")
.setProperty("hibernate.connection.driver_class","net.sourceforge.jtds.jdbc.Driver")
.setProperty("hibernate.connection.pool_size", "10")
.setProperty("hibernate.hbm2ddl.auto", "validate")
.setProperty("hibernate.cache.provider_class",
"org.hibernate.cache.EhCacheProvider")
//.setProperty("hibernate.show_sql", "true")
//.setProperty("hibernate.hbm2ddl.auto", "update")
// .setProperty("hibernate.archive.autodetection","class, hbm")
.buildSessionFactory();
} catch (Exception e) {
log.error("Erro ao ler as propriedades do hibernate.cfg.xml", e);
}
}
}
hibernate config com o mapeamento de classes
HIBERNATE.CFG.XML
hibernate-configuration>
<session-factory><property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name="hibernate.connection.provider_class">com.jolbox.bonecp.provider.BoneCPConnectionProvider</property>
<property name="bonecp.idleMaxAgeInMinutes">4</property> <property name="bonecp.idleConnectionTestPeriodInMinutes">1</property>
<property name="bonecp.partitionCount">3</property> <property name="bonecp.acquireIncrement">5</property>
<property name="bonecp.maxConnectionsPerPartition">10</property>
<property name="bonecp.minConnectionsPerPartition">1</property>
<property name="bonecp.statementsCacheSize">50</property>
<property name="bonecp.releaseHelperThreads">3</property>
<property name="current_session_context_class">thread</property>
<mapping class="com..model.Logradouro"></session-factory>
</hibernate-configuration>
Xml do pool de conexões
CONNECTIONPOOL.XML
<databaseconnectionpool>
<default>
<driver>net.sourceforge.jtds.jdbc.Driver</driver>
<maxconnections>15</maxconnections>
<initconnections>8</initconnections>
<timeoutinterval>360</timeoutinterval>
<validationquery>SELECT RTRIM('')</validationquery>
<checkinterval>30</checkinterval>
</default>
<pool id="MyProjetct">
<conexao>
<url>jdbc:jtds:sqlserver://LOCALHOST:1433/MyProjetct</url>
<user>desenvolvimento</user>
<password>==gdD6bpWZsUL8DHGGArGEB5</password>
<maxconnections>5</maxconnections>
<initconnections>2</initconnections>
<timeoutinterval>1440</timeoutinterval>
<validationquery>SELECT RTRIM('MarketData')</validationquery>
</conexao>
</pool>
</databaseconnectionpool>
Aqui utilzaremos um filtro para gerenciar a abertura e fechamento de conexões
SESSIONFILTER
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import com.mdsb.gpadrao.exception.DataAccessLayerException;
public class HibernateSessionFilter implements Filter {
private static Logger log = Logger.getLogger(HibernateSessionFilter.class);
public void init(FilterConfig arg0) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws ServletException {
Session session = HibernateSessionFactory.getSession();
try {
if (session.isOpen()) {
session.beginTransaction();
try {
chain.doFilter(request, response);
} catch (Exception e) {
log.error(e.getMessage(), e);
session.getTransaction().rollback();
throw new ServletException(e);
}
if (request.getAttribute("validationError") != null
&& ((Boolean) request.getAttribute("validationError"))) {
session.getTransaction().rollback();
} else {
session.flush();
session.getTransaction().commit();
}
} else {
log.debug("FALHA - A sessão do hibernate não está aberta.");
((HttpServletRequest) request).getRequestDispatcher(
"/login.jsp").forward(request, response);
}
} catch (DataAccessLayerException e) {
log.error(e.getMessage(), e);
session.getTransaction().rollback();
throw new ServletException(e);
} catch (Exception e) {
log.error(e.getMessage(), e);
session.getTransaction().rollback();
throw new ServletException(e);
} finally {
if(session.isOpen()){
session.close();
}
session =null;
}
}
public void destroy() {
}
}
executando oc comandos salvar e remover
AbstractDAOImpl
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import com.mdsb.framework.taglibs.filter.integration.DAOException;
import com.mdsb.gpadrao.hibernate.HibernateSessionFactory;
public abstract class AbstractDAOImpl {
private static Logger logger = Logger.getLogger(Thread.currentThread().getClass().getName());
private Session session;
public AbstractDAOImpl() {
this.session = HibernateSessionFactory.getSession();
}
protected org.hibernate.Session getHibernateSession() {
if(!session.isOpen()){
session = HibernateSessionFactory.getSession();
}
return session;
}
public Object salvar(Object o) throws DAOException{
try {
Session session = getHibernateSession();
Object obj = session.merge(o);
return obj;
}catch(HibernateException e) {
logger.error("[AbstractDAOImpl.salvar] - EXCEPTION ", e);
throw new DAOException(e);
}
}
@SuppressWarnings("finally")
public boolean remover(Object o) throws DAOException{
boolean result = false;
try {
getHibernateSession().delete(o);
result = true;
}catch(HibernateException e) {
logger.error("[AbstractDAOImpl.remover] - EXCEPTION ",e);
throw new DAOException(e);
} finally {
return result;
}
}
public Contato obtemContatoPorId(Integer idContato) {
Criteria c = getHibernateSession().createCriteria(Contato.class);
c.add(Restrictions.eq("idContato", idContato));
c.setMaxResults(1);
return (Contato) c.uniqueResult();
}
private List findHistoricoByDate(FiltroPesquisa filtro) {
StringBuilder sb = new StringBuilder();
sb.append(" SELECT h.idHistoricoContato \n");
sb.append(" FROM HistoricoContatoEmpresa h \n");
sb.append(" inner join contato c on c.idContato = h.idContato \n");
sb.append(" inner join ( \n");
sb.append(" select distinct he.idContato, max(he.dataAtualizacao) as ultimaData \n");
sb.append(" from HistoricoContatoEmpresa he \n");
sb.append(" group by he.idContato \n");
sb.append(" ) ultimoHistorico on (ultimoHistorico.idContato = h.idContato and \n");
sb.append(" ultimoHistorico.ultimaData = h.dataAtualizacao ) \n");
sb.append(" where 1=1 \n");
if(filtro.getDataInicio() != null){
sb.append("and h.dataAtualizacao >= isnull(?, h.dataAtualizacao)");
}
if(filtro.getDataFim() != null){
sb.append(" and h.dataAtualizacao < ? \n");
}
Query q = getHibernateSession().createSQLQuery(sb.toString());
int idx = -1;
if(filtro.getDataInicio() != null){
try{
q.setDate(++idx, filtro.getDataInicio());
}catch(Exception e){}
}
if(filtro.getDataFim() != null){
try {
q.setDate(++idx, DateUtil.alteraData(filtro.getDataFim(), 1, Calendar.DAY_OF_MONTH));
}
catch (Exception e){}
}
return q.list();
}
public void closeSession(){
System.out.println("fechando conexão");
if(this.session!=null){
this.session.close();
}
}
}