需要要的jar
這些jia包在Hibernate文件中都有
配置hibernate.cfg.xml:Hibernate配置
hibernate.cfg.xml
- 數(shù)據(jù)庫方言設(shè)置一定要對應(yīng)所使用的數(shù)據(jù)庫
- 數(shù)據(jù)庫c3p0使用一定要加入對應(yīng)的jar
- 加入元數(shù)據(jù)(描述 對象 數(shù)據(jù)庫的映射關(guān)系的配置文件)使用mapping標(biāo)簽
配置XXX.hbm.xml:描述 對象 數(shù)據(jù)庫的映射關(guān)系的配置文件(元數(shù)據(jù))
News.hbm.xml
對應(yīng)對象:
package chen;
import java.util.Date;
public class News {
private Integer id;
private String title;
private String author;
private String desc;
private Date date;
public News() {
}
public News(String title, String author, Date date) {
this.title = title;
this.author = author;
this.date = date;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@Override
public String toString() {
return "News [id=" + id + ", title=" + title + ", author=" + author + ", desc=" + desc + ", date=" + date + "]";
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
Hibernate配置完成
hibernate初始使用:
- 1.創(chuàng)建ServiceRegistry對象:hibernate 4.X新對象 hibernate的任何配置和服務(wù)都要在該對象中注冊才有用
- 2.創(chuàng)建 SessionFactory 對象
- 3.創(chuàng)建一個 Session 對象
- 4.開啟事務(wù)
- 5.執(zhí)行操作(業(yè)務(wù))
- 6.提交事務(wù)
- 7.關(guān)閉Session
- 8.關(guān)閉SessionFactory
代碼:
/**
* hibernate初始
*/
public static void hibernate() {
// 1.創(chuàng)建ServiceRegistry對象:hibernate 4.X新對象 hibernate的任何配置和服務(wù)都要在該對象中注冊才有用
StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();// 配置文件configure()
// 沒有參數(shù)默認(rèn)
// 2.創(chuàng)建 SessionFactory 對象
SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
// 3.創(chuàng)建一個 Session 對象
Session session = sessionFactory.openSession();
// 4.開啟事務(wù)
Transaction transaction = session.beginTransaction();
// 5.執(zhí)行保存操作
News news = new News("上海高溫", "好久沒有下雨", new Date(new Date().getTime()));
session.save(news);
// 6.提交事務(wù)
transaction.commit();
// 7.關(guān)閉Session
session.close();
// 8.關(guān)閉SessionFactory
sessionFactory.close();
}
- 創(chuàng)建ServiceRegistry對象時configure()方法默認(rèn)指向類路徑下的名hibernate.cfg.xml配置文件也可以自定義
- 當(dāng)配置完成第一次運(yùn)行hibernate會自動創(chuàng)建數(shù)據(jù)表
對應(yīng)的數(shù)據(jù)表