Hibernate框架入门记录(基于eclipse)

1.实现Hibernate框架的创建和基本使用,通过Java测试程序输出用户表信息。运行结果截图贴在答案区,项目源码(包括SQL文件)以附件形式提交。
基本步骤如下:

1.创建一个Web/Java项目
2. 配置DataBase Driver(Database Explorer)
3. (ME8.5)右键选择【MyEclipse】=》【Add Hibernate Cap…】添加Hibernate框架支持
4. (Database Explorer)逆向工程生成PO类、DAO类以及hbm.xml文件
5. 修改hibernate.cfg.xml文件,添加必要属性(可省)
6. 编写测试代码,对数据库表记录进行查询操作。

1.利用创建数据库(名为hibernate)和表(名为user)
在这里插入图片描述
在这里插入图片描述
2.创建一个Web/Java项目
在项目lib文件夹中导入
hibernate所需jar包及
(hibernate-release-5.2.14.Final->lib->required里全部jar包)
数据库连接jar包并进行Build Path
(mysql-connector-java-8.0.11.jar)
参考此篇博客
jar包搜索下载可以去此网站看看
在这里插入图片描述
3.创建mysql逆向工程
参考学习自博客
(本博客写的比较粗略,可参考上述链接博客较为详细)
连接数据库
菜单栏的window->show View->data Source Explorer
控制台出现data Source Explorer,右击里面的Database Connections->new,选择Mysql,点击next
在这里插入图片描述

在这里插入图片描述
添加自己电脑上所下载的mysql连接包
添加自己电脑上所下载的mysql连接包
在这里插入图片描述

上图1中的配置信息
Database:创建的数据库名
URL:jdbc:mysql://localhost:3306/hibernate?useSSL=false&serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8
User name:一般为root(自己设置的自己应该知道)
Password:自己设置数据库密码的自己知道

安装eclipse的插件
此博客介绍较为详细
我的是先在eclipse中的和help->Check for updates更新版本然后利用博客中的第二种中链接方法安装JBoss Tools插件的最新版本(安装时间较长,安装也有失败,安装了几次才成功)
逆向工程从数据库中的表生成实体类
下载安装完成后会要求重新启动eclipse,重启后点开eclipse菜单栏window ->Perspective->Customize Perspective
在这里插入图片描述
菜单栏window->show View ->other->hibernate configurations
在这里插入图片描述
控制台出现的新的窗口hibernate configurations,空白处右键,选择Add Configuration在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
下图
1中报错修改为(原因参考此博客

<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate?useSSL=false&amp;serverTimezone=GMT%2B8&amp;useUnicode=true&amp;characterEncoding=utf8</property>

2刚才忘记添加数据库方言这里补上

<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
右键Hibernate Code Generation->New Configuration
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述在这里插入图片描述
对数据库表记录进行查询操作
参考此篇博客
在这里插入图片描述
HibernateSessionFactory.java
文件参考此博客

package com.lx.test;

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 final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
  private static org.hibernate.SessionFactory sessionFactory;

  private static Configuration configuration = new Configuration();
  private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
  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;
  }

}

hibernate.cfg.xml添加配置映射文件
在这里插入图片描述
show.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%@ page import="java.util.List"%>
<%@ page import="java.util.ArrayList"%>

<%@page import="com.lx.bean.User"%>
<%@page import="org.hibernate.Query"%>
<%@page import="com.lx.bean.HibernateSessionFactory"%>
<%@page import="org.hibernate.Session"%>
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<center>
从Mysql数据库读取user表
    <table border="1" cellspacing="0" cellpadding="4">
        <tr>
            <td>Userid</td>      
            <td>Password</td>    
            <td>Realname</td>      
            <td>Email</td>
            <td>Admin</td>
         </tr>
          <%
              Session ss = HibernateSessionFactory.getSession();  //建立Session对象ss      
              ss.beginTransaction();                              //打开Transaction
              Query query=ss.createQuery("from User");         //调用函数Query查询        
              List<User>userList = new ArrayList<User>();  //将查询的结果放到List表中
              userList = query.list(); 
              for(int i = 0 ;i < userList.size();i++){
           %>
 
          <tr>
            <td><%=userList.get(i).getUserid()%></td>      
            <td><%=userList.get(i).getPassword()%></td>    
            <td><%=userList.get(i).getRealname()%></td>      
            <td><%=userList.get(i).getEmail()%></td>
            <td><%=userList.get(i).getAdmin()%></td>
         </tr>
         <%
            }
            ss.close();       //关闭Transaction
         %>
     </table>
</center>

</body>
</html>

运行结果
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值