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连接包
上图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&serverTimezone=GMT%2B8&useUnicode=true&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>
运行结果