对hiberfnate的认识:hibernate是冬眠的意思,按照开发思想来理解是让数据冬眠,也就是让数据持久化。
hiberante的出现是方便jdbc的操作,在jdbc的基础上发展起来的。我们使用jdbc的时候有很多弊端,在使用jdbc的时候我们大部分时间都实在在写相同重复的代码,对开发很不利,但hibernate做到了让对数据库的操作,简单明了化,是开发人员不用写重复的代码,让开发变的得心应手。
第一个hibernate程序
1 在数据库中建立数据库
2 在java中用数据库的字段建立实体
3 加入hibernate的官方jar包
4.添加映射文件 XXX.hbm.xml
XXX应该和实体的名字相同
找xml的dtd头,找到jar包中hibernat.jar的第一个包 进入包中倒数第二个里面有dtd文件头
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="cn.itcast.hibernate.domain.Customer" table="customers" lazy="false"> <id name="id" column="id" type="integer"> <generator class="increment"></generator> </id> <property name="name" column="name" type="string"></property> <property name="age" column="age" type="integer"></property> <property name="birthday" column="birthday" type="date"></property> <property name="married" column="married" type="boolean"></property> <property name="photo" column="photo" type="binary"></property> <property name="description" column="description" type="text"></property> </class> </hibernate-mapping>
5 添加跟数据库交互的文件hibernate.properties
加入hibernate.properties 文件,当我们执行相应的语句时,hibernate的相关jar包就会对自动和数据库链接
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.show_sql=true hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
6 写方法进行测试
1.首选应该创建会话工厂 应该读取配置文件和映射文件
2.打开会话
3.开启事物
4.操作会话
5.提交事物
6.关闭会话
package cn.itcast.hibernate.factory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import cn.itcast.hibernate.domain.Customer;
public class App {
//sessionFactory 就是对数据源的封装
public static SessionFactory sf = null;
static{
//加载hibernate.properties文件
Configuration conf = new Configuration();
//加载映射文件
conf.addClass(Customer.class);
sf = conf.buildSessionFactory();
}
public static void main(String[] args) {
Customer c = new Customer();
c.setName("Tom");
inserCustomer(c);
}
public static void inserCustomer(Customer c){
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
session.save(c);
tx.commit();
session.close();
}
}
注意:运行可能出错 要加入第三方的jar包 log4j slf-log4j.jar
hibernate的数据类型 全部是小写和java有细微的区别