herbernate mysql 订单_Hibernate配置及自定义注册映射文件

Hibernate (开放源代码的对象关系映射框架)

Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,

它将POJO与数据库表建立映射关系,是一个全自动的orm框架,hibernate可以自动生成SQL

语句,自动执行,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。

Hibernate可以应用在任何使用JDBC的场合,既可以在Java的客户端程序使用,也

可以在Servlet/JSP的Web应用中使用,最具革命意义的是,Hibernate可以在应用

EJB的J2EE架构中取代CMP,完成数据持久化的重任。

一.hibernate配置属性详解

hibbernate可以在各式各样不同环境下工作而设计的, 因此存在着大量的配置参数。以简便操

作,多数配置参数都有默认的配置值,也是我们日常使用hibernate的必须品。

Hibernate JDBC属性

-----------------------------------------------------------------------------------

| 属性名 | 用途

-----------------------------------------------------------------------------------

| hibernate.connection.driver_class | jdbc驱动类

| hibernate.connection.url | jdbc URL

| hibernate.connection.username | 数据库用户

| hibernate.connection.password | 数据库用户密码

| hibernate.connection.pool_size | 连接池容量上限数目

-----------------------------------------------------------------------------------

Hibernate 数据源属性

-----------------------------------------------------------------------------------

|属性名 | 用途

-----------------------------------------------------------------------------------

|hibernate.connection.datasource | 数据源JNDI名字

|hibernate.jndi.url | DI提供者的URL (可选)

|hibernate.jndi.class | DI InitialContextFactory类 (可选)

|hibernate.connection.username | 数据库用户 (可选)

|hibernate.connection.password | 数据库用户密码 (可选)

-----------------------------------------------------------------------------------

可选的配置属性

-----------------------------------------------------------------------------------

|属性名 | 用途

----------------------------------------------------------------------------------------------------------------------------------------------------------------

hibernate.dialect | 一个Hibernate Dialect类名允许Hibernate针对特定的关系数据库生成优化的SQL.取值 full.classname.of.Dialect

hibernate.show_sql | 输出所有SQL语句到控制台. 有一个另外的选择是把org.hibernate.SQL这个log category设为debug。eg. true | false

hibernate.format_sql | 在log和console中打印出更漂亮的SQL。取值 true | false

hibernate.default_schema | 在生成的SQL中, 将给定的schema/tablespace附加于非全限定名的表名上.取值 SCHEMA_NAME

hibernate.default_catalog | 在生成的SQL中, 将给定的catalog附加于非全限定名的表名上.取值 CATALOG_NAME

hibernate.session_factory_name | SessionFactory创建后,将自动使用这个名字绑定到JNDI中.取值 jndi/composite/name

hibernate.max_fetch_depth | 为单向关联(一对一, 多对一)的外连接抓取(outer join fetch)树设置最大深度. 值为0意味着将关闭默认的外连接抓取.取值 建议在0到3之间取值

hibernate.default_batch_fetch_size | 为Hibernate关联的批量抓取设置默认数量.取值 建议的取值为4, 8, 和16

hibernate.default_entity_mode | 为由这个SessionFactory打开的所有Session指定默认的实体表现模式.取值 dynamic-map, dom4j, pojo

hibernate.order_updates | 强制Hibernate按照被更新数据的主键,为SQL更新排序。这么做将减少在高并发系统中事务的死锁。取值 true | false

hibernate.generate_statistics | 如果开启, Hibernate将收集有助于性能调节的统计数据.取值 true | false

hibernate.use_identifer_rollback | 如果开启, 在对象被删除时生成的标识属性将被重设为默认值.取值 true | false

hibernate.use_sql_comments | 如果开启, Hibernate将在SQL中生成有助于调试的注释信息, 默认值为false.取值 true | false

----------------------------------------------------------------------------------------------------------------------------------------------------------------

Hibernate JDBC和连接(connection)属性:

----------------------------------------------------------------------------------------------------------------------------------------------------------------------

属性名 | 用途

----------------------------------------------------------------------------------------------------------------------------------------------------------------------

hibernate.jdbc.fetch_size | 非零值,指定JDBC抓取数量的大小 (调用Statement.setFetchSize()).

hibernate.jdbc.batch_size | 非零值,允许Hibernate使用JDBC2的批量更新.取值 建议取5到30之间的值

hibernate.jdbc.batch_versioned_data | 如果你想让你的JDBC驱动从executeBatch()返回正确的行计数 , 那么将此属性设为true(开启这个选项通常是安全的). 同时,Hibernate将为自动版本化的数据使用批量DML. 默认值为false.eg. true | false

