hibernate中使用注解自动生成类对应的表的字段

时间:2022-07-01 13:19:49

1.引入hibernate必备的jar包

hibernate中使用注解自动生成类对应的表的字段

2.新建Teacher类

package com.zhlk.model;


import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
 
/**
 * @author lvguanghui
 * date 2017-1-21
 */
@Entity
@Table(name="_teacher")
 public class Teacher {
  //teacher
private int id;
private String name;
private String title;
@Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}

}

3.在hibernate.cfg.xml中添加如下配置用来指定Teacher类

    <mapping class="com.zhlk.model.Teacher"/>
4.   新建TeacherTest类

package com.zhlk.model;


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;


/**
 * @author lvguanghui date 2017-1-21
 */
public class TeacherTest {
private static SessionFactory sf = null;


@BeforeClass
public static void beforeClass() {
sf = new AnnotationConfiguration().configure().buildSessionFactory();


}
    
@Test
public void testTeacherSave() {
Teacher t = new Teacher();
t.setId(1);
t.setName("王老师");
t.setTitle("中级");
// Configuration cfg=new AnnotationConfiguration();
// SessionFactory sf= cfg.configure().buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.save(t);
session.getTransaction().commit();
session.close();


}


@AfterClass
public static void afterClass() {
sf.close();
}
}
 

5. 经过Junit的测试,查看数据库可以知道,已经创建好了_teacher这个表

hibernate中使用注解自动生成类对应的表的字段