Web应用中使用hibernate
web项目中使用Hibernate
首先创建一个gradle项目 web-application-with-hibernate, 导入依赖
testCompile group: 'junit', name: 'junit', version: '4.12'
// https://mvnrepository.com/artifact/org.hibernate/hibernate-core
compile group: 'org.hibernate', name: 'hibernate-core', version: '5.2.12.Final'
// https://mvnrepository.com/artifact/mysql/mysql-connector-java
compile group: 'mysql', name: 'mysql-connector-java', version: '8.0.8-dmr'
创建一个用户注册的静态页面 index.jsp
<form action="" method="post">
<h2>用户注册表</h2>
<hr>
Name:<input type="text" name="name"/><br>
<br>Password: <input type="password" name="password"/><br>
<br>Email: <input type="email" name="email"/><br>
<br><input type="submit" value="注册"/>
</form>
创建一个User实体类用来存储信息
package com.demo.Model;
public class User {
private int id;
private String name;
private String password;
private String email;
//GETTER AND SETTER
//...
}
然后创建hibernate映射文件User.hbm.xml
<?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>
<class name="com.demo.Model.User" table="tb_user">
<id name="id">
<generator class="increment"/>
</id>
<property name="name"/>
<property name="email"/>
</class>
</hibernate-mapping>
我们创建操作持久化层测试类UserDao
package com.demo.Dao;
import com.demo.Model.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class UserDao {
public static int save(User u) {
int i = 0;
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure().build();
// 2. 根据服务注册类创建一个元数据资源集,同时构建元数据并生成应用一般唯一的的session工厂
SessionFactory factory = new MetadataSources(registry)
.buildMetadata().buildSessionFactory();
Session session = factory.openSession();
Transaction t = session.beginTransaction();
i = (int) session.save(u);
t.commit();
session.close();
System.out.println(u.getName());
return i;
}
}
创建数据库
CREATE TABLE `tb_user` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(32) NOT NULL DEFAULT '',
`password` varchar(32) NOT NULL DEFAULT '',
`email` varchar(32) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
hibernate配置文件
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:mysql://localhost:3306/Spring</property>
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.username">root</property>
<property name="connection.password">19970819wy</property>
<!-- DB schema will be updated if needed -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="mapping/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
修改持久化层configuration
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure("hibernate/hibernate.cfg.xml").build();
展示用户信息的jsp页面
<%@ page import="com.demo.Dao.UserDao" %><%--
Created by IntelliJ IDEA.
User: wangyu
Date: 02/11/2017
Time: 5:00 PM
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
int i = UserDao.save(obj);
if (i > 0) {
out.print("You are successfully registered");
}
%>
修改index页面的action
运行结果
hibernate生成器类
id元素的<generator>
子元素用于生成持久化类的对象的唯一标识符。 Hibernate框架中定义了许多生成器类。
- assigned
- increment
- sequence
- hilo
- native
- identity
- seqhilo
- uuid
- guid
- select
- foreign
- sequence-identity
assigned
默认的生成策略,由应用程序为对象分配ID
<hibernate-mapping>
<class ...>
<id ...>
<generator class="assigned"></generator>
</id>
.....
</class>
</hibernate-mapping>
increment
当没有其他进程讲数据插入此表时,才会生成唯一的ID,它生成short、int或long类型的数据
第一个生成的数据通常为1,然后每次递增为1
<hibernate-mapping>
<class ...>
<id ...>
<generator class="increment"></generator>
</id>
.....
</class>
</hibernate-mapping>
sequence
它使用数据库的顺序序列。如果没有定义序列,它会自动创建一个序列。 在Oracle数据库的情况下,它将创建一个名为HIBERNATE_SEQUENCE的序列。 在Oracle,DB2,SAP DB,Postgre SQL或McKoi的情况下,它使用序列(sequence),但在interbase中使用生成器。
<id ...>
<generator class="sequence"></generator>
</id>
要定义自己的序列,使用param的name
<id ...>
<generator class="sequence">
<param name="sequence">your_sequence_name</param>
</generator>
</id>
hilo
使用高低算法来生成short、int和long类型的数据
<id ...>
<generator class="hilo"></generator>
</id>
native
它使用标识,序列或希洛取决于数据库供应商
<id ...>
<generator class="native"></generator>
</id>
identity
它用于Sybase,Mysql,MS SQL Server,DB2和Hypersonic SQL以支持id列。 返回的ID类型为short,int或long。
seqhilo
它在指定的序列名称上使用高低算法。 返回的ID类型为short,int或long。
uuid
它使用128位UUID算法生成id。 返回的ID是String类型,在网络中是唯一的(因为使用了IP)。 UUID以十六进制数字表示,长度为32。
guid
它使用由字符串类型的数据库生成的GUID。 它适用于MS SQL Server和MySQL。
select
它使用数据库触发器返回主键。
foreign
它使用另一个关联对象的id,主要用于<一对一>关联。
sequence-identity
它使用特殊的序列生成策略。 仅在Oracle 10g驱动程序中支持。