Hibernate 初识
上一篇主要是写了手动写Hibernate , 这一篇加点补充,主要是关于使用Eclipse自动 生成,好了,进入正题:
 Step1:首先我们新建一个WebProject!
 Step2:在src下新建一个包我取名为 fengyan.hibernate,用于存放Hibernate的配置文件
 Step3:现在用MyEclipse添加Hibernate,选中fengyan.hibernate包,单击MyEclipse---->add hibernate capabilities,具体看下图 

 
 
生成Session工厂类!方便我们取得会话

Step4:单击“完成”后,我们在接着出现的Hibernate.ctg.xml配置文件的视图添加一个properties属性,如下图
 具体意思是Hibernate 在运行时可以在控制台输出执行的SQL语句,方便 我们监视!
 Step5:我们切换到MyEclipse Database explorer,数据库视图,因为昨天安装了MySQL,所以我配置了MySQL的连接 ,我们在study数据库下新建立一张测试表testTable, 
 DDL语句如下:
 create table `study`.`testtable`(
     create table `study`.`testtable`( `id` int not null auto_increment,--ID 自增加 在SqlServer为 Identity(1,1)
        `id` int not null auto_increment,--ID 自增加 在SqlServer为 Identity(1,1) `username` varchar(20),
       `username` varchar(20), primary key (`id`)
        primary key (`id`) );
    ); create unique index `PRIMARY` on `study`.`testtable`(`id`);
    create unique index `PRIMARY` on `study`.`testtable`(`id`);
Step6:我们选中刚刚新建的表,如下:

创建映射配置信息文件,以及数据Bean对象 Java Data Object
指定主键类型
在 Java src folder 我们选择刚刚新建的包 fengyan.beans,它这时会自动给我们由表生成对应的Beans以及映射信息XML文件
     单击下一步 以及完成即可!我们现在看看在我们的beans包下有什么东东,多了名为Testtable.java类,这个就是MyEclipse为我们自动根据Testtable表生成的Bean.看看里面的内容 
 
 package fengyan.beans;
package fengyan.beans;

 public class Testtable  implements java.io.Serializable {
public class Testtable  implements java.io.Serializable { //继承Serializable接口,序列化,可以排序
       //继承Serializable接口,序列化,可以排序

 private Integer id;
     private Integer id; private String username;
     private String username;
 
    public Testtable() {
    public Testtable() { }
    }     
   //看见了,很智能的给我们生成了一个参数的构造函数
    //看见了,很智能的给我们生成了一个参数的构造函数 //因为ID为自动递增的主键,所以这里的参数为username
    //因为ID为自动递增的主键,所以这里的参数为username public Testtable(String username) {
    public Testtable(String username) { this.username = username;
        this.username = username; }
    }

 public Integer getId() {
    public Integer getId() { return this.id;
        return this.id; }
    } 
     public void setId(Integer id) {
    public void setId(Integer id) { this.id = id;
        this.id = id; }
    }
 public String getUsername() {
    public String getUsername() { return this.username;
        return this.username; }
    } 
     public void setUsername(String username) {
    public void setUsername(String username) { this.username = username;
        this.username = username; }
    }
 }
}

思考:那这个Bean如何与我们的表关联呢,接着在fengyan.beans包下我们还发现生成了Testtable.hbm.xml 代码如下:
 <?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!--
<!--  Mapping file autogenerated by MyEclipse - Hibernate Tools
    Mapping file autogenerated by MyEclipse - Hibernate Tools -->
--> <hibernate-mapping>
<hibernate-mapping> <!-- Bean的全名      映射的表名   数据库名,因为我们在Hibernate.cfg.xml中配置了数据库,所以这里的catalog要删除 -->
   <!-- Bean的全名      映射的表名   数据库名,因为我们在Hibernate.cfg.xml中配置了数据库,所以这里的catalog要删除 -->     <class name="fengyan.beans.Testtable" table="testtable" catalog="study">
    <class name="fengyan.beans.Testtable" table="testtable" catalog="study"> <!-- 主键用<id>, -->
       <!-- 主键用<id>, --> <id name="id" type="java.lang.Integer">
        <id name="id" type="java.lang.Integer"> <column name="id" /><!-- 对应表中的字段名 -->
            <column name="id" /><!-- 对应表中的字段名 --> <generator class="native" /><!-- 主键类型native支持自动增长方式 -->
            <generator class="native" /><!-- 主键类型native支持自动增长方式 --> </id>
        </id> <!-- 一般的属性用<property> -->
        <!-- 一般的属性用<property> --> <property name="username" type="java.lang.String">
        <property name="username" type="java.lang.String"> <column name="username" length="20" />
            <column name="username" length="20" /> </property>
        </property> </class>
    </class> </hibernate-mapping>
