Hibernate开发备用

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
简介:
Hibernate开发备用
 
平时做小测试用的,稍微修改一下就可以用到正式开发环境中。
 
 
一、配置文件
<?xml version='1.0' encoding='gb2312'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        " [url]http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd[/url]">
<hibernate-configuration>
    <session-factory>
        <!--显示执行的SQL语句-->
        <property name="show_sql">true</property>
        <!--连接字符串-->
        <property name="connection.url">
            jdbc:mysql://localhost:3306/testdb
        </property>
        <!--连接数据库的用户名-->
        <property name="connection.username">root</property>
        <!--数据库用户密码-->
        <property name="connection.password">leizhimin</property>
        <!--数据库驱动-->
        <property name="connection.driver_class">
            com.mysql.jdbc.Driver
        </property>
        <!--选择使用的方言-->
        <property name="dialect">
            org.hibernate.dialect.MySQLDialect
        </property>
        <!--设置Hibernate自动管理上下文的策略-->
        <property name="current_session_context_class">thread</property>
        <!--JDBC连接池(使用内置的连接池)-->
        <property name="connection.pool_size">1</property>
        <!--是否使用数据库外连接-->
        <!--<property name="hibernate.use_outer_join">true</property>-->
        <!--事务管理类型,这里使用JDBC Transaction-->
        <property name="hiberante.transaction.factory_class">
            org.hibernate.transaction.JDBCTransactionFactory
        </property>
        <!--在启动时删除并重新创建数据库-->
        <!--<property name="hbm2ddl.auto">create</property>-->

        <mapping resource="org/lavasoft/domain/zvfims/reg/user/entity/TUser.hbm.xml"/>
        <mapping resource="org/lavasoft/domain/zvfims/reg/user/entity/TTest.hbm.xml"/>

    </session-factory>
</hibernate-configuration>
 
 
二、HibernateUtil.java
package org.lavasoft.domain.common;
import org.hibernate.Session;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
 * Created by IntelliJ IDEA.
 * User: leizhimin
 * Date: 2007-7-18
 * Time: 10:18:44
 * Hibernate工具类
 */
