建立使用hibernate的过程:
1. 导入包文件(本例导入hibernate5.1.0final版本),只需导入request文件夹下的包以及mysql驱动包,需要测试的话需要导入Juint.jar,具体如图:
2. 配置cfg文件:
创建hibernate.cfg.xml文件,可以在互联网中搜索一个样本,具体配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">123456</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/wycm_hibernate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>
其中hbm2dll.auto这个参数指的是需要自动创建新表.其他参数的含义根据语义理解即可
3. 创建单例模式的SessionFactory.由于工厂只需要一个单例来维护session的生成,所以把工厂创建的过程写到hibernateUtil这个类中,创建单例模式.
- 创建pojo类,并对此类进行声明,并设置getter,setter方法.
package org.wycm.dao;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name=”t_news”)
public class News {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String title;
private String content;
public int getId() {
return id;
}
public void setId(int 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;
}
}
5. 建立session,并进行测试
package org.wycm.test;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import org.wycm.dao.News;
import org.wycm.util.HibernateUtil;
public class test01 {
@Test
public void test() {
Session session=HibernateUtil.openSession();//开启session
Transaction tx=session.beginTransaction();//开启事务
News news=new News();
news.setTitle("aaa");
news.setContent("bbb");
session.save(news);
tx.commit();//进行提交
HibernateUtil.closeSession(session);
}
}