1. 在搭配完成Maven後,在Eclipse中新建一個Dynamic Web Project。選擇新建的項目右鍵->Configure->Convert to Maven Project 。使用這樣的方式新建一個Dynamic web project 的目錄結構還會是平時熟悉的eclipse的目錄結構,即便轉換爲Maven project 後,也依然會保持原有的目錄結構 ,只是增長了pom.xml的maven 配置文件java
2. 要在項目中使用Hibernate 就必須添加Hibernate的類庫,因此接下來就是要在Maven配置上Hiberante依賴的類庫配置,代碼以下mysql
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>tian</groupId> <artifactId>tian</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>Tian System</name> <dependencies> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.3.11.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-c3p0</artifactId> <version>4.3.11.Final</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>2.3.8</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.9</version> <scope>test</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.14</version> </dependency> <dependency> <groupId>Mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.30</version> </dependency> <dependency> <groupId>javax.transaction</groupId> <artifactId>javax.transaction-api</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <sourceDirectory>src</sourceDirectory> <resources> <resource> <directory>src</directory> <excludes> <exclude>**/*.java</exclude> </excludes> </resource> </resources> <plugins> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.3</version> <configuration> <warSourceDirectory>WebContent</warSourceDirectory> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> </plugins> </build> </project>
由於使用的MySQL,因此在也把mysql的Jdbc的驅動也配置上去了,還有Junit測試框架。其中還有一個hibernate-c3p0是第三方鏈接池。保存後,Maven就會從中心類庫中download下來因此須要的類庫文件,在須要打開看源碼的時候,還會自動加載其中對應的源碼和Doc。固然啦 ,這個是Eclipse集成maven插件的自動化工具的效果。linux
3. 類庫有了以後,就須要寫一份hibernate.cfg.xml的配置xml文件。來使用Hiberanate知道如何訪問你的數據庫,以及有哪些元數據映射。如下是一份模板web
<?xml version='1.0'?> <!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> <!-- Database connection settings 這裏是數據庫鏈接的驅動、url、用戶名及密碼--> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://127.0.0.1:3306/test</property> <property name="connection.username">root</property> <property name="connection.password">123456</property> <!-- Use the C3P0 connection pool provider c3p0鏈接池的相關配置--> <property name="connection.c3p0.min_size">5</property> <property name="connection.c3p0.max_size">500</property> <property name="connection.c3p0.timeout">300</property> <property name="connection.c3p0.max_statements">50</property> <property name="connection.c3p0.idle_test_period">3000</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup 啓動時,對數據庫的更新策略,create是刪除表後再建立,update是與映射文件不匹配時更新--> <property name="hbm2ddl.auto">update</property> <!-- generated identifier properties will be reset to default values --> <property name="use_identifier_rollback">true</property> <mapping class="cn.tian.vo.User"/> <mapping class="cn.tian.vo.Mission"/> </session-factory> </hibernate-configuration>
4. 編寫元數據的類spring
以上面的xml配置中,映射了兩個元數據,其中屬性class是說明這個類的映射是經過註解來映射屬性的sql
若是是xml映射文件則是使用resouce屬性來指明xml的文件路徑,例如若是是放在同一個包下話,則應該是數據庫
<mapping resouce="cn/tian/vo/Mission"/>
這些都是細節問題,下來是User的代碼apache
package cn.tian.vo; import javax.persistence.*; @Entity @Table(name="tian_user") public class User { /** * 使用與業務無關的代理主鍵,由Hiberante 自動生成 */ @Id //標識爲主鍵 @GeneratedValue @Column(name="id") private Long id; /** * {@code String }姓名 */ @Column(name="name",nullable=false,length=20) //配置表的列信息,name是指定列名,nullable是容許空值,length指定字段長度 private String name; /** * {@code String }密碼 */ @Column(name="pwd",length=40) private String pwd; /** * {@code String }現任職務 */ @Column(name="job",nullable=false,length=20) private String job; /** * {@code String }性別 */ @Column(name="sex",nullable=false,length=4) private String sex; /** * {@code String }電話 */ @Column(name="phone",length=11) private String phone; /** * {@code String }出生年月 */ @Column(name="brithday",length=8) private String brithday; /** * {@code String }表明結構類別 */ @Column(name="struct_type",nullable=false,length=40) private String struct_type; /** * {@code cn.tian.vo.Mission }所屬表明團 */ @ManyToOne(targetEntity=Mission.class) //這裏是創建數據關係模型中的關係 多對一,即該屬性使用外鍵關聯到tian_mission表中 @JoinColumn(name="mission_id",foreignKey=@ForeignKey(name="FK_user_mission")) //foreginKey指定外鍵名稱,及外鍵字段名 private Mission mission; /* getter/setter ********** */ }
以及Misssion代碼api
package cn.tian.vo; import javax.persistence.*; @Entity @Table(name="tian_mission") public class Mission { @Id @GeneratedValue @Column(name="mission_id") private Long id; /** * {@code String }表明團名稱 */ @Column(name="mission_name",length=40,nullable=false) private String name; /** * {@code String }備註 */ @Column(name="remark",length=40) private String remark; /* getter/setter ********** */ }
5. 編寫Hibernate測試類,來測試一下是否能成功加載Hibernatesession
import java.util.*; import jpa.Department; import jpa.Employee; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; public class TestMain { private static SessionFactory factory; public static void main(String[] args) { try{ Configuration cfg = new Configuration().configure(); StandardServiceRegistry registry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build(); factory = cfg.buildSessionFactory(registry); }catch (Throwable ex) { System.err.println("Failed to create sessionFactory object." + ex); throw new ExceptionInInitializerError(ex); } } }
如何沒有異常拋出,則是能夠成功運行了咧。
6. 若是想自定義logging的輸出方式 ,能夠在classpath下放置一個log4j.properties就能夠,具體如何配置,能夠參考Apache log4j 1.2
7. 最近在將項目佈署到linux平臺運行時,系統使用Hibernate初始化數據庫數據的時候拋出了一個Unique Key重複的錯誤,在linux平臺調試後,發現是由於hibernate 與 mysql 的編碼亂碼問題。僅僅在hibernate.cfg.xml中配置了民charSet仍是不對數據庫的鏈接指定編碼,必須再加多一個characterEncoding屬性,其xml配置以下
<property name="connection.charSet">GBK</property> <property name="connection.characterEncoding">GBK</property>