<hibernate-mapping> <class name="events.Event" table="EVENTS"> <id name="id" column="EVENT_ID"> <generator class="native"/> </id> <property name="date" type="timestamp" column="EVENT_DATE"/> <property name="title"/> </class> </hibernate-mapping>
0.id
元素是标识符属性的声明,name="id"
声明了Java属性的名字 - Hibernate会使用getId()
和setId()
来访问它。
在向数据库插入数据时,id列不需要赋值
column
属性则告诉Hibernate, 我们使用EVENTS
表的哪个字段作为主键。嵌套的generator
元素指定了标识符生成策略,在这里我们指定native
,它根据已配置的数据库(方言)自动选择最佳的标识符生成策略。Hibernate支持由数据库生成,全局唯一性(globally
unique)和应用程序指定(或者你自己为任何已有策略所写的扩展)这些策略来生成标识符
1.class 元素中的table指定数据库中对应的表,不设置则默认为与类同名的数据库
2.colum 属性用于指定数据库表中对应的字段,不设置则默认为与name属性同名的字段(比如 title 在数据库表中映射的也为 title)
3.property
元素的name
属性告诉Hibernate使用哪个getter和setter方法。在此例中,Hibernate会寻找getDate()/setDate()
, 以及getTitle()/setTitle()
。
3.type属性用于给字段指定数据类型,如果不指定,Hibernate会自动映射数据类型,自动匹配的结果很多时候不会产生你所期待或需要的缺省值
应该把这个映射文件保存为Event.hbm.xml
,且就在Event
Java类的源文件目录下。映射文件可随意地命名,但hbm.xml
的后缀已成为Hibernate开发者社区的约定(和class放在一起)
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">org.hsqldb.jdbcDriver</property> <property name="connection.url">jdbc:hsqldb:hsql://localhost</property> <property name="connection.username">sa</property> <property name="connection.password"></property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.HSQLDialect</property> <!-- Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">create</property> <mapping resource="events/Event.hbm.xml"/> </session-factory> </hibernate-configuration>
1.Hibernate的SessionFactory
-一个关联于特定数据库全局的工厂(factory)。如果你要使用多个数据库,就要用多个的<session-factory>
,通常把它们放在多个配置文件中(为了更容易启动)。
2.dialect property
元素指明Hibernate 生成的特定SQL变量
3.打开hbm2ddl.auto
选项将自动生成数据库模式(schema)- 直接加入数据库中。
把这个文件拷贝到源代码目录下面,这样它就位于classpath的根目录的最后。Hibernate在启动时会自动在classpath的根目录查找名为hibernate.cfg.xml
的配置文件。