[本站首页] [管理页面] [写新日志] [退出]

朝为田舍郎,暮登天子堂,将相本无种,男儿当自强。
首页(178) Hibernate(10) JAVA(19) Web(15) Struts(7) 口水(9) Ides(18) 其它(51) AJAX(6) database(29) 
Blog信息

blog名称:四裤全输的小窝~~
日志总数:178
评论数量:699
留言数量:198
访问次数:1152586
建立时间:2005年10月29日

Blog内搜索



日志更新

谷歌地图定位偏移解决方法
【转】利用Windows内置的命令作端口
WIN2003服务器安全加固方案
[转]sql server 日期比较、日
MediaCoder 一般参数设置
[转]VMware中创建共享磁盘阵列的方
缓解vss共享文件夹的安全隐患问题(转)
Delphi 中调用JavaScript
微软的官方方法:延长Windows Se
cxGrid 过滤 排序后 取选中记录的

最新评论

回复:谷歌地图定位偏移解决方法
回复:谷歌地图定位偏移解决方法
回复:WIN2003服务器安全加固方案
回复:cxGrid 过滤 排序后 取选中
回复:TreeView 父节点 子节点 
回复:[转]Oracle Instead
回复:DWR 官方下载地址
ugg  boots
回复:cxGrid 过滤 排序后 取选中
回复:DWR 官方下载地址

友情链接

biglin's Blog
NoisyRam's Blog
Stone's Blog
Kevin 的小家
『知』治通鉴

留言板




[Hibernate]Hibernate入门配置
文章收藏,  网上资源,  软件技术,  电脑与网络 四裤全输 发表于 2006/10/16 20:35:14

