My First Hibernate Application

    技术2022-05-11  105

    1. Create a new Dynamic Web Application.2. In order to connect to Mysql, we have to copy mysql-connector-java-3.1.11-bin.jar into /lib. And we create a bable T_Register in schemata test. The sql sentence is: CREATE TABLE T_Register (id INT PRIMARY KEY, username VARCHAR(20), password VARCHAR(20), gender VARCHAR(10), age INT(3)).3. Add necessary Hibernate Jars into /WEB-INF/lib. In MyEclipse, we can use MyEclispse -> Add Hibernate Capabilities. It will copy Hibernate Jars into /lib and lead us to create hibernate.cfg.xml. We also need to copy aspectjrt.jar into lib, or it will report error:" NoClassDefFound: org.aspectj.lang.Signature ...". Aspectj could be download from http://www.eclipse.org/aspectj/downloads.php.4. Create hibernate.cfg.xml----------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" > newweapon </ property >   < property  name ="connection.url" >   jdbc:mysql://localhost:3306/test  </ property >   < property  name ="dialect" >   org.hibernate.dialect.MySQLDialect  </ property >   < property  name ="myeclipse.connection.profile" > test </ property >   < property  name ="connection.password" > password </ property >   < property  name ="connection.driver_class" >   com.mysql.jdbc.Driver  </ property >   < property  name ="show_sql" > true </ property >    <!--  mapping element could be add later  -->   < mapping  resource ="register/register.hbm.xml"   /> </ session-factory >

    ---------5. Create register/register.hbm.xml-----------register.hbm.xml--------------

    <? xml version="1.0" encoding="UTF-8" ?> <! DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" > < hibernate-mapping  package ="register" >   < class  name ="register.Register"  table ="T_Register" >    < id  name ="id"  column ="id" >     < generator  class ="increment" />     </ id >    < property  name ="username"  column ="Username"  type ="string" />    < property  name ="password"  column ="Password"  type ="string" />    < property  name ="gender"  column ="Gender"  type ="string" />    < property  name ="age"  column ="Age"  type ="int" />   </ class > </ hibernate-mapping >

    --------------6. Create HibernateUtil.java. It is a session factory. When adding hibernate capabilities into our project, the wizard will create it automatically. In default, the wizard names it HibernateSessionFactory.java. Of course, we can change it into any name like HibernateUtil.java.----------------HibernateUtil.java----------------

    package  util; 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  HibernateUtil  {    /**      * 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<Session> threadLocal = new ThreadLocal<Session>();    private  static Configuration configuration = new Configuration();    private static org.hibernate.SessionFactory sessionFactory;    private static String configFile = CONFIG_FILE_LOCATION;    private HibernateUtil() {    }  /**     * 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) {  HibernateUtil.configFile = configFile;  sessionFactory = null; } /**     *  return hibernate configuration     *     */ public static Configuration getConfiguration() {  return configuration; }}

    ----------------7. Create Register.java which is the Model and RegisterServlet.java which is the Controler. DON'T forget to register the servlet in web.xml.----------------Register.java ----------------

    package  register; public   class  Register  int id; String username = new String(); String password = new String(); String gender = new String(); int age;  public Register(){   } public int getId() {  return this.id; } public void setId(int id) {  this.id = id; } public String getUsername() {  return this.username; } public void setUsername(String username) {  this.username = username; } public String getPassword() {  return this.password; } public void setPassword(String password) {  this.password = password; } public String getGender() {  return this.gender; } public void setGender(String gender) {  this.gender = gender; } public int getAge() {  return this.age; } public void setAge(int age) {  this.age = age; }}

    ----------------RegisterServlet.java ----------------

    package  register; import  java.io.IOException; import  java.io.PrintWriter; import  javax.servlet.ServletException; import  javax.servlet.http.HttpServlet; import  javax.servlet.http.HttpServletRequest; import  javax.servlet.http.HttpServletResponse; import  org.hibernate.HibernateException; import  org.hibernate.Session; import  org.hibernate.Transaction; import  util.HibernateUtil;; public   class  RegisterServlet  extends  HttpServlet  private static final String CONTENT_TYPE = "text/html; charset=GBK"public void doGet(HttpServletRequest request, HttpServletResponse response)   throws ServletException, IOException {  response.setContentType(CONTENT_TYPE);  String username = request.getParameter("username");  String password = request.getParameter("password");  String gender = request.getParameter("gender");  int age = Integer.parseInt(request.getParameter("age"));  Register rg = new Register();  rg.setUsername(username);  rg.setPassword(password);  rg.setGender(gender);  rg.setAge(age);  Session session = util.HibernateUtil.getSession();    Transaction tx = session.beginTransaction();  try {   session.save(rg);   tx.commit();   session.close();   response.sendRedirect("reply.jsp");  } catch (HibernateException e) {   e.printStackTrace();   tx.rollback();   response.sendRedirect("error.jsp");  } } public void doPost(HttpServletRequest request, HttpServletResponse response)   throws ServletException, IOException {  doGet(request, response); } public void destroy() { }}

    ----------------8. Create JSP files register.jsp, reply.jsp and error.jsp. ----------------register.jsp----------------

    <% @ page language="java" contentType="text/html; charset=ISO-8859-1"    pageEncoding="ISO-8859-1" %> <! DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" > < html > < head > < meta  http-equiv ="Content-Type"  content ="text/html; charset=ISO-8859-1" > < title > Register </ title > </ head > < body > < form  action ="RegisterServlet"  method ="post" > Username:  < input  type ="text"  name ="username" />< br />< br /> Password:  < input  type ="password"  name ="password" />< br />< br /> Gender:  < input  type ="text"  name ="gender" />< br />< br /> Age:  < input  type ="text"  name ="age" />< br />< br /> < input  type ="submit"  value ="Save" /> </ form > </ body > </ html >

    ----------------reply.jsp----------------

    < html > Register successfully! </ html >

    ----------------error.jsp----------------<html>Error</html>----------------

    Notes:1. The differences between Lomboz and MyEclipse. 1) MyEclipse is more powerful than Lomboz. It is easy to add hibernate, struts, spring and other capabilities into projects but it consumes much more memory. 2) In Lomboz, we create dynamic web application and it will ask us to choose a Server such as Tomcat, while in MyEclipse we create a web application and later we config the server and add the web application into the server. 2. In Eclipse, the log displayed in the console window can give us much more infomation than the errors reported in the browser.

     


    最新回复(0)