一、hibernate环境搭建:
1、首先建立一个java项目,引入hibernate的jar包:
</hibernate-configuration>
二、hibernate入门小例子:
private String id;private String name;private String password;private Date createTime;private Date expireTime;
注:get,set方法省略没写...
< hibernate-mapping ><class name="com.tgb.hibernate.User"><id name="id"><generator class="uuid" /></id><property name="name" /><property name="password" /><property name="createTime" /><property name="expireTime" /></class></hibernate-mapping>
}public static void main(String[] args) {// 默认读取hibernate.cfg.xml文件//注意:因在配置文件中配置的数据库名字为hibernate_first,导出之前确保数据库中有这个库Configuration cfg =new Configuration().configure();SchemaExport export =new SchemaExport(cfg);export.create(true, true);}
public class Client {public static void main(String[] args) {// 默认读取hibernate.cfg.xml文件Configuration cfg=new Configuration().configure();// 创建Session工厂SessionFactory factory=cfg.buildSessionFactory();Session session=null;try{//打开sessionsession=factory.openSession();//开启事务session.beginTransaction();User user=new User();user.setName("张三");user.setPassword("123");user.setCreateTime(new Date());user.setExpireTime(new Date());session.save(user);//提交事务session.getTransaction().commit();}catch(Exception e){session.getTransaction().rollback();e.printStackTrace();}finally{if (session !=null){if (session.isOpen()){session.close();}}}}}