美文网首页
Hibernate核心的配置文件&编写Hibernate入门代码

Hibernate核心的配置文件&编写Hibernate入门代码

作者: Cc_e789 | 来源:发表于2018-05-08 18:27 被阅读0次

这里是以我的Mysql为例子


<?xml version="1.0" encoding="UTF-8"?>

<!-- * 默认的命名规则为:实体类名.hbm.xml

    * 在xml配置文件中引入约束(引入的是hibernate3.0的dtd约束,不要引入4的约束) -->

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<!-- 先配置SessionFactory标签,一个数据库对应一个SessionFactory标签 -->

    <session-factory>

        <!-- 必须配置的5个参数:4个参数和1个数据库方言-->

        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>

        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_day01</property>

        <property name="hibernate.connection.username">root</property >

        <property name="hibernate.connection.password">123</property >

        <!-- 数据库方言-->

        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- 可选配置-->

        <property name="hibernate.show_sql">true</property><!-- 显示sql语句-->

        <property name="hibernate.format_sql"> true</property><!--格式化显示sql语句i-->

        <property name="hibernate.hbm2ddl.auto">update</property><!-- 如果没有表结构,会更新(添加)数据表结构,并更新数据,但不会删除原有表结构(只能添加/更新,不能删除); 如果有表结构,不会创建数据表结构,但会添加数据

,如果要修改表结构,需要在数据库中手动修改表结构 -->

        <!-- 开发时,update用的多 -->

        <property name="hibernate.hbm2ddl.auto">validate</property>

        <!--校验javaBean属性与数据库字段是否匹配 -->

        <!-- 映射配置文件,需要引入映射的配置文件(按ctrl+左键点击,能跳转,则引入成功) -->

        <mapping resource="domain/customer.hbm.xml" />

    </session-factory>

</hibernate-configuration>


编写Hibernate入门代码

/**

* 测试保存客户

*/

@Test

public void testSave() {

// 1 先加载配置文件

//        Configuration config=new Configuration();

        // 2 默认加载src目录下的配置文件

//        config.configure();//如果使用的是xml文件,必须执行这个方法。如果使用的是属性文件,可以不用执行这个方法

//        config.addResource("domain/customer.hbm.xml");//如果xml里没写映射配置文件,则要手动添加映射配置文件

        Configuration config=new Configuration().configure();//上面几行的简写代码(方法链的编程)

        // 3 创建SessionFactory对象

        SessionFactory factory=config.buildSessionFactory();

        // 4 创建session对象

        Session session =factory.openSession();

        // 5 开启事务

        Transaction tr=session.beginTransaction();

        // 6 编写保存代码

        Customer c=new Customer();

        c.setCust_name("IamCc10");

        c.setCust_level("10");

        // c.setCust_id(cust_id);  已经自动递增

        // 7 保存客户

        session.save(c);

        // 8 提交事务

        tr.commit();

        // 9 释放资源

        session.close();

        factory.close();

}

相关文章

网友评论

      本文标题:Hibernate核心的配置文件&编写Hibernate入门代码

      本文链接:https://www.haomeiwen.com/subject/ocmwrftx.html