Hibernate使用注解的方式配置
以往是在*.hbm.xml中配置实体类和表之间的映射。使用xml配置本来就很繁琐,Java中可以使用注解的方式来配置。
使用*.hbm.xml的配置方式不再赘述,这里运用注解的方式来完成配置。
1.hibernate核心配置文件变化
<mapping resource="com/wsw/hibernate/model/Person.hbm.xml"/>
改成
<mapping class="com.wsw.hibernate.model.Teacher" />
2.获取SessionFactory的方式变化
SessionFactory sf = new Configuration().configure().buildSessionFactory()
变成
SessionFactory sf = new AnnotationConfiguration().configure().buildSessionFactory()
示例
#注意事项
1.所有的注解都是在javax.persistence包下,不是在hibernate下
@Entity // 表示为实体类
@Table(name="t_teacher") // 表名注解
public class Teacher implements Serializable {
private int id;
private String username;
private int age;
@Id // 表示主键
@GenericGenerator(name = "generator", strategy = "increment")
@GeneratedValue(generator = "generator") // 自增长
@Column(name = "id") // 类属性对应着表字段
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="t_username") // 类属性对应着表字段
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Column(name="t_age")// 在实体类属性进行注解,类属性对应着表字段
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}