当前位置: 首页 > news >正文

MyEclipse环境下Hibernate入门实例

  首先在MyEclipse下创建一个WebProject,项目命名为demo,然后【MyEclipse->project capablities->add hibernate capabilities】,跟着向导操作,最后会生成一个hibernate.cfg.xml和一个HibernateSessionFactory.java文件。在向导中要求填写一些数据库连接的配置信息以及HibernateSessionFactory存放的包,配置信息我们可以参考下面的hibernate.cfg.xml来填写,而HibernateSessionFactory我们放在com.demo.hibernate.util这个包里面。

1.HibernateSessionFactory.java

View Code
package com.demo.hibernate.util;

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

/**
 * Configures and provides access to Hibernate sessions, tied to the
 * current thread of execution.  Follows the Thread Local Session
 * pattern, see {@link http://hibernate.org/42.html }.
 */
public class HibernateSessionFactory {

    /** 
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses  
     * #resourceAsStream style lookup for its configuration file. 
     * The default classpath location of the hibernate config file is 
     * in the default package. Use #setConfigFile() to update 
     * the location of the configuration file for the current session.   
     */
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private  static Configuration configuration = new Configuration();    
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

    static {
        try {
            configuration.configure(configFile);
            sessionFactory = configuration.buildSessionFactory();
        } catch (Exception e) {
            System.err
                    .println("%%%% Error Creating SessionFactory %%%%");
            e.printStackTrace();
        }
    }
    private HibernateSessionFactory() {
    }
    
    /**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();

        if (session == null || !session.isOpen()) {
            if (sessionFactory == null) {
                rebuildSessionFactory();
            }
            session = (sessionFactory != null) ? sessionFactory.openSession()
                    : null;
            threadLocal.set(session);
        }

        return session;
    }

    /**
     *  Rebuild hibernate session factory
     *
     */
    public static void rebuildSessionFactory() {
        try {
            configuration.configure(configFile);
            sessionFactory = configuration.buildSessionFactory();
        } catch (Exception e) {
            System.err
                    .println("%%%% Error Creating SessionFactory %%%%");
            e.printStackTrace();
        }
    }

    /**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

    /**
     *  return session factory
     *
     */
    public static org.hibernate.SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    /**
     *  return session factory
     *
     *    session factory will be rebuilded in the next call
     */
    public static void setConfigFile(String configFile) {
        HibernateSessionFactory.configFile = configFile;
        sessionFactory = null;
    }

    /**
     *  return hibernate configuration
     *
     */
    public static Configuration getConfiguration() {
        return configuration;
    }

}

2.hibernate.cfg.xml(在src目录下)

View Code
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

    <session-factory>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- 
         <property name="show_sql">true</property>
         -->
       
        <!-- 连接字符串 -->
        <property name="connection.url">jdbc:mysql://localhost:3306/demo</property>                                         
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <!-- 数据库驱动 -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <!-- 映射文件,是后来添加的,不是想到自动生成的 -->
        <mapping resource="com/demo/hibernate/beans/User.hbm.xml"/>
    </session-factory>

</hibernate-configuration>

3.创建数据库

在MySql中创建一个名为demo的数据库,然后将下面的代码另存为“*.sql”文件,再将该文件导入数据库。当然也可直接通过类似navicat的数据库UI来创建数据库。

DROP TABLE IF EXISTS `user`; 
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) DEFAULT NULL,
`password` varchar(50) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

4. *.hbm.xml映射文件

我们知道Hibernate是用户将对象与数据库表进行映射,那么下面编写映射文件:User.hbm.xml(在com.demo.hibernate.beans包中),从代码中我们可以看到name与column属性,name表示User类中的属性,column表示数据库表user中的字段名称。类中的属性和表中的字段可以不相同,如果相同的话column可以省略。比如下面的column="username" column="password" 可以省略不写。像<property name="email" /> 一样。

View Code
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 
<hibernate-mapping package="com.demo.hibernate.beans">
 -->

<hibernate-mapping>
    <class name="com.demo.hibernate.beans.User" table="user">
        <id name="id" column="ID" >
            <generator class="native" />
        </id>
        <property name="username" column="username" />
        <property name="password" column="password" />
        <property name="email"/>

    </class>

</hibernate-mapping>

5.编写持久化类User.java,

这里我们不一定要求User类中的属性与表user的字段相同,不过如果相同则可以省去一些步骤,就是前面提到的*.hbm.xml文件中的一些字段可以省略。

View Code
package com.demo.hibernate.beans;

public class User {
    private int id;
    private String username;
    private String password;
    private String email;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
}

6.编写DAO类UserDAO.java

