分享
 
 
 

JBuilder+Hibernate+Tomcat快速入门

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

JBuilder+Hibernate+Tomcat快速入门

高科华

作者简介:高科华,南京航空学院计算数学专业硕士,有十年以上的企业信息化工作经验。目前的研究兴趣,J2EE企业应用、ERP软件研发、数据仓库系统研发。

作者声明:本文没有最后定稿。

本文给出了用JBuilder开发Hibernate+Tomcat Web应用的一般步骤。

1. 下载hibernate-2.1.x.zip

http://prdownloads.sourceforge.net/hibernate/?sort_by=date&sort=desc

2. 安装,将zip文件解压到JBuilder_HOME\ thirdparty

3. 在JBuilder2005中新建hibernate库,选择菜单Tools-Configure-Libraries,在弹出的对话框中点击New按钮,输入hibernate库的名称:hibernate,点击Add按钮,将hibernate目录中的文件hibernate2.jar增加到hibernate库中,根据需要将hibernate\lib目录中的相应的*.jar增加到hibernate库中,一般需要这些类库:dom4j、CGLIB、Commons Collections、Commons Logging、ODMG4、EHCache

4. 新建工程文件,选菜单File-New Project,给工程文件取名为myProject

设置工程文件的属性,选菜单Project-Project Properties,选择Tomcat作为服务器,将hibernate库加入Path/Required Libraries。

5. 新建Web模块,选菜单File-New,给Web模块取名为quickstart

6. 用servlet向导新建一个servlet文件,选菜单File-New,在弹出的对话框中选择Web-Standard Servlet,取名为Servlet1,在向导的第五步选择Create a runtime configuration

7. 运行Servlet1

8. 将quickstart\Tomcat\conf目录中的文件server8080.xml加入工程文件,修改server8080.xml的内容

<?xml version="1.0" encoding="UTF-8"?>

<Server debug="0" port="8081" shutdown="SHUTDOWN">

<Service name="Catalina">

<Connector acceptCount="10" connectionTimeout="60000" debug="0" maxThreads="75" minSpareThreads="5" port="8080"/>

<Engine debug="0" defaultHost="localhost" name="Catalina">

<Host appBase="C:\jbproject\quickstart\Tomcat\webapps" autoDeploy="false" debug="0" deployXML="false" name="localhost" unpackWARs="false">

<!--Context debug="0" docBase="C:\jbproject\quickstart\quickstart" path="/quickstart" reloadable="true" workDir="C:\jbproject\quickstart\Tomcat\work\quickstart"/-->

<Context path="/quickstart" docBase="C:\jbproject\quickstart\quickstart" workDir="C:\jbproject\quickstart\Tomcat\work\quickstart">

<Resource name="jdbc/quickstart" scope="Shareable" type="javax.sql.DataSource"/>

<ResourceParams name="jdbc/quickstart">

<parameter>

<name>factory</name>

<value>org.apache.commons.dbcp.BasicDataSourceFactory</value>

</parameter>

<!-- DBCP database connection settings -->

<parameter>

<name>url</name>

<value>jdbc:hsqldb:hsql://localhost</value>

<!--value>jdbc:microsoft:sqlserver://nt04:1433;DatabaseName=test</value-->

</parameter>

<parameter>

<name>driverClassName</name>

<value>org.hsqldb.jdbcDriver</value>

<!--value>com.microsoft.jdbc.sqlserver.SQLServerDriver</value-->

</parameter>

<parameter>

<name>username</name>

<value>sa</value>

</parameter>

<parameter>

<name>password</name>

<value></value>

</parameter>

<!-- DBCP connection pooling options -->

<parameter>

<name>maxWait</name>

<value>3000</value>

</parameter>

<parameter>

<name>maxIdle</name>

<value>100</value>

</parameter>

<parameter>

<name>maxActive</name>

<value>10</value>

</parameter>

</ResourceParams>

</Context>

</Host>

</Engine>

</Service>

</Server>

9. 设置hibernate,在quickstart\src目录中新建文件hibernate.cfg.xml如下:

<?xml version='1.0' encoding='utf-8'?>

<!DOCTYPE hibernate-configuration

PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">

<hibernate-configuration>

<session-factory>

<property name="connection.datasource">java:comp/env/jdbc/quickstart</property>

<property name="show_sql">false</property>

<property name="dialect">net.sf.hibernate.dialect.PostgreSQLDialect</property>

<!-- Mapping files -->

<mapping resource="Cat.hbm.xml"/>

</session-factory>

</hibernate-configuration>

10. 新建一个持久类

package net.sf.hibernate.examples.quickstart;

public class Cat {

private String id;

private String name;

private char sex;

private float weight;

public Cat() {

}

public String getId() {

return id;

}

private 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;

}

}

