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();
    	}
    
    }
    


  • 相关阅读:
    SpringMVC 多文件上传
    get传参乱码问题
    springMVC配置
    带参sql$和#的区别(注解)
    java多线程--实现Runnable接口方式
    java复制文件夹及所有子目录和文件
    Angularjs 学习笔记
    springboot 项目 docker化部署
    docker 基础
    Java-马士兵动态代理模式
  • 原文地址:https://www.cnblogs.com/xiazdong/p/3058024.html
Copyright © 2011-2022 走看看