1.输出运行的SQL语句和格式化SQL语句:
hibernate.cfg.xml添加属性:
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- 格式化输出SQL语句 -->
<property name="format_sql">true</property>
2.如果表名和类名不一致,对表名进行设置
a) Annotation:@Table(name="teacher")
b) xml:<class name="Student" table="student">
3.如果字段名和属性名不一致
a) Annotation:@Colume(name="title")
b) xml:<id name="id" column="EVENT_ID">
<property name="date" type="timestamp" column="EVENT_DATE"/>
4.如果字段名和属性相同
a)Annotation:默认不写,@Basic
b)xml:不用写column
5.不需要persistence的字段
a)Annotation:@Transient
b)xml:不写
6.映射日期与时间类型,指定时间精度
a)Annotation:@Temporal(TemporalType.TIME)
b)xml:指定type
7.映射枚举类型
a)Annotation:@Enumerated
b)xml:google查询
8.字段映射的位置
a)放置在Field前,便于管理,但不符合封装的特性
b)放置在get方法前
eg:
package com.bjsxt.hibernate; import java.util.Date; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import javax.persistence.Basic; import javax.persistence.Column; @Entity @Table(name="_teacher") public class Teacher { private int id; private String name; private String title; private String yourWifeName; private Date birthDate; private boolean good; private Gender gender; @Enumerated(EnumType.STRING) public Gender getGender() { return gender; } public void setGender(Gender gender) { this.gender = gender; } public boolean isGood() { return good; } public void setGood(boolean good) { this.good = good; } @Transient public String getYourWifeName() { return yourWifeName; } public void setYourWifeName(String yourWifeName) { this.yourWifeName = yourWifeName; } @Id public int getId() { return id; } public void setId(int id) { this.id = id; } //Basec默认,一般不加 @Basic public String getName() { return name; } public void setName(String name) { this.name = name; } @Column(name="title") public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @Temporal(TemporalType.TIME) public Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } }
package com.bjsxt.hibernate; public enum Gender { MALE, FEMALE }
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.bjsxt.hibernate.Student" table="_student"> <id name="id" /> <property name="name" /> <property name="age" /> <property name="sex" /> <property name="good" type="yes_no"></property> </class> </hibernate-mapping>