zoukankan      html  css  js  c++  java
  • Hibernate入门 :不使用hibernate.cfg.xml

    一般,我们都会创建一个hibernate.cfg.xml,这样做无疑是好的,下面讲的方法虽然不好,但是也无疑是一种方法;

    我们可以直接在代码中设置一系列的参数;


    主要函数:


    (1)Configuration config = new Configuration(); //创建配置

    (2)config.setProperties(Properties p); //导入配置

    (3)config.addClass(Class c); //创建映射(只需要指定Class对象,自动搜索映射文件)


    特别注意:在代码中配置参数时,参数前面必须加上hibernate,比如 hibernate.connection.username,不能写成connection.username,如果不加,则会报错。


    package org.xiazdong;
    
    import java.util.Properties;
    
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.hibernate.cfg.Configuration;
    import org.hibernate.classic.Session;
    
    public class UserTest {
    
    	public static void main(String[] args) {
    		Properties p = new Properties();
    		p.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
    		p.put("hibernate.connection.url", "jdbc:mysql:///hibernate");
    		p.put("hibernate.connection.username", "root");
    		p.put("hibernate.connection.password", "12345");
    		p.put("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect");
    		p.put("hibernate.hbm2ddl.auto","update");
    		Configuration conf = new Configuration().setProperties(p).addClass(User.class);
    		SessionFactory sf = conf.buildSessionFactory();
    		Session session = sf.openSession();
    		Transaction tx = session.beginTransaction();
    		User u = new User();
    		u.setName("xiazdong-1");
    		u.setAge(20);
    		session.save(u);
    		tx.commit();
    		session.close();
    		sf.close();
    	}
    
    }
    


  • 相关阅读:
    【VUE3.0体验】关于路由的一些坑
    TensorFlow中的卷积函数
    TensorFlow源码安装
    ubuntu远程桌面
    TensorFlow图像处理API
    C程序员眼里的Python
    深度剖析HashMap的数据存储实现原理(看完必懂篇)
    golang 互斥锁和读写锁
    golang goroutine的调度
    golang channel的使用以及调度原理
  • 原文地址:https://www.cnblogs.com/xiazdong/p/3058024.html
Copyright © 2011-2022 走看看