时间:2021-07-01 10:21:17 帮助过:32人阅读
三、Hibernate基础配置 1、如果在Annotation中,类名与真是的数据库中的表名不同,可以使用增加@Table(name=数据库中的表名)的方式使其对应。此时,如果数据库中有这个表名则会对应上,如果没有这个表,则会生成这个表。同样的,在XXX.hbm.xml中,也可以配置
三、Hibernate基础配置package com.zgy.hibernate.model; 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="_teacher") public class Teacher { private int id; private String name; private String title; private String address; private String wifeName; private Date birth; private ZhiCheng zhiCheng; @Id public int getId() { return id; } public void setId(int id) { this.id = id; } @Column(name="_name") 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; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getWifeName() { return wifeName; } public void setWifeName(String wifeName) { this.wifeName = wifeName; } @Temporal(TemporalType.DATE) public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } @Enumerated(EnumType.STRING) public ZhiCheng getZhiCheng() { return zhiCheng; } public void setZhiCheng(ZhiCheng zhiCheng) { this.zhiCheng = zhiCheng; } } 修改test下的TeacherTesting.java package com.zgy.hibernate.model; import static org.junit.Assert.*; import java.util.Date; 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; public class TeacherTesting { public static SessionFactory sf = null; @BeforeClass public static void beforeClass(){ sf = new AnnotationConfiguration().configure().buildSessionFactory(); } @Test public void test() { Teacher t = new Teacher(); t.setId(5); t.setName("t5"); t.setTitle("高级"); t.setAddress("北京"); t.setBirth(new Date()); t.setZhiCheng(ZhiCheng.A); Session session = sf.openSession(); session.beginTransaction(); session.save(t); session.getTransaction().commit(); session.close(); } @AfterClass public static void afterClass(){ sf.close(); } }