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

1.引入hibernate必备的jar包


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这个表


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值