</hibernate-mapping>Step7:我们新加一个DAOs(dataAccessObject)包,并在其中添加一个TesttableDAO.java,负责对Bean的操作,代码如下:
 package fengyan.DAOS;
package fengyan.DAOS;
 import org.hibernate.Session;
import org.hibernate.Session;
 import fengyan.beans.Testtable;
import fengyan.beans.Testtable; import fengyan.hibernate.HibernateSessionFactory;
import fengyan.hibernate.HibernateSessionFactory;
 public class TesttableDAO {
public class TesttableDAO { public void addTesttable(Testtable user)
 public void addTesttable(Testtable user) {
 { //创建连接
  //创建连接 Session session = HibernateSessionFactory.getSession();
  Session session = HibernateSessionFactory.getSession(); //事物
  //事物 Transaction tx = session.beginTransaction();
  Transaction tx = session.beginTransaction(); //操作
   //操作 session.save(user);
   session.save(user); //提交事物
  //提交事物 tx.commit();
  tx.commit(); //关闭会话
  //关闭会话 session.close();
  session.close(); }
 }
 }
}

 Step7:接下来建立一个Servlet~如下图:
其中代码:
 public void doPost(HttpServletRequest request, HttpServletResponse response)
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   throws ServletException, IOException {
 response.setContentType("text/html");
  response.setContentType("text/html"); request.setCharacterEncoding("GBK");//解决接收中文
  request.setCharacterEncoding("GBK");//解决接收中文 
   //接收视图中的参数
  //接收视图中的参数 String username = request.getParameter("username");
  String username = request.getParameter("username");   
   //声明Bean及操作对象
  //声明Bean及操作对象 Testtable user = new Testtable();
  Testtable user = new Testtable(); TesttableDAO userdao = new TesttableDAO();
  TesttableDAO userdao = new TesttableDAO(); 
   //执行业务
  //执行业务 if(username != null && !username.equals(""))
  if(username != null && !username.equals("")) {
  { System.out.print(username);
   System.out.print(username); user.setUsername(username);
   user.setUsername(username); userdao.addTesttable(user);
   userdao.addTesttable(user); }
  } else
  else {
  { response.sendRedirect("/Hibernate01b/adduser.jsp");
   response.sendRedirect("/Hibernate01b/adduser.jsp"); }
  } }
 }

Step8:接下来写一个东西来测试下!新建立一个adduser.jsp文件
 <%@ page language="java" pageEncoding="GBK"%>
<%@ page language="java" pageEncoding="GBK"%> <%
<% String path = request.getContextPath();
String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>
%>
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html>
<html> <head>
  <head> <base href="<%=basePath%>">
    <base href="<%=basePath%>">     <title>My JSP 'adduser.jsp' starting page</title>
    <title>My JSP 'adduser.jsp' starting page</title>     </head>
  </head>   <body>
  <body> <%=basePath %><BR>
  <%=basePath %><BR> <form action="<%=basePath %>servlet/AddUser" method="post">
    <form action="<%=basePath %>servlet/AddUser" method="post"> 用户名:<input type=text name="username"/>
    用户名:<input type=text name="username"/> <input type=submit>
    <input type=submit> 
     </form><br>
    </form><br> </body>
  </body> </html>
</html> 另外将Hibernate及Web.xml文件代码贴下:
hibernate.cfg.xml
 <?xml version='1.0' encoding='UTF-8'?>
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 <!-- Generated by MyEclipse Hibernate Tools.                   -->
<!-- Generated by MyEclipse Hibernate Tools.                   --> <hibernate-configuration>
<hibernate-configuration> <session-factory>
    <session-factory> <property name="connection.username">root</property>
        <property name="connection.username">root</property> <property name="connection.url">
        <property name="connection.url"> jdbc:mysql://localhost:3306/study
            jdbc:mysql://localhost:3306/study </property>
        </property> <property name="dialect">
        <property name="dialect"> org.hibernate.dialect.MySQLDialect
            org.hibernate.dialect.MySQLDialect </property>
        </property> <property name="myeclipse.connection.profile">
        <property name="myeclipse.connection.profile"> MySQL5.0
            MySQL5.0 </property>
        </property> <property name="connection.password">root</property>
        <property name="connection.password">root</property> <property name="connection.driver_class">
        <property name="connection.driver_class"> org.gjt.mm.mysql.Driver
            org.gjt.mm.mysql.Driver </property>
        </property> <property name="show_sql">true</property>
        <property name="show_sql">true</property> <mapping resource="fengyan/beans/Testtable.hbm.xml" />
        <mapping resource="fengyan/beans/Testtable.hbm.xml" /> </session-factory>
    </session-factory> </hibernate-configuration>
