Day28 Hibernate第一天

2019-05-31  本文已影响0人  开发猛男

框架的使用和概念在讲义上很清楚,不再重复。

1. mysql数据库中bigint(32)对应java中long类型

2. Java Bean属性,使用基本类型相对应的包装类。例如int默认值为0,而Integer为null,避免出错。

3. Hibernate是一个持久层的ORM框架。

4. ORM(Object Relational Mapping)对象关系映射

ORM示意图

5. SessionFactory

6. Session

快速入门

1. 下载相关jar包

2. 创建数据库和表

3. 搭建环境,创建web项目,导入jar包

4. 配置映射文件示例

 <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC 
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

    <hibernate-mapping>
        <class name="com.itheima.domain.Customer" table="cst_customer">
              <!--id设置主键属性-->
            <id name="cust_id" column="cust_id">
                <generator class="native"/>
            </id>
              <!--property设置各字段映射关系-->
            <property name="cust_name" column="cust_name"/>
            <property name="cust_user_id" column="cust_user_id"/>
            ....
        </class>
    </hibernate-mapping>
5. 配置核心文件
  <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

    <hibernate-configuration>
        <session-factory>
            <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
            <property name="hibernate.connection.url">jdbc:mysql:///hibernate_day01</property>
            <property name="hibernate.connection.username">root</property>
            <property name="hibernate.connection.password">root</property>
            <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

            <mapping resource="com/itheima/domain/Customer.hbm.xml"/>
        </session-factory>
    </hibernate-configuration>

6. 编写代码

@Test
    public void testSave(){
        // 先加载配置文件
        Configuration config = new Configuration();
        // 默认加载src目录下的配置文件
        config.configure();
        // 创建SessionFactory对象
        SessionFactory factory = config.buildSessionFactory();
        // 创建session对象
        Session session = factory.openSession();
        // 开启事务
        Transaction tr = session.beginTransaction();
        // 编写保存代码
        Customer c = new Customer();
        // c.setCust_id(cust_id);   已经自动递增
        c.setCust_name("测试名称");
        c.setCust_mobile("110");
        // 保存客户
        session.save(c);
        // 提交事务
        tr.commit();
        // 释放资源
        session.close();
        factory.close();
    }
上一篇 下一篇

猜你喜欢

热点阅读