Hibernate 的自动建表技术,本例简单,只为通过自动建表技术体现HIbernate的运行原理以及配置过程。
一:新建一个Java web 应用
1.导入servlet的jar包和jsp-api的jar包。
2.将数据库连接器的jar包导入。
3.最后导入hibernate的jar包(可以通过idea自动下载)。官网下载
二:代码编写:
1》index.jsp
<%--
Created by IntelliJ IDEA.
User: kekekekekeshi
Date: 17-7-13
Time: 下午3:14
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>注册</title>
</head>
<body>
<form action="CustomerServlet" method="post" onsubmit="return save();">
<table align="center" border="0" cellpadding="3" cellspacing="1" width="500">
<tr>
<td align="right">用 户 名:</td>
<td><input id="username" name="username" type="text" class="box1"></td>
</tr>
<tr>
<td align="right">密 码:</td>
<td><input id="password" name="password" type="password" class="box1"></td>
</tr>
<tr>
<td align="right">确认密码:</td>
<td><input id="repassword" name="repassword" type="password" class="box1"></td>
</tr>
<tr>
<td align="right">年 龄:</td>
<td><input id="age" name="age" type="text" class="box1"></td>
</tr>
<tr>
<td align="right">性 别:</td>
<td>
<input name="sex" type="radio" value="1" checked="checked">男
<input type="radio" name="sex" value="0">女
</td>
</tr>
<tr>
<td align="right">描 述:</td>
<td><textarea name="description" cols="30" rows="5"></textarea> </td>
</tr>
<tr>
<td colspan="2" align="center" height="50">
<input type="submit" value="注册">
<input type="reset" value="重置">
</td>
</tr>
</table>
</form>
</body>
</html>
2》result.jsp
<%--
Created by IntelliJ IDEA.
User: kekekekekeshi
Date: 17-7-13
Time: 下午4:46
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>信息</title>
</head>
<body>
${requestScope.info}
</body>
</html>
3》src/me/hibernate/util/HibernateUtil.java
package me.hibernate.util;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
/**
* Created by kekekekekeshi on 17-7-13.
*/
public class HibernateUtil {
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static SessionFactory sessionFactory = null;
static {
try{
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.configure()
.build();
Metadata metadata = new MetadataSources(serviceRegistry)
.getMetadataBuilder()
.applyImplicitNamingStrategy(ImplicitNamingStrategyComponentPathImpl.INSTANCE)
.build();
sessionFactory = metadata
.getSessionFactoryBuilder()
.build();
}catch (Exception e){
System.err.println("创建会话工厂失败!");
e.printStackTrace();
}
}
/*
* 获取session
* @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;
}
/*
* 重建工厂
* */
public static void rebuildSessionFactory(){
try{
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.configure()
.build();
Metadata metadata = new MetadataSources(serviceRegistry)
.getMetadataBuilder()
.applyImplicitNamingStrategy(ImplicitNamingStrategyComponentPathImpl.INSTANCE)
.build();
sessionFactory = metadata
.getSessionFactoryBuilder()
.build();
}catch (Exception e){
System.err.println("创建会话工厂失败!");
e.printStackTrace();
}
}
/*
* 获取SessionFactory对象
* @return SessionFactory
* */
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
/*
* 关闭session
*
* @throws HibernateException
* */
public static void closeSession()throws HibernateException{
Session session = (Session)threadLocal.get();
threadLocal.set(null);
if(session!=null){
session.close();
}
}
}
4》src/me/hibernate/Customer.java
package me.hibernate;
/**
* Created by kekekekekeshi on 17-7-13.
*/
public class Customer {
private Integer id;
private String username;
private String password;
private boolean sex;
private Integer age;
private String description;
public void setSex(boolean sex) {
this.sex = sex;
}
public void setDescription(String description) {
this.description = description;
}
public void setAge(Integer age) {
this.age = age;
}
public void setPassword(String password) {
this.password = password;
}
public void setUsername(String username) {
this.username = username;
}
public void setId(Integer id) {
this.id = id;
}
public String getDescription() {
return description;
}
public Integer getAge() {
return age;
}
public String getPassword() {
return password;
}
public String getUsername() {
return username;
}
public Integer getId() {
return id;
}
public boolean getSex(){
return sex;
}
}
5》src/me/hibernate/Customer.hbm.xml
<?xml version="1.0" encoding="UTF-8" ?>
<hibernate-mapping xmlns="http://www.hibernate.org/xsd/hibernate-mapping">
<class name="me.hibernate.Customer" table="tb_customer">
<id name="id">
<generator class="native"/>
</id>
<property name="username" length="50" not-null="true"/>
<property name="password" length="50" not-null="true"/>
<property name="age"/>
<property name="sex"/>
<property name="description"/>
</class>
</hibernate-mapping>
6》src/hibernate.cfg.xmll
<?xml version="1.0" encoding="UTF-8" ?>
<hibernate-configuration>
<session-factory>
<property name="hibernate.hbm2ddl.auto">create</property>
<mapping resource="me/hibernate/Customer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
7》src/me/hibernate/dialect/MySQLDialect.java
package me.hibernate.dialect;
/**
* Created by kekekekekeshi on 17-7-13.
*/
public class MySQLDialect extends org.hibernate.dialect.MySQLDialect {
@Override
public String getTableTypeString() {
return "ENGINE=MyISAM";
}
}
之所以去重写Dialect是因为jar包可能老了点,而数据库新了,造成了新数据库建表时需要ENGINE而hibernate却给出了个TYPE,会造成建表不成功。
8》src/hibernate.properties
#指定数据库使用的驱动类
hibernate.connection.driver_class = com.mysql.jdbc.Driver
#指定数据库连接串
hibernate.connection.url = jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=true
#指定数据库连接的用户名
hibernate.connection.username = root
#指定数据库连接的密码
hibernate.connection.password = SQL_KEY
#指定数据库使用的方言
hibernate.dialect = me.hibernate.dialect.MySQLDialect
#指定是否打印SQL语句
hibernate.show_sql=true
9》src/me/servlet/CustomerServlet.java
package me.servlet;
import me.hibernate.Customer;
import me.hibernate.util.*;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by kekekekekeshi on 17-7-13.
*/
@WebServlet(name = "CustomerServlet")
public class CustomerServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
String username = request.getParameter("username");
String password = request.getParameter("password");
String sex = request.getParameter("sex");
String age = request.getParameter("age");
String description = request.getParameter("description");
System.out.println(username+','+password+','+sex+','+age+','+description+'.');
if(username!=null&&password!=null){
Customer customer = new Customer();
customer.setUsername(username);
customer.setPassword(password);
if(sex!=null){
customer.setSex(sex.equals('1')?true:false);
}
customer.setAge(Integer.parseInt(age));
customer.setDescription(description);
saveCustomer(customer);
request.setAttribute("info","恭喜,注册成功!");
}
request.getRequestDispatcher("result.jsp").forward(request,response);
}
private void saveCustomer(Customer customer) {
Session session = null;
try{
session = HibernateUtil.getSession();
session.beginTransaction();
session.save(customer);
session.getTransaction().commit();
}catch (Exception e){
e.printStackTrace();
session.getTransaction().rollback();
}finally {
HibernateUtil.closeSession();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
10》配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>CustomerServlet</servlet-name>
<servlet-class>me.servlet.CustomerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CustomerServlet</servlet-name>
<url-pattern>/CustomerServlet</url-pattern>
</servlet-mapping>
</web-app>
三:看看运行结果:
1.
2.
3.
ok!成功了!