一、hibernate环境搭建:
1、首先建立一个java项目,引入hibernate的jar包:
1)打开Window-->Preferences
-->Java
-->Build Path
-->User Libraries,新建一个库命名hibernate,在其中添加hibernate所需要用的一些jar包(bin下面的和hibernate3.jar和mysql-connection.jar)
2)打开项目属性,在Java Build Path里面添加刚才添加的hibernate用户库:
2、引入hibernate环境需要用到的配置文件
一般命名为:hibernate.cfg.xml。添加配置mySql数据库信息,如下:
<
hibernate-configuration
>
<session-factory>
<!-- mySql数据库连接参数 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_first</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">***</property>
<!-- 方言(适配器):提供sql语句的转换,在此用的是mySql,故转换成mysql语句,例如分页查询 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<!--
<property name="hibernate.format_sql">true</property>
-->
</session-factory>
</hibernate-configuration>
二、hibernate入门小例子:
1、首先先建立一个映射实体类
public
class
User {
private String id;private String name;private String password;private Date createTime;private Date expireTime;
注:get,set方法省略没写...
}
2、配置实体类映射配置文件(User.hbm.xml):
1)添加User
.hbm.xml
配置文件:
< 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>
2)在
hibernate.cfg.xml配置文件中添加实体关联
<
session-factory
>
<!-- mySql数据库连接参数 -->
<!-- 此处省略没写。。。
-->
<mapping resource="com/tgb/hibernate/User.hbm.xml"/>
</session-factory>
3、建立工具类,对配置好的实体关联进行导出
public
class
ExportDB {
}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);}
4、应用(保存数据):
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();}}}}}