1. 在搭配完成Maven后,在Eclipse中新建一个Dynamic Web Project。选择新建的项目右键->Configure->Convert to Maven Project 。使用这样的方式新建一个Dynamic web project 的目录结构还会是平时熟悉的eclipse的目录结构,即使转换为Maven project 后,也依然会保持原有的目录结构 ,只是增加了pom.xml的maven 配置文件
2. 要在项目中使用Hibernate 就必须添加Hibernate的类库,所以接下来就是要在Maven配置上Hiberante依赖的类库配置,代码如下
<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插件的自动化工具的效果。
3. 类库有了之后,就需要写一份hibernate.cfg.xml的配置xml文件。来使用Hiberanate知道如何访问你的数据库,以及有哪些元数据映射。以下是一份模板
<?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. 编写元数据的类
以上面的xml配置中,映射了两个元数据,其中属性class是说明这个类的映射是通过注解来映射属性的
如果是xml映射文件则是使用resouce属性来指明xml的文件路径,例如如果是放在同一个包下话,则应该是
<mapping resouce="cn/tian/vo/Mission"/>
这些都是细节问题,下来是User的代码
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",[email protected](name="FK_user_mission")) //foreginKey指定外键名称,及外键字段名 private Mission mission; /* getter/setter ********** */ }
以及Misssion代码
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测试类,来测试一下是否能成功加载Hibernate
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