背景:在搭建框架的时候,多数教程都是直接从hibernate.cfg.xml或其他命名的xml文件获取hibernate配置文件。小鱼在这里给大家介绍一种比较冷门的配置方法,或许大家可以用到。
场景:普通非web的java应用使用hibernate,使用hibernate.cfg.configuration类进行编程式配置。
提供session的hibernate工具类:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtils1 {
private static Configuration cfg = null;
private static SessionFactory factory = null;
private static Session session = null;
static {
cfg = new Configuration().setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver")
.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/aleavesystem?pinGlobalTxToPhysicalConnection=true&characterEncoding=UTF-8")
.setProperty("hibernate.connection.username", "root")
.setProperty("hibernate.connection.password", "root").addAnnotatedClass(Employee.class);
;
factory = cfg.buildSessionFactory(new StandardServiceRegistryBuilder().applySettings(cfg.getProperties())
.build());
}
public static Session getSession() {
if(factory != null) {
return factory.openSession();
}else{
factory = cfg.buildSessionFactory(new StandardServiceRegistryBuilder().applySettings(cfg.getProperties())
.build());
}
return factory.openSession();
}
public static void closeSession() {
if(session != null && session.isOpen()){
session.close();
}
}
}
说明:参阅了hibernate的接口文档,org.hibernate.cfg.Configuration类提供设置property属性的方法setProperty,参数格式(属性名称,属性值),例如设置数据库连接为setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/aleavesystem?characterEncoding=UTF-8"),其他属性依次类推,可以面条式增加属性configuration.setProperty("a","1").setProperty("b","2")......
addAnnotatedClass,则是为实体类配置提供的方法,如上面代码addAnnotatedClass(Employee.class),配置注解实体类,同样也是可以面条式增加多个实体类addAnnotatedClass(类A).addAnnotatedClass(类B).addAnnotatedClass(类C),参数注意是class类,直接实体类后面加.class就行。
实体类Employee:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "Employee ")
public class Employee {
@Id
@Column(name = "id")
private int id;
public Employee() {}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
}
测试入口类:
import org.hibernate.*;
public class Test {
public static void main(String[] args) {
/**** 上面是配置准备,下面开始我们的数据库操作 ******/
Session session = HibernateUtils1.getSession();// 从会话工厂获取一个session
Transaction t = session.beginTransaction();
Employee e1 = new Employee();
e1.setId(1);
Employee e2 = new Employee();
e2.setId(2);
session.persist(e1);
session.persist(e2);
t.commit();
session.close();
System.out.println("successfully saved");
}
}