zoukankan      html  css  js  c++  java
  • Hibernate之通过hibernate.cfg.xml配置文件访问数据库的例子

    hibernate.cfg.xml文件内容:

    <?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="dialect">org.hibernate.dialect.MySQLDialect</property>
      <property name="connection.autocommit">true</property>
      <property name="connection.useUnicode">true</property>
      <property name="connection.characterEncoding">UTF-8</property>
      <property name="hibernate.current_session_context_class">thread</property>
      <property name="show_sql">true</property>
      <property name="format_sql">true</property>
      <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
      <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test?useUnicode=true&amp;amp;characterEncoding=utf8</property>
      <property name="hibernate.connection.username">root</property>
      <property name="hibernate.connection.password">123456</property>
      <property name="hibernate.hbm2ddl.auto">update</property>
      <mapping resource="com/main/News.hbm.xml"/>
     </session-factory>
    </hibernate-configuration>
    News.hbm.xml文件内容:
    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <!-- Generated 2015-7-27 16:52:17 by Hibernate Tools 3.4.0.CR1 -->
    <hibernate-mapping>
        <class name="com.main.News" table="NEWS">
            <id name="id" type="int">
                <column name="ID" />
                <generator class="assigned" />
            </id>
            <property name="title" type="java.lang.String">
                <column name="TITLE" />
            </property>
            <property name="content" type="java.lang.String">
                <column name="CONTENT" />
            </property>
        </class>
    </hibernate-mapping>

    一个简单的insert操作:

    Configuration conf = new Configuration().configure();
    SessionFactory sf = conf.buildSessionFactory();
    Session sess = sf.openSession();
    Transaction tx = sess.beginTransaction();
    News n = new News();
    n.setId(11);
    n.setTitle("Title2");
    n.setContent("Content2");
    sess.save(n);
    n.setContent("editedContent");
    tx.commit();
  • 相关阅读:
    使用控制结构——循环语句——基本循环
    oracle字符类型 char,varchar2,varchar,clob,nvarchar,nclob
    使用控制结构——条件分支语句——多重条件分支
    hduoj 1518square
    运算符重载实现复数的加减乘除
    使用游标——参数游标
    开发PL/SQL子程序——触发器——编译触发器,删除触发器,显示触发器
    NYOJ58最少步数
    使用控制结构——条件分支语句——简单条件
    开发PL/SQL子程序——触发器——使用触发器注意事项
  • 原文地址:https://www.cnblogs.com/agindage/p/4683519.html
Copyright © 2011-2022 走看看