hibernate.jdbc.factory_class | 选择一个自定义的Batcher. 多数应用程序不需要这个配置属性.eg. classname.of.Batcher

hibernate.jdbc.use_scrollable_resultset | 允许Hibernate使用JDBC2的可滚动结果集. 只有在使用用户提供的JDBC连接时,这个选项才是必要的, 否则Hibernate会使用连接的元数据.取值 true | false

hibernate.jdbc.use_streams_for_binary | 在JDBC读写binary (二进制)或serializable (可序列化) 的类型时使用流(stream)(系统级属性).取值 true | false

hibernate.jdbc.use_get_generated_keys | 在数据插入数据库之后,允许使用JDBC3 PreparedStatement.getGeneratedKeys() 来获取数据库生成的key(键)。需要JDBC3+驱动和JRE1.4+, 如果你的数据库驱动在使用Hibernate的标 识生成器时遇到问题,请将此值设为false. 默认情况下将使用连接的元数据来判定驱动的能力.取值 true|false

hibernate.connection.provider_class | 自定义ConnectionProvider的类名, 此类用来向Hibernate提供JDBC连接.取值 classname.of.ConnectionProvider

hibernate.connection.isolation | 设置JDBC事务隔离级别. 查看java.sql.Connection来了解各个值的具体意义, 但请注意多数数据库都不支持所有的隔离级别.取值 1, 2, 4, 8

hibernate.connection.autocommit | 允许被缓存的JDBC连接开启自动提交(autocommit) (不建议).取值 true | false

hibernate.connection.release_mode | 指定Hibernate在何时释放JDBC连接. 默认情况下,直到Session被显式关闭或被断开连接时,才会释放JDBC连接. 对于应用程序服务器的JTA数据源, 你应当使用after_statement, 这样在每次JDBC调用后,都会主动的释放连接. 对于非JTA的连接, 使用after_transaction在每个事务结束时释放连接是合理的. auto将为JTA和CMT事务策略选择after_statement, 为JDBC事务策略选择after_transaction.取值 on_close | after_transaction | after_statement | auto

hibernate.connection. | 将JDBC属性propertyName传递到DriverManager.getConnection()中去.

hibernate.jndi. | 将属性propertyName传递到JNDI InitialContextFactory中去.

---------------------------------------------------------------------------------------------------------------------------------------------------------------------

Hibernate 缓冲属性

----------------------------------------------------------------------------------------------------------------------------------------------------------------------

|属性名 | 用途

----------------------------------------------------------------------------------------------------------------------------------------------------------------------

|hibernate.cache.provider_class | 自定义的CacheProvider的类名. 取值 classname.of.CacheProvider

|hibernate.cache.use_minimal_puts | 以频繁的读操作为代价, 优化二级缓存来最小化写操作. 在Hibernate3中,这个设置对的集群缓存非常有用, 对集群缓存的实现而言,默认是开启的.取值 true|false

|hibernate.cache.use_query_cache | 允许查询缓存, 个别查询仍然需要被设置为可缓存的.取值 true|false

|hibernate.cache.use_second_level_cache | 能用来完全禁止使用二级缓存. 对那些在类的映射定义中指定的类,会默认开启二级缓存.取值 true|false

|hibernate.cache.query_cache_factory | 自定义实现QueryCache接口的类名, 默认为内建的StandardQueryCache.取值 classname.of.QueryCache

|hibernate.cache.region_prefix | 二级缓存区域名的前缀.取值 prefix

|hibernate.cache.use_structured_entries | 强制Hibernate以更人性化的格式将数据存入二级缓存.取值 true|false

----------------------------------------------------------------------------------------------------------------------------------------------------------------------

Hibernate 事务属性

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

|属性名 | 用途

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

|hibernate.transaction.factory_class | 一个TransactionFactory的类名, 用于Hibernate Transaction API (默认为JDBCTransactionFactory).取值 classname.of.TransactionFactory

|jta.UserTransaction | 一个JNDI名字,被JTATransactionFactory用来从应用服务器获取JTA UserTransaction.取值 jndi/composite/name

|hibernate.transaction.manager_lookup_class | 一个TransactionManagerLookup的类名 - 当使用JVM级缓存,或在JTA环境中使用hilo生成器的时候需要该类.取值 classname.of.TransactionManagerLookup

|hibernate.transaction.flush_before_completion | 如果开启, session在事务完成后将被自动清洗(flush)。 现在更好的方法是使用自动session上下文管理。取值 true | false