public class HibernateUtil {
    private static String CONFIG_FILE_LOCATION = "hibernate.cfg.xml";
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static Configuration configuration = new Configuration();
    private static SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;
    static {
        try {
            configuration.configure(configFile);
            sessionFactory = configuration.buildSessionFactory();
        } catch (Exception e) {
            System.err.println("%%%% Error Creating SessionFactory %%%%");
            e.printStackTrace();
        }
    }
    private HibernateUtil() {
    }
    /**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     * @return Session
     * @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        if (session == null || !session.isOpen()) {
            if (sessionFactory == null) {
                rebuildSessionFactory();
            }
            session = (sessionFactory != null) ? sessionFactory.openSession() : null;
            threadLocal.set(session);
        }
        return session;
    }
    /**
     * 重新构建SessionFactory
     */
    public static void rebuildSessionFactory() {
        try {
            configuration.configure(configFile);
            sessionFactory = configuration.buildSessionFactory();
        } catch (Exception e) {
            System.err.println("%%%% Error Creating SessionFactory %%%%");
            e.printStackTrace();
        }
    }
    /**
     * Close the single hibernate session instance.
     *
     * @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);
        if (session != null) {
            session.close();
        }
    }
    /**
     * return session factory
     */
    public static org.hibernate.SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    /**
     * return session factory
     * <p/>
     * session factory will be rebuilded in the next call
     */
    public static void setConfigFile(String configFile) {
        HibernateUtil.configFile = configFile;
        sessionFactory = null;
    }
    /**
     * return hibernate configuration
     */
    public static Configuration getConfiguration() {
        return configuration;
    }
}
 
 
三、xdoclet-build.xml
<?xml version="1.0" encoding="gb2312"?>
<project name="xdoclet-build" default="xdoclet" basedir=".">
    <property name="project.lib.dir" value="${basedir}/lib"/>
    <property name="xdoclet.lib.dir" value="${project.lib.dir}/xdoclet"/>
    <property name="project.src.dir" value="${basedir}/src"/>
    <property name="project.sql.dir" value="${basedir}/doc/dbscript"/>
    <property name="project.resources.dir" value="${basedir}/doc/res"/>
    <property name="hibernate.cfg.dialect" value="org.hibernate.dialect.MySQLDialect"/>
    <property name="hibernate.cfg.driver" value="com.mysql.jdbc.Driver"/>
    <property name="hibernate.cfg.username" value="root"/>
    <property name="hibernate.cfg.password" value="leizhimin"/>
    <property name="hibernate.cfg.jdbcurl" value="jdbc:mysql://localhost:3306/testdb"/>
    <property name="hibernate.cfg.showsql" value="true"/>
    <property name="module.name" value="doc"/>

    <target name="xdoclet">
        <path id="xdoclet.task.classpath">
            <fileset dir="${xdoclet.lib.dir}">
                <include name="**/*.jar"/>
            </fileset>
            <fileset dir="${project.lib.dir}">
                <include name="**/*.jar"/>
            </fileset>
        </path>
        <taskdef name="hibernatedoclet"
            classname="xdoclet.modules.hibernate.HibernateDocletTask"
            classpathref="xdoclet.task.classpath"/>
    </target>
    <target name="generate-mapping" depends="xdoclet">
        <hibernatedoclet destdir="${project.src.dir}" verbose="true" force="false">
            <fileset dir="${project.src.dir}">
                <include name="**/domain/**/*.java"/>
            </fileset>
            <hibernate version="3.0" xmlencoding="gb2312"/>
        </hibernatedoclet>
    </target>
    <target name="generate-configuration" depends="xdoclet">
        <hibernatedoclet destdir="${project.resources.dir}" verbose="true"
            force="true">
            <fileset dir="${project.src.dir}">
                <include name="**/entity/*.java"/>
            </fileset>
            <hibernatecfg destinationFile="${project.resources.dir}/hibernate.cfg.xml"
                dialect="${hibernate.cfg.dialect}"
                driver="${hibernate.cfg.driver}"
                username="${hibernate.cfg.username}"
                password="${hibernate.cfg.password}"
                jdbcurl="${hibernate.cfg.jdbcurl}"
                showsql="${hibernate.cfg.showsql}"
                destdir="${project.resources.dir}" xmlencoding="gb2312"/>
        </hibernatedoclet>
    </target>
    <target name="generate-schema" depends="xdoclet">
        <taskdef name="schemaexport"
            classname="org.hibernate.tool.hbm2ddl.SchemaExportTask"
            classpathref="xdoclet.task.classpath"/>
        <property name="hibernate.dialect" value="${hibernate.cfg.dialect}"/>
        <property name="hibernate.format_sql" value="true"/>
        <property name="hibernate.use_sql_comments true" value="true"/>
        <schemaexport quiet="no" text="yes" drop="no" delimiter=";"
            output="${project.sql.dir}/hb_test1.sql">
            <fileset dir="${project.src.dir}">
                <include name="**/domain/**/*.hbm.xml"/>
            </fileset>
        </schemaexport>
    </target>
    <target name="generate-schema-all" depends="xdoclet">
        <taskdef name="schemaexport"
            classname="org.hibernate.tool.hbm2ddl.SchemaExportTask"
            classpathref="xdoclet.task.classpath"/>
        <property name="hibernate.dialect" value="${hibernate.cfg.dialect}"/>
        <property name="hibernate.format_sql" value="true"/>
        <property name="hibernate.use_sql_comments true" value="true"/>
        <schemaexport quiet="no" text="yes" drop="no" delimiter=";"
            output="${project.sql.dir}/hb_test2.sql">
            <fileset dir="${project.src.dir}">
                <include name="**/domain/**/*.hbm.xml"/>
            </fileset>
        </schemaexport>
    </target>
</project>
 
 

