暂时不写web项目,以前都是用mysql的jdbc直接连接数据库的,现在打算试试用hibernate

 hibernate官网http://www.hibernate.org/

 mysql自然要先安装起来(有一种是安装版的,有一种是解压缩版本的,解压缩版本的要自己去配置很多内容),我用到的可视化工具叫做 mysql gui tool  还有mark一下 powerdesigner名字容易忘

 step1: 到官网下载 这是我下的版本Hibernate ORM 4.2.7.SP1 Released

 step2: 下载java 与 mysql的连接jar包 mysql官网就有http://dev.mysql.com/downloads/connector/j/

 step3:  用eclipse创建一个工程,然后把hibernate压缩包里的required文件夹里面的包导入到工程中

 step4:  把mysql的jar包导入到工程中

 step5:  在src文件夹中添加hibernate.cfg.xml文件 (主要需要做一些配置 比如 数据库的url 用户名 密码等,还有与student.hbm.xml的映射)

 step6:  创建一个javabean和与之配对的配置文件 比如 student.java student.hbm.xml  

 step7:  创建测试主函数进行测试运行即可


 hibernate.cfg.xml文件内容:





  
    
    com.mysql.jdbc.Driver
    jdbc:mysql://127.0.0.1:3306/db_weibo
    root
    123456
    
    1
    
    org.hibernate.dialect.MySQLDialect
    
    thread
    
    org.hibernate.cache.internal.NoCacheProvider
    
    true
    
    update
    
  


student.hbm.xml文件内容:





    
    


student.java内容:

package fjnu.hibernate.pojos;
public class student {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
    }
}


test.java内容:

public class test {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        /*
        // 驱动程序名
        String driver = "com.mysql.jdbc.Driver";
        // URL指向要访问的数据库名scutcs
        String url = "jdbc:mysql://127.0.0.1:3306/db_weibo";
        // MySQL配置时的用户名
        String user = "root";
        // MySQL配置时的密码
        String password = "123456";
         // 加载驱动程序
         Class.forName(driver);
         // 连续数据库
         Connection conn = (Connection) DriverManager.getConnection(url, user, password);
         if(!conn.isClosed())
          System.out.println("Succeeded connecting to the Database!");
         // statement用来执行SQL语句
         Statement statement = (Statement) conn.createStatement();
         // 要执行的SQL语句
         String sql = "select * from test";
         // 结果集
         ResultSet rs = statement.executeQuery(sql);
         System.out.println("-----------------");
         while(rs.next()) {
             System.out.println(rs.getString("name"));
         }*/
                                               
        Configuration configuration = new Configuration();
        configuration.configure("/hibernate.cfg.xml");
        Session session = configuration.buildSessionFactory().openSession();
        Transaction trans = session.beginTransaction();
        student s = new student();
        s.setName("hallo");
        session.save(s);
        trans.commit();
        session.clear();
    }
}

工程目录:

[s2sh]_3_hibernate与mysql还有eclipse的笔记_第1张图片