hibernate 记录2

阅读更多
记录让头发掉的少。

简单写一个hibernate实现数据库操作Demo;


1.首先将hibernate-jars下载下来,创建java项目将依赖引入到项目中。

2.创建实体类:

public class Employee {  
    private int id;  
    private String firstName,lastName;  

    public int getId() {  
        return id;  
    }  
    public void setId(int id) {  
        this.id = id;  
    }  
    public String getFirstName() {  
        return firstName;  
    }  
    public void setFirstName(String firstName) {  
        this.firstName = firstName;  
    }  
    public String getLastName() {  
        return lastName;  
    }  
    public void setLastName(String lastName) {  
        this.lastName = lastName;  
    }  

}


3.创建持久化类的映射文件(映射文件用于数据库中数据的持久化)
  
  

   
  
    
      
       
      

      
      

    


4.创建配置文件
   配置文件的主要内容:connection_url(数据库连接地址),diver_class(数据库驱动),username:数据库用户名,password:登录密码  等。mapper标签中是程序的会话管理。






    

        com.mysql.jdbc.Driver
        jdbc:mysql://localhost:3306/test
        root
        123456
        org.hibernate.dialect.MySQL5InnoDBDialect
        true
          
    


5.创建操作类

 
ublic class StoreData {  
    public static void main(String[] args) {  

        //创建连接  
        Configuration cfg=new Configuration();  
        cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file  

        //创建会话工厂  
        SessionFactory factory=cfg.buildSessionFactory();  

        //创建会话 
        Session session=factory.openSession();  

        //创建事务
        Transaction t=session.beginTransaction();  

        Employee e1=new Employee();
        e1.setId(100);
        e1.setFirstName("Max");
        e1.setLastName("Su");

        session.persist(e1);//持久化数据

        t.commit();//提交事务
        session.close();  //关闭事务

        System.out.println("successfully saved");  

    }  


6. 在数据库中创建tb_employee
CREATE TABLE `tb_employee` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `firstName` varchar(32) NOT NULL DEFAULT '',
  `lastName` varchar(32) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=101 DEFAULT CHARSET=utf8;




你可能感兴趣的:(hibernate)