package cn.edu.hpu.model;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name="_tteacher")
public class Teacher {
private String name;
private int id;
public String title;
private Date brithday;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//@Id告诉hibernate这个是主键
@Id
public int getId() {
return id;
}
@Temporal(TemporalType.DATE)
public Date getBrithday() {
return brithday;
}
public void setBrithday(Date date) {
this.brithday = date;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
package cn.edu.hpu.test;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import cn.edu.hpu.model.Teacher;
public class TeacherTest {
public static void main(String[] args) {
Teacher t=new Teacher();
t.setId(3);
t.setName("t4");
t.setTitle("中级");
t.setBrithday(new Date());
//AnnotationConfiguration是用来专门读Annotation配置的
@SuppressWarnings("deprecation")
Configuration cfg=new AnnotationConfiguration();
//文件下的 <mapping resource=.....
@SuppressWarnings("deprecation")
SessionFactory sf=cfg.configure().buildSessionFactory();
//buildSessionFactory()可以理解为能得到conn的类
//暂时把Session理解成数据库的Connection
Session session=sf.openSession();//得到session
//
session.beginTransaction();
session.save(t);
session.getTransaction().commit();
session.close();
System.out.println("aaaaaaaaaaaaaaaaaaaaaaaa");
//
Session session2=sf.openSession();
session2.beginTransaction();
Teacher teacher2=(Teacher)session2.get(Teacher.class,2);
session2.getTransaction().commit();
session2.close();
System.out.println(teacher2.getBrithday());
System.out.println("hhhhhhhhhhhhhhhhhhhhhhhh");
sf.close();
}
}
在读取数据
Teacher teacher2=(Teacher)session2.get(Teacher.class,2);
的时候的id和插入的id不一致引起的