spring entitymanagerr 怎么获得datasource

实习第4天(56)
9.3.原生查询
EJB QL中富有大量的查询语句并且基本上能符合你的绝大多数的查询需求.有时,你想要使用特定厂商提供的数据库上的专有能力.
实体管理服务提供了一个方法来建立原生的SQL查询并且映射他们到你的对象上.原生查询能反回实体,栏位值,或者两者的组合.EntityManager接口有三种方法来建立原生查询:一种返回标量值,一种是返回实体类型,最后一种是定义一个复杂的结果集,它能映射到多个实体的混合和标量值.
你可以进行JDBC的连接通过javax.sql.DataSource,使用@Resource注入和执行你的SQL语句.要意识到你所做的改变不会被当前的持久化上下文所反映.
9.3.1. 标量原生查询
Query createNativeQuery(String sql)
这将建立一个原生查询返回一个标量结果.它需要一个参数:你的原生SQL.它执行并且返回结果集同EJB QL相同的形式,返回标量值.
9.3.2.简单的实体原生查询
Query createNativeQuery(String sql, Class entityClass)
一个简单的原生查询通过一个SQL语句和隐式的映像到一个实体,映射元数据为基础的一个实体.它认为原生查询的结果集中的栏将完全匹配实体的O/R映射.原生SQL查询的映射实体的确定通过entityClass 参数:
Query query = manager.createNativeQuery(
“SELECT p.phone_PK, p.phone_number, p.type
FROM PHONE AS p”, Phone.class
实体的所有属性被列出:
9.3.3.复杂的原生查询
这个实体管理方法允许你有一个复杂的映射为原生SQL.你可以同时返回多个实体和标量栏.mappingName 参数参考@javax.persistence.SqlResultSetMapping定义.这个批注用来定义一个怎能样查询原生结果的钓子到O/R模型.如果返回的栏位名与批注映射的属性不匹配,你可以提代一个字段到栏位的映射为他们,使用@javax.persistence.FieldResult :
package javax.
public @interface SqlResultSetMapping {
String name( );
EntityResult[] entities( ) default {};
ColumnResult[] columns( ) default {};
public @interface EntityResult {
Class entityClass( );
FieldResult[] fields( ) default {};
String discriminatorColumn( ) default “”;
public @interface FieldResult {
String name( );
String column( );
public @interface ColumnResult {
String name( );
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:5623次
排名:千里之外
原创:17篇
转载:45篇
(1)(1)(54)(7)(1)(2)logger, nativeEntityManagerFactory
LocalContainerEntityManagerFactoryBean()
&&&&&&&&&&&
protected &javax.persistence.EntityManagerFactory
createNativeEntityManagerFactory()
&&&&&&&&&&Subclasses must implement this method to create the EntityManagerFactory
that will be returned by the getObject() method.
protected &javax.persistence.spi.PersistenceUnitInfo
determinePersistenceUnitInfo(PersistenceUnitManager&persistenceUnitManager)
&&&&&&&&&&Determine the PersistenceUnitInfo to use for the EntityManagerFactory
created by this bean.
&DataSource
getDataSource()
&&&&&&&&&&Return the JDBC DataSource that this EntityManagerFactory
obtains its JDBC Connections from.
&javax.persistence.spi.PersistenceUnitInfo
getPersistenceUnitInfo()
&&&&&&&&&&Return the PersistenceUnitInfo used to create this
EntityManagerFactory, if the in-container API was used.
getPersistenceUnitName()
&&&&&&&&&&Return the name of the persistence unit used to create this
EntityManagerFactory, or null if
it is an unnamed default.
protected &void
postProcessEntityManagerFactory(javax.persistence.EntityManagerFactory&emf,
javax.persistence.spi.PersistenceUnitInfo&pui)
&&&&&&&&&&Hook method allowing subclasses to customize the EntityManagerFactory
after its creation via the PersistenceProvider.
setDataSource(DataSource&dataSource)
&&&&&&&&&&Specify the JDBC DataSource that the JPA persistence provider is supposed
to use for accessing the database.
setLoadTimeWeaver(LoadTimeWeaver&loadTimeWeaver)
&&&&&&&&&&Specify the Spring LoadTimeWeaver to use for class instrumentation according
to the JPA class transformer contract.
setPersistenceUnitManager(PersistenceUnitManager&persistenceUnitManager)
&&&&&&&&&&Set the PersistenceUnitManager to use for obtaining the JPA persistence unit
that this FactoryBean is supposed to build an EntityManagerFactory for.
setPersistenceUnitPostProcessors(PersistenceUnitPostProcessor[]&postProcessors)
&&&&&&&&&&Set the PersistenceUnitPostProcessors to be applied to the
PersistenceUnitInfo used for creating this EntityManagerFactory.
setPersistenceXmlLocation(String&persistenceXmlLocation)
&&&&&&&&&&Set the location of the persistence.xml file
we want to use.
setResourceLoader(ResourceLoader&resourceLoader)
&&&&&&&&&&Set the ResourceLoader that this object runs in.
afterPropertiesSet, createEntityManagerFactoryProxy, destroy, getBeanClassLoader, getEntityManagerInterface, getJpaDialect, getJpaPropertyMap, getJpaVendorAdapter, getNativeEntityManagerFactory, getObject, getObjectType, getPersistenceProvider, isSingleton, setBeanClassLoader, setEntityManagerFactoryInterface, setEntityManagerInterface, setJpaDialect, setJpaProperties, setJpaPropertyMap, setJpaVendorAdapter, setPersistenceProvider, setPersistenceProviderClass, setPersistenceUnitName, translateExceptionIfPossible
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
LocalContainerEntityManagerFactoryBean
public LocalContainerEntityManagerFactoryBean()
setPersistenceUnitManager
public void setPersistenceUnitManager(PersistenceUnitManager&persistenceUnitManager)
Set the PersistenceUnitManager to use for obtaining the JPA persistence unit
that this FactoryBean is supposed to build an EntityManagerFactory for.
The default is to rely on the local settings specified on this FactoryBean,
such as "persistenceXmlLocation", "dataSource" and "loadTimeWeaver".
For reuse of existing persistence unit configuration or more advanced forms
of custom persistence unit handling, consider defining a separate
PersistenceUnitManager bean (typically a DefaultPersistenceUnitManager instance)
and linking it in here. persistence.xml location, DataSource
configuration and LoadTimeWeaver will be defined on that separate
DefaultPersistenceUnitManager bean in such a scenario.
See Also:setPersistenceXmlLocation(java.lang.String),
setDataSource(javax.sql.DataSource),
setLoadTimeWeaver(org.springframework.instrument.classloading.LoadTimeWeaver),
DefaultPersistenceUnitManager
setPersistenceXmlLocation
public void setPersistenceXmlLocation(String&persistenceXmlLocation)
Set the location of the persistence.xml file
we want to use. This is a Spring resource location.
Default is "classpath:META-INF/persistence.xml".
NOTE: Only applied if no external PersistenceUnitManager specified.
Parameters:persistenceXmlLocation - a Spring resource String
identifying the location of the persistence.xml file
that this LocalContainerEntityManagerFactoryBean should parseSee Also:setPersistenceUnitManager(org.springframework.orm.jpa.persistenceunit.PersistenceUnitManager)
setDataSource
public void setDataSource(DataSource&dataSource)
Specify the JDBC DataSource that the JPA persistence provider is supposed
to use for accessing the database. This is an alternative to keeping the
JDBC configuration in persistence.xml, passing in a Spring-managed
DataSource instead.
In JPA speak, a DataSource passed in here will be used as "nonJtaDataSource"
on the PersistenceUnitInfo passed to the PersistenceProvider, overriding
data source configuration in persistence.xml (if any).
NOTE: Only applied if no external PersistenceUnitManager specified.
See Also:PersistenceUnitInfo.getNonJtaDataSource(),
setPersistenceUnitManager(org.springframework.orm.jpa.persistenceunit.PersistenceUnitManager)
setPersistenceUnitPostProcessors
public void setPersistenceUnitPostProcessors(PersistenceUnitPostProcessor[]&postProcessors)
Set the PersistenceUnitPostProcessors to be applied to the
PersistenceUnitInfo used for creating this EntityManagerFactory.
Such post-processors can, for example, register further entity
classes and jar files, in addition to the metadata read in from
persistence.xml.
NOTE: Only applied if no external PersistenceUnitManager specified.
See Also:setPersistenceUnitManager(org.springframework.orm.jpa.persistenceunit.PersistenceUnitManager)
setLoadTimeWeaver
public void setLoadTimeWeaver(LoadTimeWeaver&loadTimeWeaver)
Specify the Spring LoadTimeWeaver to use for class instrumentation according
to the JPA class transformer contract.
It is a not required to specify a LoadTimeWeaver: Most providers will be
able to provide a subset of their functionality without class instrumentation
as well, or operate with their VM agent specified on JVM startup.
In terms of Spring-provided weaving options, the most important ones are
InstrumentationLoadTimeWeaver, which requires a Spring-specific (but very general)
VM agent specified on JVM startup, and ReflectiveLoadTimeWeaver, which interacts
with an underlying ClassLoader based on specific extended methods being available
on it (for example, interacting with Spring's TomcatInstrumentableClassLoader).
NOTE: As of Spring 2.5, the context's default LoadTimeWeaver (defined
as bean with name "loadTimeWeaver") will be picked up automatically, if available,
removing the need for LoadTimeWeaver configuration on each affected target bean.
Consider using the context:load-time-weaver XML tag for creating
such a shared LoadTimeWeaver (autodetecting the environment by default).
NOTE: Only applied if no external PersistenceUnitManager specified.
Otherwise, the external PersistenceUnitManager
is responsible for the weaving configuration.
Specified by:setLoadTimeWeaver in interface LoadTimeWeaverAware
Parameters:loadTimeWeaver - the LoadTimeWeaver instance (never null)See Also:InstrumentationLoadTimeWeaver,
ReflectiveLoadTimeWeaver,
TomcatInstrumentableClassLoader
setResourceLoader
public void setResourceLoader(ResourceLoader&resourceLoader)
Description copied from interface: ResourceLoaderAware
Set the ResourceLoader that this object runs in.
This might be a ResourcePatternResolver, which can be checked
through instanceof ResourcePatternResolver. See also the
ResourcePatternUtils.getResourcePatternResolver method.
Invoked after population of normal bean properties but before an init callback
like InitializingBean's afterPropertiesSet or a custom init-method.
Invoked before ApplicationContextAware's setApplicationContext.
Specified by:setResourceLoader in interface ResourceLoaderAware
Parameters:resourceLoader - ResourceLoader object to be used by this objectSee Also:ResourcePatternResolver,
ResourcePatternUtils.getResourcePatternResolver(org.springframework.core.io.ResourceLoader)
createNativeEntityManagerFactory
protected javax.persistence.EntityManagerFactory createNativeEntityManagerFactory()
throws javax.persistence.PersistenceException
Description copied from class: AbstractEntityManagerFactoryBean
Subclasses must implement this method to create the EntityManagerFactory
that will be returned by the getObject() method.
Specified by:createNativeEntityManagerFactory in class AbstractEntityManagerFactoryBean
Returns:EntityManagerFactory instance returned by this FactoryBean
javax.persistence.PersistenceException - if the EntityManager cannot be created
determinePersistenceUnitInfo
protected javax.persistence.spi.PersistenceUnitInfo determinePersistenceUnitInfo(PersistenceUnitManager&persistenceUnitManager)
Determine the PersistenceUnitInfo to use for the EntityManagerFactory
created by this bean.
The default implementation reads in all persistence unit infos from
persistence.xml, as defined in the JPA specification.
If no entity manager name was specified, it takes the first info in the
array as returned by the reader. Otherwise, it checks for a matching name.
Parameters:persistenceUnitManager - the PersistenceUnitManager to obtain from
Returns:the chosen PersistenceUnitInfo
postProcessEntityManagerFactory
protected void postProcessEntityManagerFactory(javax.persistence.EntityManagerFactory&emf,
javax.persistence.spi.PersistenceUnitInfo&pui)
Hook method allowing subclasses to customize the EntityManagerFactory
after its creation via the PersistenceProvider.
The default implementation is empty.
Parameters:emf - the newly created EntityManagerFactory we are working withpui - the PersistenceUnitInfo used to configure the EntityManagerFactorySee Also:PersistenceProvider.createContainerEntityManagerFactory(javax.persistence.spi.PersistenceUnitInfo, java.util.Map)
getPersistenceUnitInfo
public javax.persistence.spi.PersistenceUnitInfo getPersistenceUnitInfo()
Description copied from interface: EntityManagerFactoryInfo
Return the PersistenceUnitInfo used to create this
EntityManagerFactory, if the in-container API was used.
Specified by:getPersistenceUnitInfo in interface EntityManagerFactoryInfoOverrides:getPersistenceUnitInfo in class AbstractEntityManagerFactoryBean
Returns:the PersistenceUnitInfo used to create this EntityManagerFactory,
or null if the in-container contract was not used to
configure the EntityManagerFactory
getPersistenceUnitName
public String getPersistenceUnitName()
Description copied from interface: EntityManagerFactoryInfo
Return the name of the persistence unit used to create this
EntityManagerFactory, or null if
it is an unnamed default. If getPersistenceUnitInfo()
returns non-null, the return type of getPersistenceUnitName()
must be equal to the value returned by
PersistenceUnitInfo.getPersistenceUnitName().
Specified by:getPersistenceUnitName in interface EntityManagerFactoryInfoOverrides:getPersistenceUnitName in class AbstractEntityManagerFactoryBean
See Also:EntityManagerFactoryInfo.getPersistenceUnitInfo(),
PersistenceUnitInfo.getPersistenceUnitName()
getDataSource
public DataSource getDataSource()Description copied from interface: EntityManagerFactoryInfoReturn the JDBC DataSource that this EntityManagerFactoryobtains its JDBC Connections from.Specified by:getDataSource in interface EntityManagerFactoryInfoOverrides:getDataSource in class AbstractEntityManagerFactoryBeanReturns:the JDBC DataSource, or null if not known
spring下的LocalContainerEntityManagerFactoryBean使用方法和示例
上一篇:下一篇:
责任申明:本站内容均整理自互联网,若有侵权,请联系我们。使用本站提供的任务技术内容造成不良后果,本站不负任何责任。
欢迎投稿,电子邮件:(#号换成@)&& QQ群1: &&5113人阅读
java(34)
&& JPA是Java EE5规范之一,是一个orm规范,由厂商来实现该规范。目前有hibernate,OpenJPA,TopLink和EclipseJPA等实现
&&& Spring提供三种方法集成JPA:
1、LocalEntityManagerFactoryBean:适用于那些仅使用JPA进行数据访问的项目。该FactoryBean根据 JPA PersistenceProvider自动检测配置文件进行工作,一般从“META-INF/persistence.xml”读取配置信息。这种方式最简单,但是不能设置Spring中定义的DataSource,且不支持Spring管理的全局事务。不建议使用此方式。这种方法实际上只适用于独立的应用程序和测试环境(这正是JPA规范设计它的原因)。
&&& 在Spring中的配置:
&&& &bean id=”entityManagerFactory” class=”org.springframework.orm.jpa.LocalEntityManagerFactoryBean”&
&&&&&& &property name=”persistenceUnitName” value=”persistenceUnit”/&
&&& &/bean&
2、从JNDI中获取:用于从Java EE服务器中获取指定的EntityManagerFactory,这种方式在Spring事务管理时一般要使用JTA事务管理。
&&& Spring中的配置:
&beans xms=&http://www.springframework.org/schema/beans&
xmlns:xsi=&http://www.w3.org/2001/XMLSchema-instance&
xmlns:jee=&http://www.springframework.org/schema/jee&
xsi:schemaLoion=&
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.0.xsd&&
&jee:jndi-up id=&entityManagerFactory&
jndi-name=&persistence/persistenceUnit&/&
在标准的Java EE 5启动过程中,Java EE服务器自动检测持久化单元(例如应用程序文件包中的META-INF/persistence.xml) ,以及Java EE部署描述符中定义给那些持久化单元命名上下文位置的环境的persistence-unit-ref项(例如web.xml)。
在这种情况下,整个持久化单元部署,包括持久化类的织入(字码码转换)都取决于Java EE服务器。 JDBC DataSource 通过在META-INF/persistence.xml 文件中的JNDI位置进行定义;EntityManager事务与服务器的JTA子系统整合。Spring仅仅用获得的 EntityManagerFactory, 通过依赖注入将它传递给应用程序对象,并为它管理事务(一般通过JtaTransactionManager)。
注意,如果在同一个应用程序中使用了多个持久化单元,JNDI获取的这种持久化单元的bean名称 应该与应用程序用来引用它们的持久化单元名称相符(例如@PersistenceUnit和 @PersistenceContext注解)。
在部署到Java EE 5服务器时使用该方法。关于如何将自定义JPA提供者部署到服务器,以及允许使用服务器提供的缺省提供者之外的JPA提供者,请查看服务器文档的相关说明。
3、LocalContainerEntityManagerFactoryBean:适用于所有环境的FactoryBean,能全面控制EntityManagerFactory配置,非常适合那种需要细粒度定制的环境。
该bean有以下属性:
persistenceUnitManager:用于获取JPA持久化单元,默认实现DefaultPersistenceUnitManager用于解决多配置文件情况。
dataSource:用于指定Spring定义的数据源。
persistenceXmlLocation:用于指定JPA配置文件,对于多JPA配置文件情况请选择设置persistenceUnitManager属性来解决。
persistenceUnitName:用于指定持久化单元名称。
persistenceProvider:用于指定持久化实现厂商类,如hibernate为:org.hibernate.ejb.HibernateProvider 类。
jpaVendorAdapter:用于设置JPA实现厂商的特定属性,如设置hibernate的是否自动生成DDL的属性generateDdl,这些属性是厂商特定的,因此最好在这里设置。目前spring提供HibernateJpaVendorAdapter,OpenJpaVendorAdapter,EclipseJpaVendorAdapter,TopLinkJpaVenderAdapter四个实现。其中最主要的属性是“database”,用来指定使用的数据库类型。从而根据数据库类型决定如何将数据库特定异常转换为Spring一致性异常。目前支持以下数据库:DB2,DERBY,H2,HSQL,INFORMIX,MYSQL,ORACLE,POSTGRESQL,SQL_SERVER,SYBASE
jpaDialect:用于指定一些高级特性,如事务管理等。目前Spring提供HibernateJpaDialect,OpenJpaDialect,EclipseJpaDialect,TopLinkJpaDialect和DefaultJpaDialect实现。注意DefaultJpaDialect不提供任何功能,因此在使用特定实现厂商的JPA实现时需要指定jpaDialect实现,如使用hibernate就使用HibernateJpaDialect。当指定jpaVendorAdapter属性时可以不指定jpaDialect,会自动设置相应的JpaDialect实现;
jpaProperties和jpaPropertyMap:指定JPA属性;如Hibernate中指定是否显示SQL的“hibernate.show_sql”属性,对于jpaProperties设置的属性自动会放进jpaPropertyMap中;
loadTimeWeaver:用于指定LoadTimeWeaver实现,从而允许JPA 加载时修改相应的类文件。具体使用得参考相应的JPA规范实现厂商文档,如Hibernate就不需要指定loadTimeWeaver。
JPA配置实例:
& persistence.xml:
&?xml version=&1.0& encoding=&UTF-8&?&
&persistence version=&1.0&
xmlns=&/xml/ns/persistence&
xmlns:xsi=&http://www.w3.org/2001/XMLSchema-instance&
xsi:schemaLocation=&/xml/ns/persistence
/xml/ns/persistence/persistence_1_0.xsd&&
&persistence-unit name=&persistenceUnit& transaction-type=&RESOURCE_LOCAL&/&
&/persistence&
persistence.xml中,指定持久化单元名称和事务类型,其他在Spring中配置。
applicationContext.xml
&bean id=&entityManagerFactory& class=&org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean&&
&property name=&dataSource& ref=&dataSource&/&
&property name=&persistenceXmlLocation& value=&chapter8/persistence.xml&/&
&property name=&persistenceUnitName& value=&persistenceUnit&/&
&property name=&persistenceProvider& ref=&persistenceProvider&/&
&property name=&jpaVendorAdapter& ref=&jpaVendorAdapter&/&
&property name=&jpaDialect& ref=&jpaDialect&/&
&property name=&jpaProperties&&
&prop key=&hibernate.show_sql&&true&/prop&
&/property&
&bean id=&persistenceProvider& class=&org.hibernate.ejb.HibernatePersistence&/&
&bean id=&jpaVendorAdapter& class=&org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter&&
&property name=&generateDdl& value=&fae& /&
&property name=&database& value=&HSQL&/&
&bean id=&jpaDialect& class=&org.springframework.orm.jpa.vendor.HibernateJpaDialect&/&
LocalContainerEntityManagerFactoryBean:指定使用本地容器管理EntityManagerFactory,从而进行细粒度控制;
dataSource属性指定使用Spring定义的数据源; persistenceXmlLocation指定JPA配置文件为chapter8/persistence.xml,且该配置文件非常简单,具体配置完全在Spring中进行;
persistenceUnitName指定持久化单元名字,即JPA配置文件中指定的; persistenceProvider:指定JPA持久化提供商,此处使用Hibernate实现HibernatePersistence类;
jpaVendorAdapter:指定实现厂商专用特性,即generateDdl= false表示不自动生成DDL,database= HSQL表示使用hsqldb数据库;
jpaDialect:如果指定jpaVendorAdapter此属性可选,此处为HibernateJpaDialect;
jpaProperties:此处指定“hibernate.show_sql =true”表示在日志系统debug级别下将打印所有生成的SQL。
JpaTemplate类:
Spring提供JpaTemplate模板类用于简化事务管理及常见操作,类似于JdbcTemplate模板类。
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:149930次
积分:1938
积分:1938
排名:第15730名
原创:21篇
转载:104篇
(1)(3)(3)(1)(1)(1)(1)(9)(1)(2)(2)(2)(4)(1)(5)(12)(7)(22)(23)(3)(13)(8)

我要回帖

更多关于 entitymanager flush 的文章

 

随机推荐