一.基础配置
hibernate.cfg.xml中:
1.hbm2ddl.auto:create:没有就新建、update:可增加字段
2.show_sql:打印sql语句出来
3.format_sql:打印时分行显示,看着清晰点
二.@Table、 @Column、 @Temporal、 @Transient、 @Enumerated
这几个Annotation要写在相应的get方法上(写在属性头上实测不灵),其中:
@Table(name="t_Teacher")//解决类名和表名不对应
@Column(name="id")//解决属性名和字段名不对应
@Column(length=50)//限制字符串长度
@Temporal(TemporalType.DATE)//限制时间格式:只记录日期不记录时间。默认是时间日期都记录
@Transient//隐藏属性,不会被映射到表中
@Enumerated(EnumType.STRING)//把枚举里的sring存储进去
@Enumerated(EnumType.ORDINAL)//把存在的顺序编号int存储进去
三.JUnit测试:
插入
- Session session = HibernateUtil.getSessionFactory().getCurrentSession();
- session.beginTransaction();
- Teacher t = new Teacher();
- t.setTeacherid(203);
- t.setName("李四");
- t.setAge(0);
- t.setBirthday(new Date());
- t.setGrade(Grade.A);
- session.save(t);
- session.getTransaction().commit();
- HibernateUtil.getSessionFactory().close();
查询:
- Session session2 = HibernateUtil.getSessionFactory().getCurrentSession();
- session2.beginTransaction();
- List<Teacher> result = session2.createQuery("from Teacher").list();//此行的Event指的是对应的类名,而不是数据表的名字。
- Iterator it = result.iterator();
- Teacher value = null;
- while (it.hasNext())
- {
- value = (Teacher)it.next();
- System.out.println(value.getTeacherid());
- System.out.println(value.getName());
- System.out.println(value.getAge());
- System.out.println(value.getBirthday());
- System.out.println(value.getGrade());
- }
- session2.getTransaction().commit();
- HibernateUtil.getSessionFactory().close();
【转自】http://blog.csdn.net/null____/article/details/8146016
- import java.util.Date;
- import javax.persistence.Column;
- 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;
- @Entity
- @Table(name="t_Teacher")//解决类名和表名不对应
- public class Teacher {
- private int teacherid;
- private String name;
- private int age;
- private Date birthday;
- private String secret;
- private Grade grade;
- //setter&getter
- @Id
- @Column(name="id")//解决属性名和字段名不对应
- public int getTeacherid() {
- return teacherid;
- }
- @Column(length=50)//限制字符串长度
- public String getName() {
- return name;
- }
- @Temporal(TemporalType.DATE)//限制时间格式:只记录日期不记录时间。默认是时间日期都记录
- public Date getBirthday() {
- return birthday;
- }
- @Transient//隐藏属性,不会被映射到表中
- public String getSecret() {
- return secret;
- }
- @Enumerated(EnumType.STRING)//把枚举里的sring存储进去
- //@Enumerated(EnumType.ORDINAL),把存在的顺序编号int存储进去
- public Grade getGrade() {
- return grade;
- }