本文共 13230 字,大约阅读时间需要 44 分钟。
在上一篇,我们讨论了如何配置Tomcat 5.5的Context.xml文件,它能够建立Tomcat 5.5中的只读JNDI。通过这个JNDI,可以为你的Tomcat servlet提供数据源—无论在你的servlet中使用的是Hibernate还是原始JDBC。而且在上一篇中,相应的示例servlet使用了原 始JDBC存取我们的MySQL数据库。
xmlns=" " xmlns:xsi=" " xsi:schemaLocation=" "> tomcatJndi.HibernateAppListener Retrieval tomcatJndi.Retrieval RetrieveViaHibernate tomcatJndi.RetrieveViaHibernate InsertViaHibernate tomcatJndi.InsertViaHibernate Retrieval /Retrieval RetrieveViaHibernate /RetrieveViaHibernate InsertViaHibernate /InsertViaHibernate |
package tomcatJndi; import javax.servlet.ServletContextListener; import javax.servlet.ServletContextEvent; import org.apache.log4j.Logger; import org.hibernate.Session; public class HibernateAppListener implements ServletContextListener { /*应用程序启动事件*/ public void contextInitialized(ServletContextEvent ce) { Logger loggerConnect = Logger.getLogger("Connect"); try { loggerConnect.debug("In HibernateAppListener.contextInitialized"); Class.forName("tomcatJndi.HibernateUtil").newInstance(); loggerConnect.debug("In HibernateAppListener, Class.forName for tomcatJndi.HibernateUtil successful"); } catch (Exception e) { loggerConnect.debug("In HibernateAppListener, Class.forName for tomcatJndi.HibernateUtil throws Exception"); } } /*应用程序退出事件*/ public void contextDestroyed(ServletContextEvent ce) {} } |
package tomcatJndi; import org.hibernate.*; import org.hibernate.cfg.*; import org.apache.log4j.Logger; public class HibernateUtil { private static final SessionFactory sessionFactory; static { try { Logger loggerRoot = Logger.getRootLogger(); Logger loggerConnect = Logger.getLogger("Connect"); loggerRoot.debug("In HibernateUtil try-clause"); loggerRoot.error("In HibernateUtil try-clause"); loggerConnect.debug("In HibernateUtil try-clause via loggerConnect DEBUG*****"); //从hibernate.cfg.xml中创建SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } } |
Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); ...[retrieve desired results via a Hibernate query] session.getTransaction().commit(); //自动关闭会话 |
Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); Car bigSUV = new Car(); bigSUV.setManufacturer("Ford"); bigSUV.setModel("Expedition"); bigSUV.setYear(2005); Driver jill = getDriverByName("Jill"); addCarToDriver(jill, bigSUV); session.getTransaction().commit(); //自动关闭会话 |
"-//Hibernate/Hibernate Configuration DTD 3.0//EN" " "> java:comp/env/jdbc/Sampdb true org.hibernate.dialect.MySQLDialect thread org.hibernate.cache.NoCacheProvider |
com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/sampdb root sammy11 |
sessionFactory =new Configuration().configure().buildSessionFactory(); |
"-//Hibernate/Hibernate Mapping DTD 3.0//EN" " "> |
package tomcatJndi; public class Car { private Long car_id; private String manufacturer; private String model; private int year; public Car() {} public Long getId() { return car_id; } private void setId(Long car_id){//注意,private类型的可见范围 this.car_id = car_id; } public String getManufacturer() { return manufacturer; } public void setManufacturer(String manufacturer) { this.manufacturer = manufacturer; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } } |
create table car( car_id bigint(20) PRIMARY KEY not null auto_increment, manufacturer varchar(40), model varchar(40), year int, fk_driver_id bigint(20), FOREIGN KEY (fk_driver_id) REFERENCES driver (driver_id) ) |
package tomcatJndi; import java.util.Set; public class Driver{ private Long driver_id; private String name; private int age; private Set carsOwned; public Driver() {} public Long getId() { return driver_id; } private void setId(Long driver_id) {//注意,private类型的可见范围 this.driver_id = driver_id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Set getCarsOwned() { return carsOwned; } public void setCarsOwned(Set carsOwned) { this.carsOwned = carsOwned; } } |
create table driver( driver_id bigint(20) PRIMARY KEY not null, name varchar(40), age int(11) ) |
package tomcatJndi; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import java.util.Iterator; import java.util.Set; import org.apache.log4j.Logger; import org.hibernate.SessionFactory; import org.hibernate.Session; import org.hibernate.Query; import org.hibernate.cfg.Configuration; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class RetrieveViaHibernate extends HttpServlet { public RetrieveViaHibernate() { super();} public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(""); out.println(""); out.println(" "); out.println(" "); out.print(" This is BRAND NEW "); out.print(this.getClass()); out.println(," using the GET method "); doQuery(out); //使用Hibernate存取Driver和Car表 out.println(" "); out.println(""); out.flush(); out.close(); } private void doQuery(PrintWriter out) { System.out.println("In doQuery"); try { //读取hibernate.cfg.xml并且准备好hibernate Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); String SQL_QUERY ="from Driver driver"; Query query = session.createQuery(SQL_QUERY); for(Iterator it=query.iterate(); it.hasNext(); ) { Driver driver=(Driver)it.next(); out.println("Driver name: " + driver.getName() + ," " ); out.println("Driver age: " + driver.getAge() + " " ); Set carsOwned = (Set)driver.getCarsOwned(); for (Iterator itOwned = carsOwned.iterator(); itOwned.hasNext(); ) { Car carOwned = (Car)itOwned.next(); out.println(" Manufacturer: " + carOwned.getManufacturer() + ," " ); out.println("Model: " + carOwned.getModel() + ," " ); out.println("Age: " + carOwned.getYear() ); out.println(" "); } } session.getTransaction().commit();//自动地关闭会话 } catch(Exception e) { System.out.println(e.getMessage()); } finally{} } } |
Session session = HibernateUtil.getSessionFactory().openSession(); |
Session session = HibernateUtil.getSessionFactory().getCurrentSession(); |