hibernate中使用configuration类配置数据库以及实体类映射

背景:在搭建框架的时候,多数教程都是直接从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");
    }
}

转载于:https://my.oschina.net/u/4178300/blog/3082875

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值