eclipse下手动利用hibernate连接数据库


1.下载hibernate jar包:hibernate-release-4.3.8.Final ORM,导入必要的jar包,路径为:hibernate-release-4.3.8.Final\lib\required。 包含的jar包有    10个。

2.建立新的java项目。

3.学习自己建立User Library:

(a)项目右键——build path——configure build path——add library.

(b)选择User-library,在其中新建library,命名为hibernate。

(c)在library中加入hibernate所需要的jar包(路径为:hibernate-release-4.3.8.Final\lib\required),hello world就够了,其他的还要加。

4.引入数据库的jdbc驱动。我用的mysql:mysql-connector-java-5.1.7-bin.jar

(a)创建数据库:create  database wkh;

(b)切换数据库:use wkh;

(c)创建employee表:

create table EMPLOYEE (
   id INT NOT NULL auto_increment,
   first_name VARCHAR(20) default NULL,
   last_name  VARCHAR(20) default NULL,
   salary     INT  default NULL,
   PRIMARY KEY (id)
);

5.在src目录下建立hibernate的配置文件hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
   <session-factory>
   <property name="hibernate.dialect">
      org.hibernate.dialect.MySQLDialect
   </property>
   <property name="hibernate.connection.driver_class">
      com.mysql.jdbc.Driver
   </property>

   <!-- Assume test is the database name -->
   <property name="hibernate.connection.url">
      jdbc:mysql://localhost:3306/wkh
   </property>
   <property name="hibernate.connection.username">
      root
   </property>
   <property name="hibernate.connection.password">
      root
   </property>

   <!-- List of XML mapping files -->
   <mapping resource="Employee.hbm.xml"/>

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

5、建立Employee类,Employee.java

public class Employee {
   private int id;
   private String firstName;
   private String lastName;
   private int salary;  

   public Employee() {}
   public Employee(String fname, String lname, int salary) {
      this.firstName = fname;
      this.lastName = lname;
      this.salary = salary;
   }
   public int getId() {
      return id;
   }
   public void setId( int id ) {
      this.id = id;
   }
   public String getFirstName() {
      return firstName;
   }
   public void setFirstName( String first_name ) {
      this.firstName = first_name;
   }
   public String getLastName() {
      return lastName;
   }
   public void setLastName( String last_name ) {
      this.lastName = last_name;
   }
   public int getSalary() {
      return salary;
   }
   public void setSalary( int salary ) {
      this.salary = salary;
   }
}

6、src目录下建立映射文件Employee.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

<hibernate-mapping>
   <class name="Employee" table="EMPLOYEE">
      <meta attribute="class-description">
         This class contains the employee detail.
      </meta>
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <property name="firstName" column="first_name" type="string"/>
      <property name="lastName" column="last_name" type="string"/>
      <property name="salary" column="salary" type="int"/>
   </class>
</hibernate-mapping>

7、建立测试类TestEmployee.java

import java.util.List;
import java.util.Date;
import java.util.Iterator; 

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class ManageEmployee {

   private static SessionFactory factory; 

   public static void main(String[] args) {
      try{
         factory = new Configuration().configure().buildSessionFactory();
      }catch (Throwable ex) {
         System.err.println("Failed to create sessionFactory object." + ex);
         throw new ExceptionInInitializerError(ex);
      }
      ManageEmployee ME = new ManageEmployee();

      /* Add few employee records in database */
      Integer empID1 = ME.addEmployee("Zara", "Ali", 1000);
      Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
      Integer empID3 = ME.addEmployee("John", "Paul", 10000);

      /* List down all the employees */
      ME.listEmployees();

      /* Update employee's records */
      ME.updateEmployee(empID1, 5000);

      /* Delete an employee from the database */
      ME.deleteEmployee(empID2);

      /* List down new list of the employees */
      ME.listEmployees();
   }
   /* Method to CREATE an employee in the database */
   public Integer addEmployee(String fname, String lname, int salary){
      Session session = factory.openSession();
      Transaction tx = null;
      Integer employeeID = null;
      try{
         tx = session.beginTransaction();
         Employee employee = new Employee(fname, lname, salary);
         employeeID = (Integer) session.save(employee);
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace();
      }finally {
         session.close();
      }
      return employeeID;
   }
   /* Method to  READ all the employees */
   public void listEmployees( ){
      Session session = factory.openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();
         List employees = session.createQuery("FROM Employee").list();
         for (Iterator iterator =
                           employees.iterator(); iterator.hasNext();){
            Employee employee = (Employee) iterator.next();
            System.out.print("First Name: " + employee.getFirstName());
            System.out.print("  Last Name: " + employee.getLastName());
            System.out.println("  Salary: " + employee.getSalary());
         }
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace();
      }finally {
         session.close();
      }
   }
   /* Method to UPDATE salary for an employee */
   public void updateEmployee(Integer EmployeeID, int salary ){
      Session session = factory.openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();
         Employee employee =
                    (Employee)session.get(Employee.class, EmployeeID);
         employee.setSalary( salary );
		 session.update(employee);
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace();
      }finally {
         session.close();
      }
   }
   /* Method to DELETE an employee from the records */
   public void deleteEmployee(Integer EmployeeID){
      Session session = factory.openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();
         Employee employee =
                   (Employee)session.get(Employee.class, EmployeeID);
         session.delete(employee);
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace();
      }finally {
         session.close();
      }
   }
}