DAO就是Database Access Objects,数据访问对象的英文缩写。顾名思义对数据库操作的方法都写在这个类中,就比如代码中getUser()方法就是需要读取数据库信息。不过hibernate因为通过映射的方法不直接使用SQL语句操纵数据库,而是引入了HQL语言。最明显的一点是:

  Query query=session.createQuery("from User where username=?");

这里from User中的User是指User类而不是user表,HQL直接对对象操作。

View Code
package com.demo.hibernate.dao;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.demo.hibernate.beans.User;
import com.demo.hibernate.util.HibernateSessionFactory;
public class UserDAO {
    
    public User getUser(String username) throws HibernateException{
        Session session=null;
        Transaction tx=null;
        User user=null;
        try
        {
            session=HibernateSessionFactory.getSession();
            tx=session.beginTransaction();
            Query query=session.createQuery("from User where username=?");
            query.setString(0, username.trim());
            user=(User)query.uniqueResult();
            query=null;
            //session.save(user);
            tx.commit();
            //session.close();
        }
//        catch(HibernateException e)
//        {
//            throw e;
//        }
//        finally
//        {
//            if(tx!=null)
//            {
//                tx.rollback();
//            }
//            HibernateSessionFactory.closeSession();
//        }
        catch(HibernateException e)
        {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        return user;
    }
}

7.编写Service类并运行(含有主函数的类)

View Code
package com.demo.hibernate.service;

import com.demo.hibernate.beans.User;
import com.demo.hibernate.dao.UserDAO;

public class UserService {

    public boolean valid(String username,String password)
    { 
        UserDAO test=new UserDAO();
        User user=test.getUser("admin");
        if(user.getPassword().equals(password))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    
    public static void main(String args[])
    {
        UserService service=new UserService();
        boolean login=service.valid("admin", "admin");
        System.out.println("验证结果"+login);
    }
}

8.显示结果:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
验证结果:true

 

 

 

 

转载于:https://www.cnblogs.com/xwdreamer/archive/2010/09/23/2297087.html

相关文章:

  • 彻底弄懂CSS盒子模式
  • Linux启动流程
  • 按类别DF特征词选择算法
  • Dell Insprion 6400坏
  • Makefile相关资料
  • 浅谈角色与权限
  • Exchange2007如何给邮件通讯组Distribution Group设置Send As与Behalf 权限
  • 错误与修正
  • 转: CRT检测内存泄漏技巧以及注意问题
  • RIP协议拓扑结构变化-收敛
  • Redhat 下不重启系统发现LUN
  • asp.net导出数据到EXCEL简单有效
  • RedHat 6.0环境下Oracle 8.0.5的安装
  • Windows 7下用无线网卡自建热点共享Internet访问
  • Oracle发布更新使数据库性能优化达到75%
  • Angular2开发踩坑系列-生产环境编译
  • const let
  • js中forEach回调同异步问题
  • laravel 用artisan创建自己的模板
  • Material Design
  • SQLServer之创建显式事务
  • VuePress 静态网站生成
  • vue自定义指令实现v-tap插件
  • webpack+react项目初体验——记录我的webpack环境配置
  • 第13期 DApp 榜单 :来,吃我这波安利
  • 扫描识别控件Dynamic Web TWAIN v12.2发布,改进SSL证书
  • 通过npm或yarn自动生成vue组件
  • 异常机制详解
  • 在Mac OS X上安装 Ruby运行环境
  • 终端用户监控:真实用户监控还是模拟监控?
  • 最近的计划
  • NLPIR智能语义技术让大数据挖掘更简单
  • ​VRRP 虚拟路由冗余协议(华为)
  • #define 用法
  • #git 撤消对文件的更改
  • #Java第九次作业--输入输出流和文件操作
  • #预处理和函数的对比以及条件编译
  • ${ }的特别功能
  • (145)光线追踪距离场柔和阴影
  • (Matlab)使用竞争神经网络实现数据聚类
  • (Mirage系列之二)VMware Horizon Mirage的经典用户用例及真实案例分析
  • (论文阅读31/100)Stacked hourglass networks for human pose estimation
  • (三) diretfbrc详解
  • (四)库存超卖案例实战——优化redis分布式锁
  • (一)appium-desktop定位元素原理
  • (一)python发送HTTP 请求的两种方式(get和post )
  • (一)UDP基本编程步骤
  • (转)jQuery 基础
  • ***详解账号泄露:全球约1亿用户已泄露
  • **Java有哪些悲观锁的实现_乐观锁、悲观锁、Redis分布式锁和Zookeeper分布式锁的实现以及流程原理...
  • ... fatal error LINK1120:1个无法解析的外部命令 的解决办法
  • .[backups@airmail.cc].faust勒索病毒的最新威胁:如何恢复您的数据?
  • .NET CLR Hosting 简介
  • .NET Remoting学习笔记(三)信道
  • .Net(C#)常用转换byte转uint32、byte转float等