搭建Junit单元测试,方便测试下好的程序;
使用Annotation注解,不用xml来实现实体类与表的映射;
1、编写POJO类
@GeneratedValue(strategy=GenerationType.AUTO)package com.hibernate._0200_BasicConfguration;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity // 标注实体类
@Table(name="_teacher") //指定数据库中对应的表的名称
public class Teacher {
private int id;
private String name;
private String title;
private boolean good;
private String wifeName;
private Date birthDay;
@Id //注解为主键
@GeneratedValue(strategy=GenerationType.AUTO) //指定ID生成策略
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="myName") //映射属性在数据库中的字段
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Temporal(TemporalType.DATE) //指定数据在数据库中的类型
public Date getBirthDay() {
return birthDay;
}
public void setBirthDay(Date birthDay) {
this.birthDay = birthDay;
}
public String getWifeName() {
return wifeName;
}
public void setWifeName(String wifeName) {
this.wifeName = wifeName;
}
public boolean isGood() {
return good;
}
public void setGood(boolean good) {
this.good = good;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
将实体类注解为 @Entity ,可用 注解 @Table(name="***")来指定数据库中对应表的名称
将主键注解为 @Id ,并可以用@GeneratedValue(strategy=GenerationType.***) 来指定ID生成策略
使用 @Column(name="***")指定类的属性对应数据库字段的名称;
使用@Temporal(TemporalType.***) 指定数据库中字段的类型;
2、添加映射的配置文件
在hibernate.cfg.xml文件中添加
<mapping class="com.hibernate._0200_BasicConfguration.Teacher" />
3、搭建Junit单元测试
加入Junit的包,利用Junit进行单元测试。
4、测试类
package com.hibernate._0300_BasicConfguration;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class test2 {
public static void main(String[] args) {
SessionFactory sf= new AnnotationConfiguration().configure().buildSessionFactory();
Session session = sf.getCurrentSession();
session.beginTransaction();;
Teacher teacher = new Teacher();
teacher.setId(2);
teacher.setName("飞鸽");
teacher.setTitle("高级工程师");
teacher.setGood(true);
teacher.setWifeName("林志林");
teacher.setBirthDay(new Date());
session.save(teacher);
session.getTransaction().commit();
sf.close();
}
}
使用getTransaction时,首先从当前线程中那session,没有则创建新的,openSession每次都是打开新的;
使用getTransaction时,commint后自动关闭,而是用openSession每次要手动关闭;
使用getTransaction,hibernate.cfg.xml中要配置 <property name="current_session_context_class">thread</property> ,从当前线程中那,否则会报错。