本文转自 leizhimin 51CTO博客,原文链接:http://blog.51cto.com/lavasoft/35211,如需转载请自行联系原作者
相关实践学习
如何快速连接云数据库RDS MySQL
本场景介绍如何通过阿里云数据管理服务DMS快速连接云数据库RDS MySQL,然后进行数据表的CRUD操作。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
6月前
|
Java 数据库连接 API
解锁高效开发秘籍:深入探究 Hibernate 如何优雅处理一对多与多对多关系,让数据映射再无烦恼!
【9月更文挑战第3天】Hibernate 是 Java 领域中最流行的 ORM 框架之一,广泛用于处理实体对象与数据库表之间的映射。尤其在处理复杂关系如一对多和多对多时,Hibernate 提供了丰富的 API 和配置选项。本文通过具体代码示例,展示如何使用 `@OneToMany`、`@JoinColumn`、`@ManyToMany` 和 `@JoinTable` 等注解优雅地实现这些关系,帮助开发者保持代码简洁的同时确保数据一致性。
119 4
|
6月前
|
SQL Java 数据库连接
Hibernate 批量操作来袭!掌握最佳实践,轻松应对数据洪流,开启高效开发新时代
【9月更文挑战第3天】在软件开发中,高效数据操作至关重要。作为流行的Java持久化框架,Hibernate提供了强大的数据库操作功能。本文探讨了Hibernate批量操作,包括批量插入、更新和删除的最佳实践,通过使用原生SQL和`Session`的`createNativeQuery()`方法,结合`addBatch()`及`executeBatch()`方法实现高效批量操作。合理设置批量大小、事务管理和性能测试是优化的关键。在实际开发中,应根据业务需求和性能要求选择合适的方法,以提升程序性能和可维护性。
353 3
|
7月前
|
SQL Java 数据库连接
Hibernate 是一款开源 ORM(对象关系映射)框架,封装了 JDBC,允许以面向对象的方式操作数据库,简化了数据访问层的开发。
Hibernate 是一款开源 ORM(对象关系映射)框架,封装了 JDBC,允许以面向对象的方式操作数据库,简化了数据访问层的开发。通过映射机制,它可以自动处理对象与数据库表之间的转换,支持主流数据库,提高了代码的可移植性和可维护性。其核心接口包括 SessionFactory、Session 和 Transaction 等,通过它们可以执行数据库的 CRUD 操作。配置方面,需在项目中引入 Hibernate 及数据库驱动依赖,并创建 `hibernate.cfg.xml` 配置文件来设置数据库连接和 Hibernate 行为参数。
89 1
|
7月前
|
数据库 开发者 Java
颠覆传统开发:Hibernate与Spring Boot的集成,让你的开发效率飞跃式提升!
【8月更文挑战第31天】在 Java 开发中,Spring Boot 和 Hibernate 已成为许多开发者的首选技术栈。Spring Boot 简化了配置和部署过程,而 Hibernate 则是一个强大的 ORM 框架,用于管理数据库交互。将两者结合使用,可以极大提升开发效率并构建高性能的现代 Java 应用。本文将通过代码示例展示如何在 Spring Boot 项目中集成 Hibernate,并实现基本的数据库操作,包括添加依赖、配置数据源、创建实体类和仓库接口,以及在服务层和控制器中处理 HTTP 请求。这种组合不仅简化了配置,还提供了一套强大的工具来快速开发现代 Java 应用程序。
512 0
|
SQL XML Java
Mybatis01入门+使用和配置+面试题mybatis与hibernate的区别+ssm与ssh2开发对比
Mybatis01入门+使用和配置+面试题mybatis与hibernate的区别+ssm与ssh2开发对比
Mybatis01入门+使用和配置+面试题mybatis与hibernate的区别+ssm与ssh2开发对比
|
SQL Java 数据库连接
2021-5-14hibernate核心开发接口(API)(下)
persist() delete() 代码: update() 代码: 根据id 查询get() 根据id查询 load()
159 0
2021-5-14hibernate核心开发接口(API)(下)
|
XML Java 数据库连接
2021-5-14hibernate核心开发接口(API)(上)
0. hibernate应用程序体系结构视图 1. Hibernate 核心接口API ① Configuration接口 ② SessionFactory接口 ③ Session接口 概述 session对象的获取 a. 获取方式(两种): b. 两种方法的比较 session中的常用方法 CURD(增删查改) CURD-定义工具类 提取共享代码 创建HbnUtils工具类 类、表结构 CURD增删改的实现 save() persist() delete() update() 根据`id` 查询get() 根据`id`查询 load() `get()`和`load()` 区别
142 0
2021-5-14hibernate核心开发接口(API)(上)
|
XML Java 数据库连接
Hibernate简单注解开发和事务处理(四)下
Hibernate简单注解开发和事务处理(四)
285 0
Hibernate简单注解开发和事务处理(四)下
|
XML Java 数据库连接
Hibernate简单注解开发和事务处理(四)上
Hibernate开发时,有两种形式,一种是XML配置的方式,另外一种是注解形式的开发。 XML配置是,需要写一个实体类User,还要在它的同级目录下创建一个相对应的User.hbm.xml, 而注解方式比较简单,只需要在User类中添加相应的注解即可。
200 0
Hibernate简单注解开发和事务处理(四)上
|
SQL Java 数据库连接
走进JavaWeb技术世界13:Hibernate入门经典与注解式开发
本系列文章将整理到我在GitHub上的《Java面试指南》仓库,更多精彩内容请到我的仓库里查看 https://github.com/h2pl/Java-Tutorial 喜欢的话麻烦点下Star哈 文章首发于我的个人博客: www.how2playlife.com 本文是微信公众号【Java技术江湖】的《走进JavaWeb技术世界》其中一篇,本文部分内容来源于网络,为了把本文主题讲得清晰透彻,也整合了很多我认为不错的技术博客内容,引用其中了一些比较好的博客文章,如有侵权,请联系作者。

热门文章

最新文章