1、創建數據庫及其表
create database demo;
use demo;
CREATE TABLE `user` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(50) DEFAULT NULL,
`password` varchar(50) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `ID` (`id`),
KEY `ID_2` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8
2、Intellij IDEA連接數據庫
1)點擊IDEA主界面右邊的Database,點擊“+”號,選擇Data Source -> 選擇對應的數據庫,我這里選擇的是MySQL。
2)輸入需要用到的數據庫的名稱,比如demo,輸入用戶名和密碼,點擊“Test Connection‘,測試連接數據庫是否成功。
3)數據庫連接成功,點擊”OK“,最后點擊”Apply“和”OK“即可。
4)連接成功后,顯示所有數據庫及其表格。
5)隨意點擊一個表中的某個字段,即可查看到表格內容,比如user表。Data為表格內容,Text為生成表格的SQL語句。
3、使用Intellij IDEA13創建Hibernate
1)創建一個空白Project,名為:HibernateProject。
2)創建一個Module,名為:HibernateModule,選擇“Web Application”和“Hibernate”。選擇“create default hibernate configuration in project configuration”和“Download”,點擊“Configure”,由於后面需要用到struts2,如果使用最新的Hibernate版本的話,貌似有些不兼容,所以這里選擇Hibernate 3.6.10-3.6.10。確定即可。IDEA會自動下載相關的Jar包,並自動生成一個hibernate.cfg.xml配置文件。
3)調整一個項目的結構,將lib文件夾移動到web/WEB-INF路徑下,在web/WEB-INF路徑下生成一個文件夾classes。快捷鍵:Ctrl + Alt + Shift + S ,彈出Project Module。配置Paths和Dependencies。
4)將額外需要的JAR包復制到lib文件夾中,比如MySQL驅動包mysql-connector-java-5.1.22-bin.jar,測試包junit-4.10.jar。
5)根據數據庫demo中的user表,生成UserEntity類。有兩種生成方式,一種是生成UserEntity類並生成相應的配置文件UserEntity.hbm.xml 文件。另外一種是利用標注的方式進行數據庫表與實體類的屬性的匹配。這里選擇第二種方式。
選擇左邊的Persistence,選擇對應的Module的hibernate.cfg.xml,注意選擇的是圖標是數據庫樣式的,右鍵 -> Generate Persistence Mapping -> By Database Schema。
選擇數據庫源,就是剛剛測試連接的數據庫;輸入包名,它會自動創建包的;由於這里只是簡單的演示如何利用Hibernate操作數據庫,所以只是簡單的選擇其中一個表來做實驗,比如選擇demo.user。並且將右下方的“Generate Column Properties”勾上。如果選擇的是第一種操作方式,則將右下方的“Generate Separate XML per Entity”勾選上,即為每一個表所對應的實體類生成一個配置文件。確定即可。
6)自動生成的實體類UserEntity。
package com.yyq.dao; import javax.persistence.*; @Entity @Table(name = "user", schema = "", catalog = "demo") public class UserEntity { private int id; private String username; private String password; private String email; @Id @Column(name = "id", nullable = false, insertable = true, updatable = true, length = 10, precision = 0) public int getId() { return id; } public void setId(int id) { this.id = id; } @Basic @Column(name = "username", nullable = true, insertable = true, updatable = true, length = 50, precision = 0) public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Basic @Column(name = "password", nullable = true, insertable = true, updatable = true, length = 50, precision = 0) public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Basic @Column(name = "email", nullable = true, insertable = true, updatable = true, length = 50, precision = 0) public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UserEntity that = (UserEntity) o; if (id != that.id) return false; if (email != null ? !email.equals(that.email) : that.email != null) return false; if (password != null ? !password.equals(that.password) : that.password != null) return false; if (username != null ? !username.equals(that.username) : that.username != null) return false; return true; } @Override public int hashCode() { int result = id; result = 31 * result + (username != null ? username.hashCode() : 0); result = 31 * result + (password != null ? password.hashCode() : 0); result = 31 * result + (email != null ? email.hashCode() : 0); return result; } }
7)配置hibernate.cfg.xml 如下。
<?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/demo</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.username">root</property> <property name="connection.password">123456</property> <property name="current_session_context_class">thread</property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">update</property> <!-- DB schema will be updated if needed --> <!-- <property name="hbm2ddl.auto">update</property> --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <mapping class="com.yyq.dao.UserEntity"/> </session-factory> </hibernate-configuration>
8)生成測試路徑。在Module路徑下生成一個文件夾,與src同級,名為test,點擊文件夾test,右鍵,選擇Mark Directory As - > Test Sources Root。

