核心提示:hibernate.cfg.xmlrootrootcom.mysql.jdbc.Driverjdbc:mysql://localhost:3306/scott数据库方言 -->org.hibernat...
hibernate.cfg.xml
root root com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/scott org.hibernate.dialect.MySQLInnoDBDialect true true update
持久化类
package cn.ls.vo;
import java.sql.Date;
public class News {
private Integer id;
private String title;
@Override
public String toString() {
return "News [id=" + id + ", title=" + title + ", author=" + author + ", 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;
}
private String author;
private Date date;
public News() {
}
public News(String title, String author, Date date) {
super();
this.title = title;
this.author = author;
this.date = date;
}
}
News.hbm.xml
Test类
package cn.ls.vo;
import static org.junit.Assert.*;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class HibernateTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void test() {
//1.创建一个SessionFactory对象
SessionFactory sf=null;
//1)创建configuretion对象,对应hibernate的基本配置信息和对象关系映射信息
Configuration con= new Configuration().configure();
//4.0前这样创建
//sf =con.buildSessionFactory();
//2)创建一个ServiceRegistry对象,hibernate的任何配置和服务都需要在该对象中注册后有效
Configuration configuration=new Configuration().configure();
ServiceRegistry service=
new ServiceRegistryBuilder().applySettings(configuration.getProperties())
.buildServiceRegistry();
sf=configuration.buildSessionFactory(service);
//2.创建一个session对象
Session session=sf.openSession();
//3.开启事务
Transaction tr=session.beginTransaction();
//4.执行保存操作
News news= new News("java","ATGUIGU",(java.sql.Date) new Date());
//5.提交事务
tr.commit();
//6关闭session对象
session.close();
//7.关闭SessionFactory对象
sf.close();
}
}


