1. 下載安裝JBossTools eclipse的插件html
http://www.jboss.org/tools/download/ 也能夠只安裝java
Update site (including sources) bundle of all Hibernate Tools
4.1.0.Final
78 MB
2013-07-22
update zipmysql
Kepler版本 http://www.jboss.org/tools/download/stable/4_1.htmlgit
安裝過程當中eclipse要聯網安裝其餘的東西,很慢。github
2. 安裝MariaDBsql
https://mariadb.org/ 下載速度比較慢,直接從國內的網站下載最新X64的 MariaDB 10.0.4 安裝過程和MySQL同樣,用戶名和密碼記住數據庫
https://downloads.mariadb.org/ 向下找session
下載MySQL的Java數據庫鏈接jar包 http://dev.mysql.com/downloads/connector/j/#downloads 選擇平臺獨立的版本便可Platform Independent (Architecture Independent)app
3. 使用MariaDB自帶的HeidiSQL新建數據庫eclipse
-- 導出 gamestore 的數據庫結構 DROP DATABASE IF EXISTS `gamestore`; CREATE DATABASE IF NOT EXISTS `gamestore` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `gamestore`; -- 導出 表 gamestore.company 結構 DROP TABLE IF EXISTS `company`; CREATE TABLE IF NOT EXISTS `company` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COMMENT='game producer'; -- 正在導出表 gamestore.company 的數據:~4 rows (大約) /*!40000 ALTER TABLE `company` DISABLE KEYS */; INSERT INTO `company` (`id`, `name`) VALUES (1, 'EA'), (2, 'ActiveVision'), (3, 'North RockStar'), (4, 'TakeTwo'); /*!40000 ALTER TABLE `company` ENABLE KEYS */; -- 導出 表 gamestore.game 結構 DROP TABLE IF EXISTS `game`; CREATE TABLE IF NOT EXISTS `game` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, `type` int(10) unsigned DEFAULT '0', `company_id` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`id`), KEY `FK_game_company` (`company_id`), CONSTRAINT `FK_game_company` FOREIGN KEY (`company_id`) REFERENCES `company` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; -- 正在導出表 gamestore.game 的數據:~4 rows (大約) /*!40000 ALTER TABLE `game` DISABLE KEYS */; INSERT INTO `game` (`id`, `name`, `type`, `company_id`) VALUES (1, 'BattleField 4', NULL, 1), (2, 'Call of Duty 10', NULL, 2), (3, 'FIFA14', NULL, 1), (4, 'GTA5', NULL, 3);
4. 新建Eclipse工程
在工程Java Build Path中加入Hibernate required的必備包,以及mariadb-java-client-1.1.5.jar和mysql-connector-java-5.1.26-bin.jar兩個包
打開Eclipse的 DataSource Explorer視圖, 新建一個Connection Profile, 選擇MySQL類型,驅動選擇MySQL的驅動,此時要找到工程中添加的mysql-connector-java-5.1.26-bin.jar 用來和數據庫進行鏈接,
URL:jdbc:mysql://localhost:3306/gamestore
數據庫:gamestore
5. 新建Hibernate配置文件
在src目錄下,在新建嚮導的Hibernate目錄下找到Hibernate Configuration File(cfg.xml),按照嚮導使用默認的名稱便可,默認狀況下Hibernate在初始化Configuration對象時,會在程序包所在的根目錄下找名爲Hibernate.cfg.xml文件做爲配置文件,不然須要在configure()方法中設置配置文件。選擇Get Values from Connection 後選擇剛纔新建的Connection Profile,此時會導入剛纔的默認是指,不過是針對MySQL數據庫的,以後在該配置基礎上改成MariaDB的配置便可。須要注意插件自動生成的xml文件的DTD是不是正確的,建議從Hibernate官方例子中拷貝最新的模板進行修改。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.mariadb.jdbc.Driver</property>
<property name="hibernate.connection.password">123456</property>
<property name="hibernate.connection.url">jdbc:mariadb://localhost:3306/gamestore</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.jdbc.batch_size">20</property>
<property name="show_sql">true</property>
<mapping resource="com/aquar/game/database/Game.hbm.xml"/>
<mapping resource="com/aquar/game/database/Company.hbm.xml"/>
</session-factory>
</hibernate-configuration>
6. 新建Hibernate Console Configuration
同建立配置文件同樣,(能夠在建立配置文件的最後一步,勾選建立Hibernate Console Configuration,就不用在進入新建文件嚮導了),固然選擇Hibernate Core 4.0,Database connection 一樣選擇剛纔的connection profile,設置Configuration file爲剛纔建立的hibernate.cfg.xml
7. 新建Hibernate Reverse Engineer File(reveng.xml)
選擇剛纔新建的Console Configuration 後,點擊刷新就能夠看到數據庫和下面的表格,選擇須要建立的POJO對象的表格finish。在eclipse中打開hibernante.reveng.xml文件後,有可視化編輯標籤頁。其中:
Type Mappings:用來將數據庫數據類型和Hibernate的類型進行映射,例如能夠把JDBC的INTEGER映射爲Hibernate的integer。主鍵id最好映射爲integer,這樣java會生成Integer類型的id定義,經過判斷id是否爲null方便判斷一個對象是不是數據庫中獲取的對象。
Table Filters:用來選擇那些表格會映射
Table & Columns : 設置表格字段的映射規則
其實直接找一份模板,在源碼的基礎上修改更直接,使用可視化工具編輯主鍵和外鍵不夠靈活。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd" >
<hibernate-reverse-engineering>
<type-mapping>
<sql-type jdbc-type="INTEGER" hibernate-type="integer"
not-null="true">
</sql-type>
</type-mapping>
<table-filter match-name="company" match-catalog="gamestore"></table-filter>
<table-filter match-catalog="gamestore" match-name="game" />
<table catalog="gamestore" name="company">
<primary-key>
<generator class="increment"></generator>
<key-column name="id"></key-column>
</primary-key>
<column name="name"></column>
</table>
<table catalog="gamestore" name="game">
<primary-key>
<generator class="increment"></generator>
<key-column name="id"></key-column>
</primary-key>
<column name="name"></column>
<column name="type"></column>
<column name="company_id"></column>
</table>
</hibernate-reverse-engineering>
8. 生成POJO和Mappings
選擇eclipse的window下Customize Perspective ,在Command Groups 中勾選Hibernate Code Generation。
打開Hibernate Code Generation Configurations,選擇剛纔建立的Console Configuration,輸出目錄爲工程src目錄,包目錄爲但願放置的java包目錄,以及剛纔的Hibernate.reveng.xml文件,執行run便可。這樣會在指定的包目錄下建立對應的JavaBean規範的類和hbm.xml文件。這些文件若是有不知足須要的能夠手動修改。
package com.aquar.game.database; // Generated Nov 3, 2013 7:49:14 PM by Hibernate Tools 4.0.0 import java.util.HashSet; import java.util.Set; /** * Company generated by hbm2java */ public class Company implements java.io.Serializable { /** * */ private static final long serialVersionUID = 1544255372285741722L; private Integer id; private String name; private Set games = new HashSet(0); public Company() { } public Company(Integer id, String name) { this.id = id; this.name = name; } public Company(Integer id, String name, Set games) { this.id = id; this.name = name; this.games = games; } public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Set getGames() { return this.games; } public void setGames(Set games) { this.games = games; } }
對應的hmb.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.aquar.game.database">
<class name="Company" table="company" catalog="gamestore">
<id name="id" type="integer">
<column name="id" />
<generator class="increment"></generator>
</id>
<property name="name" type="string">
<column name="name" length="50" not-null="true" />
</property>
<set name="games" table="game" inverse="true" lazy="true" fetch="select">
<key>
<column name="company_id" not-null="true" />
</key>
<one-to-many class="Game" />
</set>
</class>
</hibernate-mapping>
簡單測試
數據庫操做Handler
package com.aquar.game.dataserver; import java.util.List; import org.hibernate.Criteria; import org.hibernate.LockOptions; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistryBuilder; public class DataHandler { private static DataHandler instance; private SessionFactory sessionFactory; private DataHandler() { // TODO Auto-generated constructor stub } public static DataHandler getInstance() { if (instance == null) { instance = new DataHandler(); } return instance; } public void init() { // configures settings from hibernate.cfg.xml Configuration cfg = new Configuration(); cfg.configure(); // A SessionFactory is set up once for an application sessionFactory = cfg.buildSessionFactory(new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry()); } public <T> boolean save(List<T> objs) { boolean ret = false; Session session = sessionFactory.openSession(); try { session.beginTransaction(); int count = 0; for (T obj : objs) { session.save(obj); count++; if (count == 20) { //20, same as the JDBC batch size //flush a batch of inserts and release memory: session.flush(); session.clear(); count = 0; } } session.getTransaction().commit(); ret = true; } catch (Exception e) { e.printStackTrace(); } finally { session.close(); } return ret; } @SuppressWarnings("unchecked") public <T> List<T> query(T obj) { List<T> result = null; Session session = sessionFactory.openSession(); try { session.beginTransaction(); Criteria crit = session.createCriteria(obj.getClass()); result = crit.list(); session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); } finally { session.close(); } return result; } public <T> T load(T t) { Session session = sessionFactory.openSession(); session.buildLockRequest(LockOptions.NONE).lock(t); return t; } public <T> boolean delete(T obj) { boolean ret = false; Session session = sessionFactory.openSession(); try { session.beginTransaction(); session.delete(obj); session.getTransaction().commit(); ret = true; } catch (Exception e) { e.printStackTrace(); } finally { session.close(); } return ret; } public void release() { if (sessionFactory != null) { sessionFactory.close(); } } }
初始化注意要用
public void init() {
// configures settings from hibernate.cfg.xml
Configuration cfg = new Configuration();
cfg.configure(); //這個必須有,不然不會去獲取cfg.xml中的屬性配置,官方簡單教程中的例子方法不能使用。
// A SessionFactory is set up once for an application
sessionFactory = cfg.buildSessionFactory(new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry());
}
JUnit測試用例,須要依賴JUnit4
package com.aquar.game.test; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.aquar.game.database.Company; import com.aquar.game.database.Game; import com.aquar.game.dataserver.DataHandler; public class DataHandlerTest extends TestCase { @Before public void setUp() throws Exception { DataHandler.getInstance().init(); } @After public void tearDown() throws Exception { DataHandler.getInstance().release(); } @Test public void testSave() { boolean ret = false; List<Game> games = new ArrayList<Game>(); String[] names = {"BattleField 4", "Call of Duty 10", "FIFA14", "GTA5"}; for (String name : names) { Game game = new Game(); game.setName(name); games.add(game); } ret = DataHandler.getInstance().save(games); assertTrue(ret); } @Test public void testQuery() { List<Company> list = DataHandler.getInstance().query(new Company()); assertNotNull(list); assertFalse(list.isEmpty()); assertTrue(true); } }
source code on github:GameStore