11. 在quickstart\src目录中新建影射文件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="net.sf.hibernate.examples.quickstart.Cat" table="CAT">

<!-- A 32 hex character is our surrogate key. It's automatically

generated by Hibernate with the UUID pattern. -->

<id name="id" type="string" unsaved-value="null" >

<column name="CAT_ID" sql-type="char(32)" not-null="true"/>

<generator class="uuid.hex"/>

</id>

<!-- A cat has to have a name, but it shouldn' be too long. -->

<property name="name">

<column name="NAME" length="16" not-null="true"/>

</property>

<property name="sex"/>

<property name="weight"/>

</class>

</hibernate-mapping>

12. 准备数据库

13. 新建一个类HibernateUtil

import net.sf.hibernate.*;

import net.sf.hibernate.cfg.*;

public class HibernateUtil {

private static Log log = LogFactory.getLog(HibernateUtil.class);

private static final SessionFactory sessionFactory;

static {

try {

// Create the SessionFactory

sessionFactory = new Configuration().configure().buildSessionFactory();

} catch (Throwable ex) {

log.error("Initial SessionFactory creation failed.", ex);

throw new ExceptionInInitializerError(ex);

}

}

public static final ThreadLocal session = new ThreadLocal();

public static Session currentSession() throws HibernateException {

Session s = (Session) session.get();

// Open a new Session, if this Thread has none yet

if (s == null) {

s = sessionFactory.openSession();

session.set(s);

}

return s;

}

public static void closeSession() throws HibernateException {

Session s = (Session) session.get();

session.set(null);

if (s != null)

s.close();

}

}

14. 修改Servlet1.java

package net.sf.hibernate.examples.quickstart;

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

import java.util.*;

import net.sf.hibernate.Transaction;

import net.sf.hibernate.HibernateException;

import net.sf.hibernate.Session;

import net.sf.hibernate.Query;

public class Servlet1 extends HttpServlet {

private static final String CONTENT_TYPE = "text/html; charset=Big5";

private HibernateUtil hibernateUtil = null;

//Initialize global variables

public void init() throws ServletException {

}

//Process the HTTP Get request

public void doGet(HttpServletRequest request, HttpServletResponse response) throws

ServletException, IOException {

response.setContentType(CONTENT_TYPE);

PrintWriter out = response.getWriter();

hibernateUtil = new HibernateUtil();

try {

Session session = hibernateUtil.currentSession();

Transaction tx = session.beginTransaction();

Cat princess = new Cat();

princess.setName("Princess");

princess.setSex('F');

princess.setWeight(7.4f);

session.save(princess);

tx.commit();

Query query = session.createQuery(

"select c from Cat as c where c.sex = :sex");

query.setCharacter("sex", 'F');

out.println("<html>");

out.println("<head><title>Servlet1</title></head>");

out.println("<body bgcolor=\"#ffffff\">");

for (Iterator it = query.iterate(); it.hasNext(); ) {

Cat cat = (Cat) it.next();

out.println("<p>Female Cat: " + cat.getName()+"</p>");

}

out.println("</body>");

out.println("</html>");

out.close();

tx.commit();

HibernateUtil.closeSession();

} catch (HibernateException e) {

e.printStackTrace();

}

}

//Process the HTTP Post request

public void doPost(HttpServletRequest request, HttpServletResponse response) throws

ServletException, IOException {

doGet(request, response);

}

//Process the HTTP Put request

public void doPut(HttpServletRequest request, HttpServletResponse response) throws

ServletException, IOException {

}

//Clean up resources

public void destroy() {

}

}

15. 再次运行Servlet1,报错。

16. 设置工程文件的属性,选菜单Project-Project Properties,在弹出的对话框中选择Build-Resource-xml,选择选择按钮Copy。这一步是为了在重建工程文件时把src目录中的xml文件拷贝到classes目录中。

17. 再次运行Servlet1,你将看到使用了hibernate后的显示结果。

“hibernate.cfg.xml not found”。

用JUnit测试时,文件hibernate.cfg.xml中需增加如下内容:

<property name="connection.driver_class">org.hsqldb.jdbcDriver</property>

<property name="connection.url">jdbc:hsqldb:hsql://localhost</property>

<property name="username">sa</property>

<property name="password"></property>

<property name="connection.provider_class"> net.sf.hibernate.connection.DBCPConnectionProvider</property>

<property name="connection.pool_size">50</property>

<property name="dbcp.maxActive">100</property>

<property name="dbcp.whenExhaustedAction">1</property>

<property name="dbcp.maxWait">120000</property>

<property name="dbcp.maxIdle">10</property>

参考资源

http://www.hibernate.org/hib_docs/reference/en/html/quickstart.html

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
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- 王朝網路 版權所有