分享
 
 
 

Hibernate入门配置

王朝java/jsp·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

Hibernate入门配置

一、建表

<<<<<<<<<<<<<表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>

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有