<hibernate-configuration> <session-factory> <!-- 指定数据库所连接的驱动 --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <!-- 指定数据库连接的url --> <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property> <!-- 指定数据库连接的用户名 --> <property name="connection.username">root</property> <!-- 指定数据库连接的密码 --> <property name="connection.password">123456</property> <!-- 指定连接池里面的最大连接数 --> <property name="hibernate.c3p0.max_size">20</property> <!-- 指定连接池里面最小的连接数 --> <property name="hibernate.c3p0.min_size">1</property> <!-- 指定连接池里面连接超时的时长 --> <property name="hibernate.c3p0.timeout">5000</property> <!-- 指定连接池里面最大缓存多少个statement对象 --> <property name="hibernate.c3p0.max_statements">100</property> <property name="hibernate.c3p0.idle_test_period">3000</property> <property name="hibernate.c3p0.acquire_increment">2</property> <property name="hibernate.c3p0.validate">true</property> <!-- 指定数据库方言 --> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 根据需要自动创建数据库表 --> <property name="hbm2ddl.auto">update</property> <!-- 显示hibernate持久化操作生成的sql语句 --> <property name="show_sql">true</property> <!-- 将sql脚本格式化后再输出来 --> <property name="hibernate.format_sql">true</property> <!-- 映射的文件 --> <mapping resource="hbm/News.hbm.xml"/> </session-factory> </hibernate-configuration>
<hibernate-mapping> <!-- 每一个class类对应一个持久化对象 --> <class name="model.News" table="mw_news"> <id name="id"> <!-- 主键的生成策略 --> <generator class="identity"></generator> </id> <property name="title"></property> <property name="content"></property> </class> </hibernate-mapping>
public class News {
/*主键id*/
private Integer id;
/*新闻标题*/
private String title;
/*新闻内容*/
private String content;
public News(){}
public News(Integer id){
this.id=id;
}
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 getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
public class TestApplication {
public static void main(String[] args) {
Configuration configuration=new Configuration().configure();
SessionFactory sessionFactory=configuration.buildSessionFactory();
Session session=sessionFactory.openSession();
Transaction transaction=session.beginTransaction();
News news=new News();
news.setTitle("dkfhk");
news.setContent("dsjfkh");
session.save(news);
transaction.commit();
session.close();
sessionFactory.close();
}
}
注:本例中用到了c3p0连接池,需要将c3p0有关jar包也引用进来