|hibernate.transaction.auto_close_session | 如果开启, session在事务完成后将被自动关闭。 现在更好的方法是使用自动session上下文管理。取值 true | false

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

方言

----------------------------------------------------------------------------------

|RDBMS | 方言

----------------------------------------------------------------------------------

|DB2 | org.hibernate.dialect.DB2Dialect

|DB2 AS/400 | org.hibernate.dialect.DB2400Dialect

|DB2 OS390 | org.hibernate.dialect.DB2390Dialect

|PostgreSQL | org.hibernate.dialect.PostgreSQLDialect

|MySQL | org.hibernate.dialect.MySQLDialect

|MySQL with InnoDB | org.hibernate.dialect.MySQLInnoDBDialect

|MySQL with MyISAM | org.hibernate.dialect.MySQLMyISAMDialect

|Oracle (any version) | org.hibernate.dialect.OracleDialect

|Oracle 9i/10g | org.hibernate.dialect.Oracle9Dialect

|Sybase | org.hibernate.dialect.SybaseDialect

|Sybase Anywhere | org.hibernate.dialect.SybaseAnywhereDialect

|Microsoft SQL Server | org.hibernate.dialect.SQLServerDialect

|SAP DB | org.hibernate.dialect.SAPDBDialect

|Informix | org.hibernate.dialect.InformixDialect

|HypersonicSQL | org.hibernate.dialect.HSQLDialect

|Ingres | org.hibernate.dialect.IngresDialect

|Progress | org.hibernate.dialect.ProgressDialect

|Mckoi SQL | org.hibernate.dialect.MckoiDialect

|Interbase | org.hibernate.dialect.InterbaseDialect

|Pointbase | org.hibernate.dialect.PointbaseDialect

|FrontBase | org.hibernate.dialect.FrontbaseDialect

|Firebird | org.hibernate.dialect.FirebirdDialect

----------------------------------------------------------------------------------

其他属性

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

|属性名 用途

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

|hibernate.current_session_context_class | 为"当前" Session指定一个(自定义的)策略。eg. jta | thread | custom.Class

|hibernate.query.factory_class | 选择HQL解析器的实现.取值 org.hibernate.hql.ast.ASTQueryTranslatorFactory or org.hibernate.hql.classic.ClassicQueryTranslatorFactory

|hibernate.query.substitutions | 将Hibernate查询中的符号映射到SQL查询中的符号 (符号可能是函数名或常量名字).取值 hqlLiteral=SQL_LITERAL, hqlFunction=SQLFUNC

|hibernate.hbm2ddl.auto | 在SessionFactory创建时,自动检查数据库结构,或者将数据库schema的DDL导出到数据库. 使用 create-drop时,在显式关闭SessionFactory时,将drop掉数据库schema.取值 validate | update | create | create-drop

|hibernate.cglib.use_reflection_optimizer | 开启CGLIB来替代运行时反射机制(系统级属性). 反射机制有时在除错时比较有用. 注意即使关闭这个优化, Hibernate还是需要CGLIB. 你不能在hibernate.cfg.xml中设置此属性取值 true | false

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

二、hibernate.xmls配置

oracle.jdbc.driver.OracleDriver

jdbc:oracle:thin:@localhost:1521:orcl

system

sa

org.hibernate.dialect.Oracle10gDialect

true

true

validate

thread

10

false

hibernate配置文件可以有两种方式:官方推荐的XML配置文件和属性配置文件。我们大都采用XML方式的配置,因为结构良好,配置灵活,可读性强。而且可以在XML中直接配置映射文件而属性文件则不行。但是我们可能忽略的一个问题是:hibernate首先查找的配置文件却是属性配置文件hibernate.properties。

127a36cb93dfeb35804353f1b9c35ea0.png

Hibernate首先去找了hibernate.properties配置文件,但是没找到。然后创建字节码支持器,用到cglib,之后用了时间戳控制,之后才是读取hibernate.cfg.xml配置文件。这些在最前面的日志信息我们可能会忽略它,但是我们要明白hibernate的一些加载原理。

为什么使用properties配置hibernate?

在实际开发中一般都是hibernate.properties和hibernate.cfg.xml结合使用,这样可以使得结果更加清晰,便于更改数据库连接配置,需要修改属性就去hibernate.properties文件修改,需要修改映射配置就在hibernate.cfg.xml中去修改。

使用hibernate.properties配置

hibernate.connection.driver_class=oracle.jdbc.driver.OracleDriver

hibernate.connection.url=jdbc:oracle:thin:@localhost:1521:orcl

