`

hiber初步学习

阅读更多

以前学过Hiblernate 但现在忘的机乎是忘的干干净净了,现在又开始复习了!!


创建一新 表格!


新建一个新的java project就行


配置环境; 导包有 Hibernate3核心库 还有一大堆的lib里的库,和 mysql的连接库


新建一个User类  基属性有:

        private String id;

        private String name;

        private String password;

        private Date creatTime;

        private Date expireTime;


在同一个包内 为这个User写一个应射文件 User.hbm.xml 这个文件可以是xml 也可以是 properites的 xml是流行的


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

////////靠!这部分么被自动删了,标签都不让写啊

然后在 src下面写一个hibernate.cfg.xml

<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

////////靠!这部分么被自动删了,标签都不让写啊


  org.hibernate.dialect.MySQLDialect
  com.mysql.jdbc.Driver
  jdbc:mysql://localhost/hibernate_first
  root
  123456
 
 
 




然后写一个生成类 ExportDB。java

import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;



public class ExportDB {

public static void main(String[] args) {
  Configuration config = new Configuration().configure();
 
  SchemaExport se = new SchemaExport(config);
 
  se.create(true, true);
}

}



程序首先 执行这个类,config  是hibernate.hbm.xml的信息 里面可以找到 我们的应射文件,这样就关连起来了:


这样也就在数据库里面创建了一个新的表



加入一条为:


import java.util.Date;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Insert {

/**
  * 用hibernate来插入一条记录到user
  * @param args
  */
public static void main(String[] args) {
  Configuration config = new Configuration().configure();
 
  SessionFactory sf= config.buildSessionFactory();
  Session session = null;
 
     try {
   session = sf.openSession();
  
   session.beginTransaction();
  
   User user = new User();
   user.setCreatTime(new Date());
   user.setExpireTime(new Date());
   user.setName("吕成龙");
   user.setPassword("123456");
  
   session.save(user);
  
   session.getTransaction().commit();
  } catch (HibernateException e) {
   session.getTransaction().rollback();
   e.printStackTrace();
  }finally {
   if(session != null) {
    if(session.isOpen()) {
     session.close();
    }
   }
  }

 
}

}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics