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

来源:互联网 发布:cgx什么意思网络用语 编辑:程序博客网 时间:2024/04/30 15:34

一 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 Stringdescription ; 相应的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就让人很晕,老师今天只是讲了一点点的映射关系,我就傻了

原创粉丝点击