hibernate.connection.username=root

hibernate.connection.password=password

hibernate.dialect=org.hibernate.dialect.Oracle10gDialect

hibernate.show_sql=true

hibernate.format_sql=true

hbm2ddl.auto=validate

current_session_context_class=thread

hibernate.jdbc.batch_size=10

hibernate.cache.use_second_level_cache=false

hibernate 配置

classpath:jdbc.properties

${hibernate.connection.driver_class}

${hibernate.connection.url}

${hibernate.connection.username}

${hibernate.connection.password}

${hibernate.dialect}

${hibernate.show_sql}

${hibernate.format_sql}

${hibernate.connection.url}

${current_session_context_class}

${hibernate.jdbc.batch_size}

${use_second_level_cache}

可能写的有点简单,但意思是这个意思

如果和spring 一起用,那么几乎一样。

配置如下:

jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver

jdbc.url=jdbc\:mysql\://localhost\:3306/demo

jdbc.username=root

jdbc.password=password

jdbc.initialPoolSize=5

jdbc.minPoolSize=5

jdbc.maxPoolSize=100

spring-applicationContext.xml

classpath:jdbc.properties

如果实体配置完后,如果是几个的话,还好,要是多起来,那么你将会疯,所以提供以下解决实体类加载到hibernate中。

1.自动扫包

2.注册映射文件

1.自动扫包

扫描一个包下的文件时:

需要扫描不同包下的文件时:

classpath:entity

classpath:com.smilesnake..entity

2.注册映射文件

本人提供第三种配置方案----自定义

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee"

xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd

http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd

http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.1.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"

default-lazy-init="true">

/WEB-INF/config/jdbc.properties

/WEB-INF/config/jdbc.properties

class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

hibernate.dialect=${hibernate.dialect}

hibernate.show_sql=false

hibernate.format_sql=false

hibernate.query.substitutions=true 1, false 0

hibernate.jdbc.fetch_size=20

hibernate.connection.autocommit=true

hibernate.connection.release_mode=auto

hibernate.cache.use_query_cache=true

hibernate.cache.use_second_level_cache=true

hibernate.cache.use_structured_entries=true

当然,这上面的配置省略了很多,只提供了hibernate部分

jdbc.properties

#mysql

jdbc.driverClassName=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://127.0.0.1:3306/smilesnake?characterEncoding=UTF-8

jdbc.username=smilesnake

jdbc.password=password

hibernate.db=mysql

hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

#oracle

#jdbc.driverClassName=oracle.jdbc.driver.OracleDriver

#jdbc.url=jdbc:oracle:thin:@192.168.0.132:1521:orcl

#jdbc.username=smilesnake

#jdbc.password=password

#hibernate.db=oracle

#hibernate.dialect=org.hibernate.dialect.Oracle10gDialect

#sqlserver

#jdbc.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver

#jdbc.url=jdbc:sqlserver://192.168.0.132:1433;DatabaseName=smilesnake

#jdbc.username=smilesnake

#jdbc.password=password

#hibernate.db=sqlserver

#hibernate.dialect=org.hibernate.dialect.SQLServerDialect

#db2

#jdbc.driverClassName=com.ibm.db2.jcc.DB2Driver

#jdbc.url=jdbc:db2://localhost:50000/smilesnake

#jdbc.username=smilesnake

#jdbc.password=password

#hibernate.db=db2

#hibernate.dialect=org.hibernate.dialect.DB2Dialect

#mysql

hibernate.hbm.jeecms.core=classpath*:/com/smilesnake/core/entity/hbm/common/*.hbm.xml

hibernate.hbm.jeecms.cms=classpath*:/com/smilesnake/cms/entity/main/hbm/common/*.hbm.xml

hibernate.hbm.jeecms.assist=classpath*:/com/smilesnake/cms/entity/assist/hbm/common/*.hbm.xml

cpool.checkoutTimeout=5000

cpool.minPoolSize=20

cpool.maxPoolSize=100

cpool.maxIdleTime=7200

cpool.maxIdleTimeExcessConnections=1800

cpool.acquireIncrement=10

想用哪个就打开哪个,不想用哪个就注释掉

PropertyUtils.java

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStream;

import java.util.ArrayList;

import java.util.Collections;

import java.util.Enumeration;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import java.util.Properties;

import java.util.Set;

import java.util.TreeSet;

import org.springframework.beans.BeansException;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.BeanFactoryAware;

public class PropertyUtils implements BeanFactoryAware {

/**

* 从指定的properties 得到 以prefix开头的配置,并将其路径放到一个list中后返回此list

* @param prefix

* @return list

*/