转自:www.javafan.net/article/20060608205832987.html一、建表<<<<<<<<<<<<<表cat>>>>>>>>>>>>>>>>>>>>>>>>>>>>>CREATE TABLE cat (    cat_id varchar(20) NOT NULL,    NAME varchar(20) NOT NULL,    sex CHAR(1),    weight FLOAT,    PRIMARY KEY (cat_id)); 二、po层(系统以cat.hbm.xml为准,一个xml可以写多个class) <<<<<<<<<<<<<cat.hbm.xml>>>>>>>>>>>>>>>>>>>>>>><?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"> <hibernate-mapping>     <class name="com.netease.wireless.groupsms.hbnt.po.Cat" table="cat">         <id name="id" type="string" unsaved-value="null" >            <column name="cat_id" sql-type="varchar(20)" not-null="true"/>            <generator class="uuid.hex"/>        </id>         <property name="name">            <column name="NAME" sql-type="varchar(20)" not-null="true"/>        </property>         <property name="sex"/>         <property name="weight"/>     </class> </hibernate-mapping> <<<<<<<<<<<<<Cat.java>>>>>>>>>>>>>>>>>>>>>>>>>package com.netease.wireless.groupsms.hbnt.po; public class Cat {     private String id;    private String name;    private char sex;    private float weight;     public Cat() {    }     public String getId() {        return id;    }     public void setId(String id) {        this.id = id;    }     public String getName() {        return name;    }     public void setName(String name) {        this.name = name;    }     public char getSex() {        return sex;    }     public void setSex(char sex) {        this.sex = sex;    }     public float getWeight() {        return weight;    }     public void setWeight(float weight) {        this.weight = weight;    }     public String toString() {        String strCat = new StringBuffer()            .append(this.getId()).append(", ")            .append(this.getName()).append(", ")            .append(this.getSex()).append(", ")            .append(this.getWeight())            .toString();         return strCat;    }} 三、hibernate.cfg.xml(切切不要自己去加属性,基本的就两个connection.datasource和dialect)<property name="connection.username">root</property>       <property name="connection.password">root</property><property name="connection.provider_class">net.sf.hibernate.connection.DatasourceConnectionProvider</property><property name="jndi.class">org.gjt.mm.mysql.Driver</property> <<<<<<<<<<<<<hibernate.cfg.xml>>>>>>>>>>>>>>>>>>>>>>><?xml version='1.0' encoding='UTF-8'?><!DOCTYPE hibernate-configuration PUBLIC          "-//Hibernate/Hibernate Configuration DTD 2.0//EN"          "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd"> <!-- DO NOT EDIT: This is a generated file that is synchronized --><!-- by MyEclipse Hibernate tool integration.                   --><hibernate-configuration>     <session-factory>        <!-- properties -->        <property name="connection.datasource">java:comp/env/jdbc/test</property>        <property name="show_sql">true</property>        <property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property>             <!-- mapping files -->  <mapping resource="com/netease/wireless/groupsms/hbnt/po/cat.hbm.xml"/>      </session-factory> </hibernate-configuration> 四、测试servlet //Session生成/关闭<<<<<<<<<<<<<HibernateUtil.java>>>>>>>>>>>>>>>>>>>>>>> package com.netease.wireless.groupsms.hbnt.util;import net.sf.hibernate.HibernateException;import net.sf.hibernate.Session;import net.sf.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.     * NOTICE: Location should be on the classpath as Hibernate uses     * #resourceAsStream style lookup for its configuration file. That     * is place the config file in a Java package - the default location     * is the default Java package.<br><br>     * Examples: <br>     * <code>CONFIG_FILE_LOCATION = "/hibernate.conf.xml".      * CONFIG_FILE_LOCATION = "/com/foo/bar/myhiberstuff.conf.xml".</code>      */    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";//hibernate.cfg.xml     /** Holds a single instance of Session */    private static final ThreadLocal threadLocal = new ThreadLocal();     /** The single instance of hibernate configuration */    private static final Configuration cfg = new Configuration();     /** The single instance of hibernate SessionFactory */    private static net.sf.hibernate.SessionFactory sessionFactory;     /**     * Returns the ThreadLocal Session instance.  Lazy initialize     * the <code>SessionFactory</code> if needed.     *     *  @return Session     *  @throws HibernateException     */    public static Session currentSession() throws HibernateException {        Session session = (Session) threadLocal.get();         if (session == null) {            if (sessionFactory == null) {                try {                    cfg.configure(CONFIG_FILE_LOCATION);                    //cfg.configure();                    sessionFactory = cfg.buildSessionFactory();                }                catch (Exception e) {                    System.err.println("%%%% Error Creating SessionFactory %%%%");                    System.err.println("|||||||||||||" + e.getMessage());                    e.printStackTrace();                }            }            session = sessionFactory.openSession();            threadLocal.set(session);        }         return session;    }     /**     *  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();        }    }     /**     * Default constructor.     */    private HibernateUtil() {    } } <<<<<<<<<<<<<测试HbntTestSvlt.java>>>>>>>>>>>>>>>>>>>>>>> /* *  * @(#)CorpSMS.corpsms V1.0 2005-1-15 * Copyright 2003 NetEase, Inc. All rights reserved. *  * coder: sweater  * email: wtshi@corp.netease.com *  * graphic designer: * email: * * fuction:向电话薄中添加组和电话号码 *  */ package com.netease.wireless.groupsms.vo; import java.io.IOException;import java.io.PrintWriter;import java.util.Iterator; import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; import net.sf.hibernate.HibernateException;import net.sf.hibernate.Query;import net.sf.hibernate.Session;import net.sf.hibernate.Transaction; import com.netease.wireless.groupsms.hbnt.po.Cat;import com.netease.wireless.groupsms.hbnt.util.HibernateUtil;/** * * @author sweater */public class HbntTestSvlt extends HttpServlet {     /**     * Constructor of the object.     */    public HbntTestSvlt() {        super();    }     /**     * Destruction of the servlet. <br>     */    public void destroy() {        super.destroy(); // Just puts "destroy" string in log        // Put your code here    }     /**     * The doGet method of the servlet. <br>     *     * This method is called when a form has its tag value method equals to get.     *      * @param request the request send by the client to the server     * @param response the response send by the server to the client     * @throws ServletException if an error occurred     * @throws IOException if an error occurred     */    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {         response.setContentType("text/html");        PrintWriter out = response.getWriter();         out.println("<html>");        out.println("<head>");     out.println("<title>Hello Hibernate</title>");        out.println("</head>");        out.println("<body>");     out.println("Hello Hibernate!<br>");         try {            Session session = HibernateUtil.currentSession();             Transaction tx = session.beginTransaction();             Query query = session.createQuery("select cat from Cat as cat where cat.sex = :sex");            query.setCharacter("sex", 'F');             for (Iterator it = query.iterate(); it.hasNext();) {                Cat cat = (Cat) it.next();                out.println("Cat: " + cat.toString() + "<br>");            }             tx.commit();             HibernateUtil.closeSession();        } catch (HibernateException e) {            System.out.println(e.getMessage());            //System.out.println(e.printStackTrace());        }         out.println("</body>");        out.println("</html>");    }     /**     * The doPost method of the servlet. <br>     *     * This method is called when a form has its tag value method equals to post.     *      * @param request the request send by the client to the server     * @param response the response send by the server to the client     * @throws ServletException if an error occurred     * @throws IOException if an error occurred     */    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {         response.setContentType("text/html");        PrintWriter out = response.getWriter();        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");        out.println("<HTML>");        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");        out.println("  <BODY>");        out.print("    This is ");        out.print(this.getClass());        out.println(", using the POST method");        out.println("  </BODY>");        out.println("</HTML>");        out.flush();        out.close();    }     /**     * Returns information about the servlet, such as      * author, version, and copyright.      *     * @return String information about this servlet     */    public String getServletInfo() {        return "This is my default servlet created by Eclipse";    }     /**     * Initialization of the servlet. <br>     *     * @throws ServletException if an error occure     */    public void init() throws ServletException {        // Put your code here    } } <<<<<<<<<<<<<该servlet使用时的web.xml>>>>>>>>>>>>>>>>>>>>>>> <?xml version="1.0" encoding="UTF-8"?><web-app version="2.4"  xmlns="http://java.sun.com/xml/ns/j2ee"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee  http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  <servlet>    <description>hbnttest</description>    <display-name>hbnttest</display-name>    <servlet-name>HbntTestSvlt</servlet-name>    <servlet-class>com.netease.wireless.groupsms.vo.HbntTestSvlt</servlet-class>  </servlet>   <servlet-mapping>    <servlet-name>HbntTestSvlt</servlet-name>    <url-pattern>/servlet/HbntTestSvlt</url-pattern>  </servlet-mapping> </web-app> 


阅读全文(2444) | 回复(0) | 编辑 | 精华


发表评论:
昵称:
密码:
主页:
标题:
验证码:  (不区分大小写,请仔细填写,输错需重写评论内容!)
站点首页 | 联系我们 | 博客注册 | 博客登陆

Sponsored By W3CHINA
W3CHINA Blog 0.8 Processed in 0.219 second(s), page refreshed 144765794 times.
《全国人大常委会关于维护互联网安全的决定》  《计算机信息网络国际联网安全保护管理办法》
苏ICP备05006046号