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

来源:互联网 发布:哈希姆家族 知乎 编辑:程序博客网 时间:2024/06/17 04:14

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、测试、运行成功



3 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 我收到了方正的提示函怎么办 淘宝刷q币单被骗了怎么办 中通快递已签收但是东西丢了怎么办 手机不版本低不支持微信下载怎么办 淘宝虚拟商品不支持7天退货怎么办 卖虚拟物品遇到恶意退款买家怎么办 淘宝极速退款后卖家拒绝退款怎么办 我的天猫积分不让换券了怎么办 微信手机话费充错了怎么办 自己进货在淘宝卖被投诉假货怎么办 京东买的电器售后后服务差怎么办 京东到家申请退款卖家不处理怎么办 天猫买了假货商品下架了怎么办 淘宝本地生活服务不能入驻了怎么办 淘宝店铺名在电脑上搜索不到怎么办 已经将退货寄回店家硬说没有怎么办 微信申诉账号短信验证失败怎么办 京东账号换手机号收不到短信怎么办 我的手机收不到短信通知怎么办? 淘宝卖家发货物流单号写错了怎么办 商铺买东西不给调换大小怎么办 圆通快递物流信息一直没更新怎么办 中通快递三天没更新物流信息怎么办 快递已经到了物流信息不更新怎么办 天天快递查询不更新物流信息怎么办 买车下个月分期全部付清怎么办手续 天猫客服介入以后商家不退款怎么办 淘宝上买代购奢侈品买到假货怎么办 淘宝退货卖家收到货拒绝退款怎么办 没收到货但申请了退货退款怎么办 小米商城预约中德手机没货怎么办 电脑用百度网盘下载速度超慢怎么办 ios网盘下载速度太慢怎么办 小米手机4x卡机了怎么办 小米手机4x屏幕点不动了怎么办 苹果手机连接u盘没反应怎么办 苹果官网储蓄卡分期额度不够怎么办 京东买东西发票信息填写错了怎么办 华为v9手机激活密码忘了怎么办 公司报销发票纸质的丢了怎么办 在京东上买的小天才手表坏了怎么办