用MyEclipse开发Hibernate入门实例

开发 后端
本文提供的Hibernate入门实例使用MyEclipse开发。文章从设置环境到最后的测试都介绍的十分详细。

以下为一个Hibernate入门实例,使用MyEclipse开发。

一、环境

1.eclipse 3.2.2
2.myeclipse 5.1.1
3.jdk 1.5

二、简要说明

数据库为mysql

在mysql中建立一个test数据库,建立cat表

  1. CREATE TABLE `cat` (  
  2. `cat_id` varchar(32) NOT NULL,  
  3. `namevarchar(16) NOT NULL,  
  4. `sex` varchar(1) default NULL,  
  5. `weight` float(9,3) default NULL,  
  6. PRIMARY KEY (`cat_id`)  

三、步骤

1.导入包的准备工作

a.新建java project.建立包example
在它下面编写类Cat.java

  1. package example;  
  2.  
  3. public class Cat implements java.io.Serializable {  
  4.  
  5.  
  6.     // Fields     
  7.  
  8.      private String catId;  
  9.      private String name;  
  10.      private String sex;  
  11.      private Float weight;  
  12.  
  13.  
  14.     // Constructors  
  15.  
  16.     /** default constructor */ 
  17.     public Cat() {  
  18.     }  
  19.  
  20. /** minimal constructor */ 
  21.     public Cat(String name) {  
  22.         this.name = name;  
  23.     }  
  24.       
  25.     /** full constructor */ 
  26.     public Cat(String name, String sex, Float weight) {  
  27.         this.name = name;  
  28.         this.sex = sex;  
  29.         this.weight = weight;  
  30.     }  
  31.  
  32.      
  33.     // Property accessors  
  34.  
  35.     public String getCatId() {  
  36.         return this.catId;  
  37.     }  
  38.       
  39.     public void setCatId(String catId) {  
  40.         this.catId = catId;  
  41.     }  
  42.  
  43.     public String getName() {  
  44.         return this.name;  
  45.     }  
  46.       
  47.     public void setName(String name) {  
  48.         this.name = name;  
  49.     }  
  50.  
  51.     public String getSex() {  
  52.         return this.sex;  
  53.     }  
  54.       
  55.     public void setSex(String sex) {  
  56.         this.sex = sex;  
  57.     }  
  58.  
  59.     public Float getWeight() {  
  60.         return this.weight;  
  61.     }  
  62.       
  63.     public void setWeight(Float weight) {  
  64.         this.weight = weight;  
  65.     }   
  66. }  

同样在此包下面编写Cat.hbm.xml

  1. < ?xml version="1.0" encoding="utf-8"?> 
  2. < !DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
  4. < !--   
  5.     Mapping file autogenerated by MyEclipse - Hibernate Tools  
  6. --> 
  7. < hibernate-mapping> 
  8.     < class name="example.Cat" table="cat" catalog="testhibernate"> 
  9.         < id name="catId" type="java.lang.String"> 
  10.             < column name="cat_id" length="32" /> 
  11.             < generator class="uuid.hex">< /generator> 
  12.         < /id> 
  13.         < property name="name" type="java.lang.String"> 
  14.             < column name="name" length="16" not-null="true" /> 
  15.         < /property> 
  16.         < property name="sex" type="java.lang.String"> 
  17.             < column name="sex" length="1" /> 
  18.         < /property> 
  19.         < property name="weight" type="java.lang.Float"> 
  20.             < column name="weight" precision="9" scale="3" /> 
  21.         < /property> 
  22.     < /class> 
  23. < /hibernate-mapping> 

b.在工程的src里面加入一个包,用来存放将要生成的HibernateSessionFactory。包名如(example.util)。
导入hibernate生成的代码:

  1. package example.util;  
  2.  
  3. import org.hibernate.HibernateException;  
  4. import org.hibernate.Session;  
  5. import org.hibernate.cfg.Configuration;  
  6.  
  7. /**  
  8. * Configures and provides access to Hibernate sessions, tied to the  
  9. * current thread of execution. Follows the Thread Local Session  
  10. * pattern, see {@link http://hibernate.org/42.html }.  
  11. */ 
  12. public class HibernateSessionFactory {  
  13.  
  14.     /**   
  15.      * Location of hibernate.cfg.xml file.  
  16.      * Location should be on the classpath as Hibernate uses   
  17.      * #resourceAsStream style lookup for its configuration file.   
  18.      * The default classpath location of the hibernate config file is   
  19.      * in the default package. Use #setConfigFile() to update   
  20.      * the location of the configuration file for the current session.     
  21.      */ 
  22.     private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";  
  23. private static final ThreadLocal< Session> threadLocal = new ThreadLocal< Session>();  
  24.     private static Configuration configuration = new Configuration();  
  25.     private static org.hibernate.SessionFactory sessionFactory;  
  26.     private static String configFile = CONFIG_FILE_LOCATION;  
  27.  
  28.     private HibernateSessionFactory() {  
  29.     }  
  30.  
  31. /**  
  32.      * Returns the ThreadLocal Session instance. Lazy initialize  
  33.      * the < code>SessionFactory< /code> if needed.  
  34.      *  
  35.      * @return Session  
  36.      * @throws HibernateException  
  37.      */ 
  38.     public static Session getSession() throws HibernateException {  
  39.         Session session = (Session) threadLocal.get();  
  40.  
  41.    if (session == null || !session.isOpen()) {  
  42.     if (sessionFactory == null) {  
  43.      rebuildSessionFactory();  
  44.     }  
  45.     session = (sessionFactory != null) ? sessionFactory.openSession()  
  46.       : null;  
  47.     threadLocal.set(session);  
  48.    }  
  49.  
  50.         return session;  
  51.     }  
  52.  
  53. /**  
  54.      * Rebuild hibernate session factory  
  55.      *  
  56.      */ 
  57. public static void rebuildSessionFactory() {  
  58.    try {  
  59.     configuration.configure(configFile);  
  60.     sessionFactory = configuration.buildSessionFactory();  
  61.    } catch (Exception e) {  
  62.     System.err  
  63.       .println("%%%% Error Creating SessionFactory %%%%");  
  64.     e.printStackTrace();  
  65.    }  
  66. }  
  67.  
  68. /**  
  69.      * Close the single hibernate session instance.  
  70.      *  
  71.      * @throws HibernateException  
  72.      */ 
  73.     public static void closeSession() throws HibernateException {  
  74.         Session session = (Session) threadLocal.get();  
  75.         threadLocal.set(null);  
  76.  
  77.         if (session != null) {  
  78.             session.close();  
  79.         }  
  80.     }  
  81.  
  82. /**  
  83.      * return session factory  
  84.      *  
  85.      */ 
  86. public static org.hibernate.SessionFactory getSessionFactory() {  
  87.    return sessionFactory;  
  88. }  
  89.  
  90. /**  
  91.      * return session factory  
  92.      *  
  93.      * session factory will be rebuilded in the next call  
  94.      */ 
  95. public static void setConfigFile(String configFile) {  
  96.    HibernateSessionFactory.configFile = configFile;  
  97.    sessionFactory = null;  
  98. }  
  99.  
  100. /**  
  101.      * return hibernate configuration  
  102.      *  
  103.      */ 
  104. public static Configuration getConfiguration() {  
  105.    return configuration;  
  106. }  
  107.  
  108. }  

对工程名点鼠标右键。选择myeclipse->add hibernate capabicities。

在弹出的窗口选择中Hibernate 3.0 Core Libraries和Hibernate 3.0 Advanced Support Libraries

下面选中Copy checked Library Jars to project folder and add to build-path。点击下一步。

c.默认(hibernate cofig file),下一步。

d.选中User JDBC driver
connect url: jdbc:mysql://localhost:3306/test
Driver class: org.gjt.mm.mysql.Driver
username: root
password: ******
Dialect: mysql

e.在第一行包选择里面,选择在前面第二大步建的包如(example)。点击完成。

f.弹出的画面中 选择properties的add按钮。在Property中加入show_sql,Value中加入true。点确定

保存设置。在mappings中点add加入前面建立的Cat.hbm.xml。最后生成的hibernate.cfg.xml文件如下

  1. < ?xml version='1.0' encoding='UTF-8'?> 
  2. < !DOCTYPE hibernate-configuration PUBLIC  
  3.           "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
  4.           "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> 
  5.  
  6. < !-- Generated by MyEclipse Hibernate Tools.                   --> 
  7. < hibernate-configuration> 
  8.  
  9. < session-factory> 
  10. < property name="connection.username">root< /property> 
  11. < property name="connection.url"> 
  12.    jdbc:mysql://localhost:3306/testhibernate  
  13. < /property> 
  14. < property name="dialect"> 
  15.    org.hibernate.dialect.MySQLDialect  
  16. < /property> 
  17. < property name="connection.password">123456< /property> 
  18. < property name="connection.driver_class"> 
  19.    org.gjt.mm.mysql.Driver  
  20. < /property> 
  21. < property name="show_sql">true< /property> 
  22. < mapping resource="example/Cat.hbm.xml" /> 
  23.  
  24. < /session-factory> 
  25.  
  26. < /hibernate-configuration> 

3.测试 新建包test 在其中建立测试文件TestHibernate.java

  1. package test;  
  2.  
  3. import java.util.Iterator;  
  4. import java.util.List;  
  5. import example.*;  
  6. import example.util.*;  
  7. import org.hibernate.Session;  
  8. import org.hibernate.Transaction;  
  9.  
  10. public class TestHibernate {  
  11. Session session=null;  
  12. Transaction tx=null;  
  13. public static void main(String[] args) {  
  14. TestHibernate th=new TestHibernate();   
  15. List cl=th.getAllCats();  
  16. if(cl!=null){  
  17.    Iterator it=cl.iterator();  
  18.    while(it.hasNext()){  
  19.     Cat cat=(Cat)it.next();  
  20.     System.out.println("catID:"+cat.getCatId()+"name:"+cat.getName()+"sex:"+cat.getSex());  
  21.    }  
  22. }  
  23.     
  24.     
  25.  
  26. }  
  27. public List getAllCats(){  
  28. session=HibernateSessionFactory.getSession();  
  29. List catlist=null;  
  30. try{  
  31.    tx=session.beginTransaction();  
  32.    catlist=session.createQuery("from Cat").list();  
  33.    return catlist;  
  34. }catch(Exception ex){  
  35.    System.err.println(ex.getMessage());  
  36.    return null;  
  37. }finally{  
  38.    HibernateSessionFactory.closeSession();  
  39. }  
  40. }  
  41.  
  42. }  

这个用MyEclipse开发的Hibernate入门实例,学习起来并不算难。

【编辑推荐】

  1. 浅谈在Hibernate中使用Oracle sequence
  2. Hibernate简括
  3. hibernate的Query cache
  4. Hibernate中get()和load()的区别
  5. 浅谈Hibernate中HQL查询需要注意的几点
责任编辑:book05 来源: 百度博客
相关推荐

2009-07-14 16:55:32

MyEclipse S

2009-07-10 15:24:33

MyEclipse开发Spring

2009-07-09 17:33:39

2009-06-26 16:07:43

MyEclipse开发Hibernate程序

2009-09-27 16:21:22

Hibernate C

2009-09-23 17:05:52

Hibernate S

2013-05-20 15:42:22

2009-09-23 10:28:49

使用Hibernate

2009-09-22 10:09:21

Hibernate S

2009-09-23 15:12:41

Hibernate视图

2009-09-22 08:39:59

Hibernate F

2009-09-23 17:18:16

Hibernate S

2009-09-24 10:06:42

Hibernate实例

2009-09-07 07:38:05

Myeclipse项目

2009-03-16 15:00:16

阿里软件旺旺软件平台SaaS

2009-09-25 13:48:17

Hibernate i

2009-09-24 15:27:41

Hibernate查询

2009-09-23 11:21:32

学习Hibernate

2009-09-23 13:23:12

Hibernate M

2009-07-15 11:04:02

MyEclipse F
点赞
收藏

51CTO技术栈公众号