</hibernate-configuration>web.xml
 <?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.4"
<web-app version="2.4"  xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns="http://java.sun.com/xml/ns/j2ee"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee  http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <welcome-file-list>
 <welcome-file-list> <welcome-file>/adduser.jsp</welcome-file>
     <welcome-file>/adduser.jsp</welcome-file> </welcome-file-list>
 </welcome-file-list> <servlet>
  <servlet> <description>This is the description of my J2EE component</description>
    <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name>
    <display-name>This is the display name of my J2EE component</display-name> <servlet-name>AddUser</servlet-name>
    <servlet-name>AddUser</servlet-name> <servlet-class>fengyan.servlet.AddUser</servlet-class>
    <servlet-class>fengyan.servlet.AddUser</servlet-class> </servlet>
  </servlet>
 <servlet-mapping>
  <servlet-mapping> <servlet-name>AddUser</servlet-name>
    <servlet-name>AddUser</servlet-name> <url-pattern>/servlet/AddUser</url-pattern>
    <url-pattern>/servlet/AddUser</url-pattern> </servlet-mapping>
  </servlet-mapping> </web-app>
</web-app>HibernateSessionFactory.java代码
 package fengyan.hibernate;
package fengyan.hibernate;
 import org.hibernate.HibernateException;
import org.hibernate.HibernateException; import org.hibernate.Session;
import org.hibernate.Session; import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Configuration;

 public class HibernateSessionFactory {
public class HibernateSessionFactory { 
   private static String CONFIG_FILE_LOCATION = "/fengyan/hibernate/hibernate.cfg.xml";
    private static String CONFIG_FILE_LOCATION = "/fengyan/hibernate/hibernate.cfg.xml"; private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); private  static Configuration configuration = new Configuration();
    private  static Configuration configuration = new Configuration(); private static org.hibernate.SessionFactory sessionFactory;
    private static org.hibernate.SessionFactory sessionFactory; private static String configFile = CONFIG_FILE_LOCATION;
    private static String configFile = CONFIG_FILE_LOCATION;
 private HibernateSessionFactory() {
    private HibernateSessionFactory() { }
    }
 public static Session getSession() throws HibernateException {
    public static Session getSession() throws HibernateException { Session session = (Session) threadLocal.get();
        Session session = (Session) threadLocal.get();
 if (session == null || !session.isOpen()) {
        if (session == null || !session.isOpen()) { if (sessionFactory == null) {
            if (sessionFactory == null) { rebuildSessionFactory();
                rebuildSessionFactory(); }
            } session = (sessionFactory != null) ? sessionFactory.openSession()
            session = (sessionFactory != null) ? sessionFactory.openSession() : null;
                    : null; threadLocal.set(session);
            threadLocal.set(session); }
        }
 return session;
        return session; }
    }
 public static void rebuildSessionFactory() {
    public static void rebuildSessionFactory() { try {
        try { configuration.configure(configFile);
            configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory();
            sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) {
        } catch (Exception e) { System.err
            System.err .println("%%%% Error Creating SessionFactory %%%%");
                    .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace();
            e.printStackTrace(); }
        } }
    }

 public static void closeSession() throws HibernateException {
    public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get();
        Session session = (Session) threadLocal.get(); threadLocal.set(null);
        threadLocal.set(null);
 if (session != null) {
        if (session != null) { session.close();
            session.close(); }
        } }
    }

 public static org.hibernate.SessionFactory getSessionFactory() {
    public static org.hibernate.SessionFactory getSessionFactory() { return sessionFactory;
        return sessionFactory; }
    }

 public static void setConfigFile(String configFile) {
    public static void setConfigFile(String configFile) { HibernateSessionFactory.configFile = configFile;
        HibernateSessionFactory.configFile = configFile; sessionFactory = null;
        sessionFactory = null; }
    }

 public static Configuration getConfiguration() {
    public static Configuration getConfiguration() { return configuration;
        return configuration; }
    }
 }
} 
                    
                     
                    
                 
                    
                

 
     
                
            
         
 
         浙公网安备 33010602011771号
浙公网安备 33010602011771号