学ehcache中涉及hibernate,做一个小例子入门,记下以备后查。
1. 创建hibernate.cfg.xml,为hibernate主配置文件, 通过修改其中的session-factory中的配置,可以实现后台DB的切换。
jdbc:mysql://localhost/hibernate_first com.mysql.jdbc.Driver root beauty org.hibernate.dialect.MySQLDialect true
2. 定义实体类User
package com.bjsxt.hibernate;import java.util.Date;public class User { private String id; private String name; private String password; private Date createTime; private Date expireTime; 省略getter/setter... }
3. 创建实体类映射文件User.hbm.xml(此文件可以任意命名,标准为类名.hbm.xml),位置通常与实体类放在一个package中
4. 编写hbm2ddl工具,从实体类直接生成数据库表. 注意, 表是自动导的,hibernate_first数据库是要自己手动建的
package com.bjsxt.hibernate;import org.hibernate.cfg.Configuration;import org.hibernate.tool.hbm2ddl.SchemaExport;/*将Class.hbm.xml转换为DDL文件,这个类可以反复使用的^@@^ */public class ExportDB { /** * @param args */ public static void main(String[] args) { //读取hibernate.cfg.xml配置文件 Configuration cfg= new Configuration().configure(); SchemaExport export = new SchemaExport(cfg); export.create(true,true); }}
5. 运行ExportDB ,先爽一爽
mysql> describe t_user;+------------+--------------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+------------+--------------+------+-----+---------+-------+| userid | varchar(255) | NO | PRI | NULL | || name | varchar(255) | YES | | NULL | || password | varchar(255) | YES | | NULL | || createTime | datetime | YES | | NULL | || expireTime | datetime | YES | | NULL | |+------------+--------------+------+-----+---------+-------+5 rows in set (0.36 sec)
6. 写client类,以操作对象的方法操作数据库中的数据
package com.bjsxt.hibernate;import java.util.Date;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class Client { public static void main(String[] args) { //读取hibernate.cfg.xml配置文件 Configuration cfg= new Configuration().configure(); //一个DB对应一个sessionFactory SessionFactory factory = cfg.buildSessionFactory(); Session session = null; User user =null; try{ session=factory.openSession(); session.beginTransaction(); user= new User(); user.setName("lisi"); user.setPassword("1223"); user.setCreateTime(new Date()); user.setExpireTime(new Date()); session.save(user); user.setName("wangwu"); session.getTransaction().commit(); } catch (Exception e) {e.printStackTrace(); session.getTransaction().rollback();} finally { HibernateUtils.closeSession(session); } user.setName("ac"); try{ session = HibernateUtils.getSession(); session.beginTransaction(); session.update(user); session.getTransaction().commit(); } catch(Exception e) {e.printStackTrace(); session.getTransaction().rollback(); } finally { HibernateUtils.closeSession(session); } }}
7. 书写测试用例,从DB中取数据
package com.bjsxt.hibernate;import java.util.Iterator;import java.util.List;import org.hibernate.Query;import org.hibernate.Session;import junit.framework.TestCase;public class QueryTest extends TestCase { public void testQuery() { Session session=null; try{ session= HibernateUtils.getSession(); session.beginTransaction(); Query query = session.createQuery("from User"); query.setFirstResult(0); query.setMaxResults(2); List userList = query.list(); for (Iterator iter = userList.iterator();iter.hasNext();) { User user = (User)iter.next(); System.out.println(user.getId()+"---"+ user.getName()); } session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); session.getTransaction().rollback(); } finally { HibernateUtils.closeSession(session); } }}
运行结果如下:
Hibernate: select user0_.userid as userid0_, user0_.name as name0_, user0_.password as password0_, user0_.createTime as createTime0_, user0_.expireTime as expireTime0_ from t_user user0_ limit ?402880e43b5ba096013b5ba097a30001---second402880e43b5ba0ab013b5ba0ac070001---second
hibernate较好的实现了对底层jdbc的封装,代码中看不到jdbc的迹象,极大的简化了DAO层开发。
但它对sql的掌握力较差,不能操作底层sql算是不足之处。