Hibernate基本映射:
实体类—映射—表。
实体类普通属性—映射—表字段。
采用<class>标签映射数据库表。
采用<property>标签映射表字段。
普通属性指的是:不包括自定义类,数组,集合等。
如果实体类和实体类中的属性和sql中的关键字重复,必须采用table或者column重新命名。
实体类的设计原则:
1, 实现一个默认的(无参数的)构造方法。
2, 提供一个标识属性(可选)。
3, 使用非final的类(可选)。如果final,无法继承。属性final则无法复写。影响lazy。因为Lazy是通过生成一个子类实现的。
4, 为持久化字段生成访问器,getter,setter方法。
例:
<hibernate-mapping package="eg">
<class name="Cat" table="cats">
//id必须放在第一个位置
<id name="id">
//increment用于为long, short或者int类型生成 唯一标识。只在同一个jvm中唯一,所以不要在集群下使用
<generator class="native"/>
</id>
<discriminator column="subclass"
type="character"/>
<property name="weight"/>
<property name="birthdate"
type="date"
not-null="true"
update="false"/>
<property name="color"
type="eg.types.ColorUserType"
not-null="true"
update="false"/>
<property name="sex"
not-null="true"
update="false"/>
<property name="litterId"
column="litterId"
update="false"/>
<many-to-one name="mother"
column="mother_id"
update="false"/>
<set name="kittens"
inverse="true"
order-by="litter_id">
<key column="mother_id"/>
<one-to-many class="Cat"/>
</set>
<subclass name="DomesticCat"
discriminator-value="D">
<property name="name"
type="string"/>
</subclass>
</class>
<class name="Dog">
<!-- mapping for Dog could go here -->
</class>
</hibernate-mapping>