9)生成測試類。
package com.yyq; import com.yyq.dao.UserEntity; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.junit.Before; import org.junit.Test; public class DAOTest { Configuration config = null; SessionFactory sessionFactory = null; Session session = null; Transaction tx = null; @Before public void init() { config = new Configuration().configure("/hibernate.cfg.xml"); sessionFactory = config.buildSessionFactory(); session = sessionFactory.openSession(); tx = session.beginTransaction(); } //增加 @Test public void insert() { UserEntity ue = new UserEntity(); ue.setUsername("Anny"); ue.setPassword("123"); ue.setEmail("Anny@163.com"); session.save(ue); tx.commit(); } //修改 @Test public void update() { UserEntity user = (UserEntity) session.get(UserEntity.class, new Integer(2)); user.setUsername("Penny"); session.update(user); tx.commit(); session.close(); } //查找 @Test public void getById() { UserEntity user = (UserEntity) session.get(UserEntity.class, new Integer(8)); tx.commit(); session.close(); System.out.println("ID號:" + user.getId() + ";用戶名:" + user.getUsername() + ";密碼:" + user.getPassword() + ";郵件:" + user.getEmail()); } //刪除 @Test public void delete() { UserEntity user = (UserEntity) session.get(UserEntity.class, new Integer(6)); session.delete(user); tx.commit(); session.close(); } }
10)運行測試類,可以一個一個方法的進行運行,也可以在類名處將所有的測試方法都一起運行。全部運行成功!

11)項目結構圖。
4、Hibernate與Struts2整合
1)配置web.xml,這與普通的Struts2程序一樣。
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>Struts2AndHibernate</display-name> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
2)將相關的Jar包復制到lib文件夾下。

3)創建一個名為ListAllAction.java文件。
package com.yyq.action; import com.googlecode.s2hibernate.struts2.plugin.annotations.SessionTarget; import com.googlecode.s2hibernate.struts2.plugin.annotations.TransactionTarget; import com.opensymphony.xwork2.ActionSupport; import com.yyq.dao.UserEntity; import org.hibernate.Session; import org.hibernate.Transaction; import java.util.List; public class ListAllAction extends ActionSupport { //使用@SessionTarget標注得到Hibernate Session @SessionTarget private Session session = null; //使用@TransactionTarget標注得到Hibernate Transaction @TransactionTarget private Transaction transaction = null; private List<UserEntity> users; public String list(){ try{ //得到user表中的所有記錄 users = session.createCriteria(UserEntity.class).list(); transaction.commit(); session.close(); return SUCCESS; }catch (Exception e){ e.printStackTrace(); return ERROR; } } public List<UserEntity> getUsers(){ return users; } public void setUsers(List<UserEntity> users){ this.users = users; } }
4)修改index.jsp文件以顯示后台數據庫的數據獲取情況。
<%@ taglib prefix="s" uri="/struts-tags" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>顯示數據</title> </head> <body> <table> <tr> <th>ID</th> <th>用戶名</th> <th>密碼</th> <th>郵箱</th> </tr> <s:iterator value="users" var="obj"> <tr> <td><s:property value="id"/></td> <td><s:property value="username"/></td> <td><s:property value="password"/></td> <td><s:property value="email"/></td> </tr> </s:iterator> </table> </body> </html>
5)配置struts.xml文件。
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN" "http://struts.apache.org/dtds/struts-2.1.7.dtd"> <struts> <!--s2hibernate插件里面有一個叫hibernate-default的package, 它里面的攔截器用於實現struts2+hibernate整合--> <package name="default" extends="hibernate-default"> <!--defaultStackHibernate里面的攔截器會識別出@SessionTarget,@TransactionTarget等標注, 然后將hibernate注入進去--> <default-interceptor-ref name="defaultStackHibernate"/> <default-class-ref class="com.yyq.action.ListAllAction"/> <action name="listAll" method="list"> <result>index.jsp</result> </action> </package> </struts>
6)啟動Tomcat,輸入:http://localhost:8080/listAll.action

7)項目結構圖。

