传智播客——hibernate细节(一)

本文深入探讨了Hibernate作为连接Java应用与关系型数据库的中间件的作用,详细介绍了其作为持久化层的功能,以及如何通过ORM映射工具进行对象持久化操作。包括配置文件、映射文件的使用,以及一个简单的例子实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一 Hibernate是什么
1)连接java应用程序和关系型数据库的中间件
2)对JDBC API封装,负责对象持久化
3)位于持久化层,封装所有的数据访问细节,使业务逻辑层更关注于业务逻辑。
4)一种ORM映射工具。
二 hibernate简单例子实现
1)导入jar包,当然不能忘了相应的数据库驱动文件
 2)数据库中建一个表,当然也可以用hibernate自动建表
Customers( id int primary key, name varchar(20), age int, birthday datetime, married int , photo longblob, | blob(oracle) | image(sqlserver) description text | clob(oracle) | text(sqlserver) )
3)创建一个需要持久化存储的JavaBean类
public class Customer { private Integer id ; private String name ; private Integer age ; private Date birthday ; private boolean married ; private byte[] photo ; private String description ; 相应的get/set方法
4) 
创建映射文件Customer.hbm.xml[跟类在一起,名称一致,规范]
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC                               //hibernate.jar/org.hiberante.Hibernate-mapping.dtd
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="cn.itcast.hibernate.pesistence.Customer" table="customers" lazy="false">
<id name="id" column="id" type="integer">
<generator class="increment" />
</id>
<property name="name" column="name" type="string" />
<property name="age" column="age" type="integer" />
<property name="birthday" column="birthday" type="date" />
<property name="married" column="married" type="boolean" />
<property name="photo" column="photo" type="binary" />
<property name="description" column="description" type="text" />
</class>
</hibernate-mapping>
  }
5)创建配置文件.src/hibernate.properties
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost:3306/hibernate
hibernate.connection.username=root
hibernate.connection.password=root
//方言是对底层数据库所用自身机制的配置(注册,比如函数,数据类型,过程之类)
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=true
6)测试类App
public class App {
//相当于连接池(数据源)
private static SessionFactory sf = null ;
static{
try {
//加载属性文件,hibernate.properties
Configuration conf = new Configuration();
//加载映射文件
conf.addClass(Customer.class);
//构建回话工厂,初始化会话工厂
sf = conf.buildSessionFactory();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Customer c = new Customer();
c.setName("tom");
insertCustomer(c);
}
public static void insertCustomer(Customer c){
Session s = sf.openSession();
//开始事务:acid
Transaction tx = s.beginTransaction();
s.save(c);
tx.commit();
s.close();
}
}
学习总结:同是框架struts就容易很多,hibernate就让人很晕,老师今天只是讲了一点点的映射关系,我就傻了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值