8、测试、运行成功

时间: 2024-08-24 07:09:14

eclipse下手动利用hibernate连接数据库的相关文章

自己手动安装hibernate tools for eclipse(Hibernate反向工程)

自己手动安装hibernate tools for eclipse(Hibernate反向工程) 用过myeclipse的人都知道,myeclipse有集成一个hibernate的可以根据数据库表自动生成mapping映射(xml 或annotation)以及java的pojo类的工具.其实hibernate官方网站就有提供一个这样的工具,当然,现在的 名字叫做jboss tools,而hibernate tools只是其中的一小部分. 对于像我这样的对myeclipse日渐臃肿而无法接受的人而

Eclipse下的第一个Hibernate

承接上一篇:Eclipse配置SQL Explorer插件和数据库,在我们配置完Eclipse下的SQL Explore后,我就继续Hibernate了,看的是JavaEE企业应用实战这本书. 1.新建项目,建立完目录结构如下 2.下载Hibernate支持库,添加Hibernate需要的库,我选择的是Hibernate3.6.10的库,下载地址 Hibernate3.6.10库下载 还有一个不加会报错的库SLF4J SLF4J官方下载:http://www.slf4j.org/download

[Gradle] 在 Eclipse 下利用 gradle 构建系统

转载自:http://www.ibm.com/developerworks/cn/opensource/os-cn-gradle/ 构建系统时候常常要用到 Ant, Maven 等工具,对于初学者来说,它们还是过于复杂,上手还是需要时间的.本文将向读者介绍一种全新的构建项目的方式 gradle,它简单.上手快,能大大节省项目的时间和成本. 在 eclipse 下利用 gradle 构建系统 基本开发环境 操作系统:本教程使用的为 Windows Vista Enterprise, 如果您的系统是

ubuntu14.04下手动安装eclipse

ubuntu14.04下手动安装eclipse 第一步: 安装jdk 第二步: 下载eclipse,假设下载的文件文件名为eclipse.tar.gz 第三步: 解压 sudo -zxvf ./eclipse.tar.gz 会的到文件夹eclipse 第四步: 移动文件 sudo mv ./eclipse /usr/lib 第五步: 创建启动快捷方式 $ sudo gedit /usr/share/applications/eclipse.desktop 添加如下内容: [Desktop Ent

hibernate框架在eclipse下的配置方法(一)

一.ORM O:object 对象 R:Realtion 关系(关系型数据库) M:Mapping 映射 ORM:对象关系型映射 目前流行的编程语言,如Java.C# ,它们都是面向对象的编程语言,而目前主流的数据库产品例如Oracle.DB2等,依然是关系型数据库.编程语言和底层数据库发展的不协调(阻抗不匹配,例如数据库中无法直接实现存储继承.多态.封装等特征和行为),催生出了ORM框架.ORM框架可以作为面向对象语言和关系型数据库之间的桥梁. 二.Hibernate Hibernate是一个

在 Eclipse 下利用 gradle 构建系统

在 eclipse 下利用 gradle 构建系统 基本开发环境 操作系统:本教程使用的为 Windows Vista Enterprise, 如果您的系统是 Linux 的,请选择下载对应版本的其他工具,包括开发工具.Java EE 服务器.Apache Ant.SoapUI. 开发工具:Eclipse IDE for SOA Developers 版本,请到 http://www.eclipse.org/downloads/ 网站下载,当然任何版本的 eclipse 都是可以的. Java

eclipse从数据库逆向生成Hibernate实体类(eclipse中反向生成hibernate实体类+jpa注释)

eclipse从数据库逆向生成Hibernate实体类 做项目必然要先进行数据库表设计,然后根据数据库设计建立实体类(VO),这是理所当然的,但是到公司里做项目后,让我认识到,没有说既进行完数据库设计后还要再"自己"建立一变VO.意思是,在项目设计时,要么根据需求分析建立实体类,由正向生成数据库表:要么就先进行数据库表设计,再逆向生成实体类.没有说进行完任意一方的设计后再去花时间去自己匹配建立另一方的设计. 原因是: 1. 1.5倍工作量,浪费时间.(时间对公司来说很重要) 2. 无法

【框架】[Hibernate]利用Hibernate进行单表的增删改查-Web实例

转载请注明出处:http://blog.csdn.net/qq_26525215 本文源自[大学之旅_谙忆的博客] 前面两篇博客已经将Hibernate的基础知识讲解得差不多了,差不多到写实例的时候了. 本篇只用hibernate进行单表的增删改查. 应用Hibernate,对students表进行增删改查. service层和DAO层,我都是直接写实现类了(因为这里主要是演示一下Hibernate的使用),如果是开发项目,注意一定要写接口! 准备数据库: 首先准备一个students表: cr

eclipse下jdbc数据源与连接池的配置及功能简介

今天在做四则运算网页版的时候遇到了一个困惑,由于需要把每个产生的式子存进 数据库,所以就需要很多次重复的加载驱动,建立连接等操作,这样一方面写程序不方便,加大了程序量,另一方面,还有导致数据库的性能急剧下降,那么怎么解决这个问题呢? 我所学到的方法就是通过JDBC数据源和连接池的方式来解决这个问题.利用DataSource来建立数据库的连接不需要加载JDBC驱动,也不需要DriverManager类,通过向一个JNDI服务器查询来得到DataSource对象,然后调用DataSource对象的g