最近在做项目的时候,发现项目的关于数据持久化用的是hibernate框架,小编就针对于hibernate做了点儿整理。
一、是什么
关于hibernate是什么的东西,大家都会想到它是关于数据持久化的框架。
什么是框架?
在我看来框架就是一种工具,可以让我们的开发变得简单的工具。
怎么让我们的开发变得简单?
通过引入一些jar包来简化我们对于数据库操作的代码,通过这些jar包可以让我们可以利用很简单的语句来完成我们想要的功能,提高了我们开发的效率,减少了开发成本。
二、怎么用
1、用.xml文件来设置数据库连接,并设置一些其他的属性:
<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/hibernate3</property>
<!-- 数据库用户名 -->
<property name="hibernate.connection.username">root</property>
<!-- 数据库密码 -->
<property name="hibernate.connection.password">123456</property>
<!-- 方言:mysql -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 是否显示SQL语句 -->
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!-- 实体类映射文件 -->
<mapping resource="com/test/hibernate/User.hbm.xml"/>
</session-factory>
</hibernate-configuration> 2、编写实体类:
public class User {
private String id;
private String name;
private String password;
private Date createTime;
private Date expireTime;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getExpireTime() {
return expireTime;
}
public void setExpireTime(Date expireTime) {
this.expireTime = expireTime;
}
} 3、设置实体类的.xml映射文件:
<hibernate-mapping>
<class name="com.test.hibernate.User" >
<id name="id">
<generator class="uuid"/>
</id>
<property name="name"/>
<property name="password"/>
<property name="createTime"/>
<property name="expireTime"/>
</class>
</hibernate-mapping> 4、书写可以生成数据库表的工具类:
public static void main(String[] args) {
// TODO Auto-generated method stub
Configuration cfg = new Configuration().configure();
SchemaExport export = new SchemaExport(cfg);
export.create(true, true);
}5、去MySQL中创建数据库,并执行工具类,去数据库中查看数据库表是不是生成成功。
三、优缺点
优点:
(1) hibernate可以很大程度上减少我们的代码量
(2)开发更加对象化,我们在操作的时候更多的是针对对象来进行操作的
(3)具有移植性
(4)没有入侵性,支持透明持久化。
缺点:
(1)使用数据库特性的语句很难调优
(2)对大批量数据更新存在问题
(3)存在大量的统计查询功能,性能相对原生SQL要差很多
Hibernate框架详解

被折叠的 条评论
为什么被折叠?



