`
wagnn
  • 浏览: 7158 次
最近访客 更多访客>>
社区版块
存档分类
最新评论

Eclipse下Hibernate入门

阅读更多
Eclipse下Hibernate入门

最近boss让做项目,借机学习了一下Hibernate,小有收获。
     hiberante是对数据库持久层访问的一种机制,hibernate的应用可以使程序员将重点放到业务逻辑的实现上。hibernate的原理是将数据库结构封装,使程序员可以像使用普通对象一样调用数据库的相关接口,从实现数据库的相关操作。
    
     由于Exadel基于eclipse集成了Hibernate,并且方便易用所以我选用
     Exadel+Mysql
     还需要hibernate3.jar http://www.hibernate.org/
             mysql-connector http://dev.mysql.com/downloads/
   
       在Mysql中新建test数据库(Mysql其实有个空的test数据库),然后新建下面的Table

create table user (
id int(10) not null auto_increment primary key,
name varchar(20) not null,
password varchar(20) not null,
email varchar(50),
address varchar(100)
)type=innodb;




新建Java Project,将Mysql_Driver,Hibernate两个user library添加到该工程的java build path中。

新建与数据表对应的POJO类:User和Contact

/**
*

*/
package com.user;

/**
* @author lzy
*
*/
public class User{
    private Integer id;
    private String name;
    private String password;
    private Contact contact;
   

/**
  * @return Returns the id.
  */
public Integer getId() {
  return id;
}
/**
  * @param id The id to set.
  */
public void setId(Integer id) {
  this.id = id;
}
/**
  * @return Returns the name.
  */
public String getName() {
  return name;
}
/**
  * @param name The name to set.
  */
public void setName(String name) {
  this.name = name;
}
/**
  * @return Returns the password.
  */
public String getPassword() {
  return password;
}
/**
  * @param password The password to set.
  */
public void setPassword(String password) {
  this.password = password;
}
/**
  * @return Returns the contact.
  */
public Contact getContact() {
  return contact;
}
/**
  * @param contact The contact to set.
  */
public void setContact(Contact contact) {
  this.contact = contact;
}
   
   
}
/**
*
*/
package com.user;

/**
* @author lzy
*
*/
public class Contact {
private String email;
    private String address;

/**
  * @return Returns the address.
  */
public String getAddress() {
  return address;
}
/**
  * @param address The address to set.
  */
public void setAddress(String address) {
  this.address = address;
}
/**
  * @return Returns the email.
  */
public String getEmail() {
  return email;
}
/**
  * @param email The email to set.
  */
public void setEmail(String email) {
  this.email = email;
}
}

添加Hibernate支持,这时系统会要求输入一些信息,按提示即可
完成后系统自动生成hibernate.cfg.xml,User.hbm.xml
映射文件必须稍作修改。

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-3.0.dtd">

<hibernate-configuration>
    <session-factory >

  <!-- local connection properties -->
  <property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.username"></property>
  <property name="hibernate.connection.password"></property>
  <!-- property name="hibernate.connection.pool_size"></property -->

  <!-- dialect for MySQL -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <property name="hibernate.show_sql">True</property>
        <property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
     <mapping resource="User.hbm.xml"/>


    </session-factory>
</hibernate-configuration>

User.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

<hibernate-mapping package="com.user">
<class
  name="User"
  table="user"
>
  <id
   name="Id"
   type="integer"
   column="id"
  >
   <generator class="native"/>
  </id>

  <property
   name="Name"
   column="name"
   type="string"
   not-null="true"
   length="20"
  />
  <property
   name="Password"
   column="password"
   type="string"
   not-null="true"
   length="20"
  />
  <component name="Contact" class="Contact">
   <property
   name="Email"
   column="email"
   type="string"
   not-null="false"
   length="50"
  />
  <property
   name="Address"
   column="address"
   type="string"
   not-null="false"
   length="100"
  />
  </component>
 


</class>
</hibernate-mapping>



3.测试
添加一个测试类:HibernateTest

package com.user;

import java.util.List;
import java.util.ListIterator;

import org.hibernate.*;
import org.hibernate.cfg.*;

public class HibernateTest {
    public static void main(String[] args) throws HibernateException {
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
       
        //
        //testInsert(sessionFactory);
       
        //
        testQuery(sessionFactory);
       
         
        sessionFactory.close();
       
    }
    public static void testInsert( SessionFactory sessionFactory )throws HibernateException {
    
      Session session = sessionFactory.openSession();
        Transaction tx= session.beginTransaction();
        User user = new User();
        Contact contact=new Contact();
        contact.setEmail("email");
        contact.setAddress("address");
       
        user.setName("caterpillar");
        user.setPassword("password");
        user.setContact(contact);
       
        session.save(user);
        tx.commit();
        session.close();
        System.out.println("OK!");
   }
   
    public static void testQuery( SessionFactory sessionFactory )throws HibernateException {
    
     Session session = sessionFactory.openSession();
        Transaction tx= session.beginTransaction();
        User user = new User();
        Contact contact=new Contact();
                 
        Query query=session.createQuery("from User as user");
        //query.setCharacter(1, 'M');
        List names =query.list();
        for(ListIterator it=names.listIterator();it.hasNext();){
           user= (User)it.next();
           System.out.println("Id: " + user.getId());
            System.out.println("name: " + user.getName());
            System.out.println("password: " + user.getPassword());
            if(user.getContact()!=null){
            
             if(user.getContact().getEmail()!=null){
              System.out.println("Email: " + user.getContact().getEmail());
             }
             if(user.getContact().getAddress()!=null){
              System.out.println("Address: " + user.getContact().getAddress());
               
             }
            }
           
           
           
        }
         
      
        tx.commit();
        session.close();
    
    }
}
分享到:
评论

相关推荐

    Hibernate入门案例源码

    【Hibernate入门案例源码】是针对初学者设计的一份教程,旨在帮助理解并掌握Java持久化框架Hibernate的基础应用。Hibernate是一个强大的ORM(对象关系映射)框架,它简化了数据库与Java对象之间的交互,使开发者可以...

    Eclipse快速上手Hibernate之入门实例

    ### Eclipse快速上手Hibernate之入门实例详解 #### 引言 Hibernate是一个强大的对象关系映射(ORM)框架,用于简化数据库操作,使开发者能够用面向对象的方式处理数据库数据,而无需编写复杂的SQL语句。本篇文章将...

    eclipse 下的hibernate tools

    标题 "Eclipse 下的 Hibernate Tools" 提供了一个关键线索,那就是我们要探讨的是如何在流行的 Java 开发环境 Eclipse 中使用 Hibernate 工具。Hibernate 是一个强大的对象关系映射(ORM)框架,它允许开发者以面向...

    struts+hibernate入门实例(eclipse版)

    ### Struts + Hibernate 入门实例(Eclipse 版) #### 一、开发环境搭建 在本章节中,作者朱千平将引导我们完成开发环境的搭建,包括以下几个步骤: 1. **下载安装Eclipse**: Eclipse 是一个开源的集成开发环境...

    利用Eclipse开发Hibernate应用.pdf

    在Eclipse中创建Java项目时,需要将Hibernate库(包括hibernate2.jar和lib目录下的所有jar文件)以及MySQL JDBC驱动(如mysql-connector-java-3.0.14-production-bin.jar)添加到项目的类路径中。 然后,通过...

    Struts+Hibernate入门实例(eclipse版)

    在"Struts+Hibernate入门实例(eclipse版).doc"文档中,应该详细阐述了以上步骤的实施细节,包括每一步的具体配置和代码示例。学习这个实例,开发者将能更好地理解如何在实际项目中结合使用Struts和Hibernate,提升...

    hibernate入门实例操作步骤

    本篇将详细介绍Hibernate入门实例的操作步骤,包括手工配置文件和利用Eclipse自动生成配置的两种方法。 **一、手工配置文件** 1. **环境准备** 在开始前,确保已安装JDK、Eclipse IDE,并在项目中引入Hibernate的...

    Hibernate入门实例源代码,eclipse工程,可直接运行。

    **Hibernate入门实例源代码** Hibernate 是一款开源的对象关系映射(ORM)框架,它简化了Java应用程序对数据库的访问。这个压缩包包含了使用Hibernate进行入门学习的源代码,且整个项目是一个Eclipse工程,可以直接...

    myeclipse下hibernate入门

    ### MyEclipse 下 Hibernate 入门知识点解析 #### 一、概述 本文将详细介绍如何在 MyEclipse 环境下进行 Hibernate 的基础配置及应用。对于初学者来说,通过本教程可以快速掌握 Hibernate 在实际项目中的使用方法...

    myeclipse下hibernate入门实例介绍

    ### MyEclipse 下 Hibernate 入门实例详解 #### 一、引言 本文将详细介绍如何在 MyEclipse 环境下使用 Hibernate 进行一个简单的数据库操作实例。该实例将涵盖从环境搭建到实现增删改查的基本过程。通过这个实例,...

    Struts+Hibernate入门实例(eclipse版).doc

    ### Struts+Hibernate入门实例(eclipse版)知识点详解 #### 一、前言与背景介绍 随着企业级应用的发展,J2EE 和 .NET 成为了两大主流技术栈。本文主要聚焦于 J2EE 方向,特别是其中两个重要的开源框架:Hibernate ...

    在Eclipse上创建Hibernate实例

    使用MyEclipse创建hibernate实例入门教程

    hibernate系列(一)hibernate入门

    **hibernate系列(一)hibernate入门** 在Java世界中,ORM(Object-Relational Mapping,对象关系映射)框架是连接数据库与应用程序的重要桥梁,它将数据库中的数据与程序中的对象进行关联,使得开发者可以使用面向...

    Hibernate从入门到精通1

    Hibernate从入门到精通1

    最简单的Hibernate入门简介

    然而,大多数的Hibernate入门介绍都加入了很多非Hibernate的东西,比:Tomcat,Eclipse,Log4J,Struts,XDoclet,甚至JBoss。这容易让人产生Hibernate复杂难懂的误解,特别是打击了初学者的积极性。在这篇文章将不涉及...

    Eclipse从入门到精通(第2版).pdf

    本书为《Eclipse从入门到精通》一书的全新改版。本书以最新的Eclipse 3.2作为写作版本。全书分为5篇:起步篇介绍了Eclipse及相关插件的安装,还介绍了一些Eclipse开发环境的基本使用技巧;SWT/JFace篇详细介绍了SWT...

    02_传智播客hibernate教程_hibernate入门案例的细节分析

    【标题】:“02_传智播客hibernate教程_hibernate入门案例的细节分析” 在本教程中,我们将深入探讨Hibernate,一个流行的Java对象关系映射(ORM)框架,它简化了数据库操作,使开发者可以更加专注于业务逻辑而不是...

    MyEclipse+Hibernate快速入门中文版

    ### MyEclipse+Hibernate快速入门知识点详解 #### 一、前言 本文档旨在通过一个简单易懂的方式,介绍如何在MyEclipse环境下配置并使用Hibernate框架。这是一份非常适合初学者使用的指南,特别是对于那些希望快速...

    Java开源项目Hibernate快速入门

    然而,大多数的Hibernate入门介绍都加入了很多非Hibernate的东西,比如: Tomcat, Eclipse, Log4J,Struts, XDoclet, 甚至JBoss。这容易让人产生Hibernate复杂难懂的误解,特别是打击了初学者的积极性。在本文中将不...

Global site tag (gtag.js) - Google Analytics