query by hibernate

This simple example is show the query result of Hibernate,the database is sqlservel2000,ok,first,create a web project in eclipse,then click the right on this project to add hibernate capabilities in MyEclipse.so it will generate a hibnerate.cfg.xml and HibernateSessionFactory.java

Hibernate.cfg.xml:

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

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

	<session-factory>
		<property name="connection.username">sa</property>
		<property name="connection.url">
			jdbc:microsoft:sqlserver://localhost:7788;DatabaseName=SVSE
		</property>
		<property name="dialect">
			org.hibernate.dialect.SQLServerDialect
		</property>
		<property name="myeclipse.connection.profile">
			SqlServer
		</property>
		<property name="connection.password">admin</property>
		<property name="connection.driver_class">
			com.microsoft.jdbc.sqlserver.SQLServerDriver
		</property>
		<mapping resource="com/sotomi/view/Gameinfo.hbm.xml" />
		<mapping resource="com/sotomi/view/Downloadlist.hbm.xml" />
		<mapping resource="com/sotomi/view/Gametype.hbm.xml" />
		<mapping resource="com/sotomi/view/Users.hbm.xml" />

	</session-factory>

</hibernate-configuration>

 

HibernateSessionFactory.java:

package com;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
 * Configures and provides access to Hibernate sessions, tied to the
 * current thread of execution.  Follows the Thread Local Session
 * pattern, see {@link http://hibernate.org/42.html }.
 */
public class HibernateSessionFactory {

    /** 
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses  
     * #resourceAsStream style lookup for its configuration file. 
     * The default classpath location of the hibernate config file is 
     * in the default package. Use #setConfigFile() to update 
     * the location of the configuration file for the current session.   
     */
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
	private static final ThreadLocal threadLocal = new ThreadLocal();
    private  static Configuration configuration = new Configuration();    
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

	static {
    	try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err
					.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
    }
    private HibernateSessionFactory() {
    }
	
	/**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();

		if (session == null || !session.isOpen()) {
			if (sessionFactory == null) {
				rebuildSessionFactory();
			}
			session = (sessionFactory != null) ? sessionFactory.openSession()
					: null;
			threadLocal.set(session);
		}

        return session;
    }

	/**
     *  Rebuild hibernate session factory
     *
     */
	public static void rebuildSessionFactory() {
		try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err
					.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}

	/**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

	/**
     *  return session factory
     *
     */
	public static org.hibernate.SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
     *  return session factory
     *
     *	session factory will be rebuilded in the next call
     */
	public static void setConfigFile(String configFile) {
		HibernateSessionFactory.configFile = configFile;
		sessionFactory = null;
	}

	/**
     *  return hibernate configuration
     *
     */
	public static Configuration getConfiguration() {
		return configuration;
	}

}

 

then create a Dao class for querying:

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.HibernateSessionFactory;

public class HibernateDao extends HibernateDaoSupport{

	public List findSql(String hql){
		List list = new ArrayList();
		try { 
			Session session = HibernateSessionFactory.getSession();
			list = session.createSQLQuery(hql).list();
			session.close();
			System.out.println("list size is "+list.size());
		} catch (DataAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}
}

 Then config the struts-config.xml to forward to the showing jsp:

<%@ page language="java" import="java.util.*,com.sotomi.view.*" pageEncoding="gbk"%>
<%
List list = (List)request.getAttribute("List");

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  </head>
  
  <body>
    <%
      if(list.size()>0){ 
      for(int i=0;i<list.size();i++){
      Object[] obj = (Object[])list.get(i);
    %>
    <tr><%=obj[2]%></tr>
    <%  
      }}
    %>
    
  </body>
</html>

 

then output is : 1800 960 3200 26 2400 32

你可能感兴趣的:(DAO,Hibernate,xml,MyEclipse,Microsoft)