public List getList(String prefix) {

//判断配置文件或者前缀不为空,为空返回一个空的集合

if (properties == null || prefix == null) {

return Collections.emptyList();

}

List list = new ArrayList();

// 返回属性列表中所有键的枚举,如果在主属性列表中未找到同名的键,则包括默认属性列表中不同的键。

Enumeration> en = properties.propertyNames();

String key;

//遍历 Enumeration

while (en.hasMoreElements()) {

key = (String) en.nextElement();

//判断是否以hibernate.hbm开头

//意为着读取properties文件中的herbernate.hbm开头的配置,

if (key.startsWith(prefix)) {

list.add(properties.getProperty(key));

}

}

return list;

}

/**

* 从指定的properties 得到 以prefix开头的配置,并将其路径放到一个Set中后返回此Set

* @param prefix

* @return Set

*/

public Set getSet(String prefix) {

if (properties == null || prefix == null) {

return Collections.emptySet();

}

Setset=new TreeSet();

Enumeration> en = properties.propertyNames();

String key;

while (en.hasMoreElements()) {

key = (String) en.nextElement();

if (key.startsWith(prefix)) {

set.add(properties.getProperty(key));

}

}

return set;

}

/**

* 从指定的properties 得到 以prefix开头的配置,并将其路径放到一个Map中后返回此Map

* @param prefix

* @return Map

*/

public Map getMap(String prefix) {

if (properties == null || prefix == null) {

return Collections.emptyMap();

}

Map map = new HashMap();

Enumeration> en = properties.propertyNames();

String key;

int len = prefix.length();

while (en.hasMoreElements()) {

key = (String) en.nextElement();

if (key.startsWith(prefix)) {

map.put(key.substring(len), properties.getProperty(key));

}

}

return map;

}

/**

* Properties 继承了HashTable

* 从指定的properties 得到 以prefix开头的配置,并将其路径放到一个Properties中后返回此Properties

* @param prefix

* @return Properties

*/

public Properties getProperties(String prefix) {

Properties props = new Properties();

if (properties == null || prefix == null) {

return props;

}

Enumeration> en = properties.propertyNames();

String key;

int len = prefix.length();

while (en.hasMoreElements()) {

key = (String) en.nextElement();

if (key.startsWith(prefix)) {

props.put(key.substring(len), properties.getProperty(key));

}

}

return props;

}

//此方法分别在config/jeecms/jeecms-servlet-admin-action.xml调用('hibernate.db')

/**

* 从指定的properties 得到 以prefix开头的配置,并将其路径放到一个String中后返回此String

* @param prefix

* @return String

*/

public String getPropertiesString(String prefix) {

String property = "";

if (properties == null || prefix == null) {

return property;

}

Enumeration> en = properties.propertyNames();

String key;

while (en.hasMoreElements()) {

key = (String) en.nextElement();

if (key.equals(prefix)) {

return properties.getProperty(key);

}

}

return property;

}

//此方法分别在config/jeecms/jeecms-context.xml调用('directive.')

//此方法分别在config/jeecms/jeecms-servlet-front-action.xml调用('directive.')

/**

* 从指定的properties 得到 以prefix开头的配置,并将其路径放到一个Map中后返回此Map

* @param prefix

* @return

*/

public Map getBeanMap(String prefix) {

Map keyMap = getMap(prefix);

if (keyMap.isEmpty()) {

return Collections.emptyMap();

}

Map resultMap = new HashMap(keyMap.size());

String key, value;

for (Map.Entry entry : keyMap.entrySet()) {

key = entry.getKey();

value = entry.getValue();

resultMap.put(key, beanFactory.getBean(value, Object.class));

}

return resultMap;

}

/**

* 读取file文件后将文件信息保存在props

* @param file

* @return

*/

public static Properties getProperties(File file) {

Properties props = new Properties();

InputStream in;

try {

in = new FileInputStream(file);

//读取此文件

props.load(in);

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return props;

}

/**

* 读取指定文件中的指定key的value值,

* @param file

* @param key

* @return String

*/

public static String getPropertyValue(File file,String key) {

Properties props=getProperties(file);

return (String) props.get(key);

}

private BeanFactory beanFactory;

private Properties properties;

public void setProperties(Properties properties) {

this.properties = properties;

}

public void setBeanFactory(BeanFactory beanFactory) throws BeansException {

this.beanFactory = beanFactory;

}

}

如果有侵权,马上删除

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值