http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/ed7736f3/modules/hibernate/src/main/java/org/gridgain/grid/cache/hibernate/GridHibernateReadWriteAccessStrategy.java ---------------------------------------------------------------------- diff --git a/modules/hibernate/src/main/java/org/gridgain/grid/cache/hibernate/GridHibernateReadWriteAccessStrategy.java b/modules/hibernate/src/main/java/org/gridgain/grid/cache/hibernate/GridHibernateReadWriteAccessStrategy.java deleted file mode 100644 index 4fe6552..0000000 --- a/modules/hibernate/src/main/java/org/gridgain/grid/cache/hibernate/GridHibernateReadWriteAccessStrategy.java +++ /dev/null @@ -1,282 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.gridgain.grid.cache.hibernate; - -import org.apache.ignite.*; -import org.apache.ignite.cache.*; -import org.apache.ignite.internal.util.*; -import org.apache.ignite.transactions.*; -import org.hibernate.cache.*; -import org.hibernate.cache.spi.access.*; - -import java.util.*; - -import static org.apache.ignite.transactions.IgniteTxConcurrency.*; -import static org.apache.ignite.transactions.IgniteTxIsolation.*; - -/** - * Implementation of {@link AccessType#READ_WRITE} cache access strategy. - * <p> - * Configuration of L2 cache and per-entity cache access strategy can be set in the - * Hibernate configuration file: - * <pre name="code" class="xml"> - * <hibernate-configuration> - * <!-- Enable L2 cache. --> - * <property name="cache.use_second_level_cache">true</property> - * - * <!-- Use GridGain as L2 cache provider. --> - * <property name="cache.region.factory_class">org.gridgain.grid.cache.hibernate.GridHibernateRegionFactory</property> - * - * <!-- Specify entity. --> - * <mapping class="com.example.Entity"/> - * - * <!-- Enable L2 cache with read-write access strategy for entity. --> - * <class-cache class="com.example.Entity" usage="read-write"/> - * </hibernate-configuration> - * </pre> - * Also cache access strategy can be set using annotations: - * <pre name="code" class="java"> - * @javax.persistence.Entity - * @javax.persistence.Cacheable - * @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) - * public class Entity { ... } - * </pre> - */ -public class GridHibernateReadWriteAccessStrategy extends GridHibernateAccessStrategyAdapter { - /** */ - private final ThreadLocal<TxContext> txCtx; - - /** - * @param ignite Grid. - * @param cache Cache. - * @param txCtx Thread local instance used to track updates done during one Hibernate transaction. - */ - protected GridHibernateReadWriteAccessStrategy(Ignite ignite, GridCache<Object, Object> cache, ThreadLocal txCtx) { - super(ignite, cache); - - this.txCtx = (ThreadLocal<TxContext>)txCtx; - } - - /** {@inheritDoc} */ - @Override protected Object get(Object key) throws CacheException { - try { - return cache.get(key); - } - catch (IgniteCheckedException e) { - rollbackCurrentTx(); - - throw new CacheException(e); - } - } - - /** {@inheritDoc} */ - @Override protected void putFromLoad(Object key, Object val) throws CacheException { - try { - cache.putx(key, val); - } - catch (IgniteCheckedException e) { - rollbackCurrentTx(); - - throw new CacheException(e); - } - } - - /** {@inheritDoc} */ - @Override protected SoftLock lock(Object key) throws CacheException { - try { - TxContext ctx = txCtx.get(); - - if (ctx == null) - txCtx.set(ctx = new TxContext()); - - lockKey(key); - - ctx.locked(key); - - return null; - } - catch (IgniteCheckedException e) { - rollbackCurrentTx(); - - throw new CacheException(e); - } - } - - /** {@inheritDoc} */ - @Override protected void unlock(Object key, SoftLock lock) throws CacheException { - try { - TxContext ctx = txCtx.get(); - - if (ctx != null) - unlock(ctx, key); - } - catch (IgniteCheckedException e) { - rollbackCurrentTx(); - - throw new CacheException(e); - } - } - - /** {@inheritDoc} */ - @Override protected boolean update(Object key, Object val) throws CacheException { - return false; - } - - /** {@inheritDoc} */ - @Override protected boolean afterUpdate(Object key, Object val, SoftLock lock) throws CacheException { - try { - TxContext ctx = txCtx.get(); - - if (ctx != null) { - cache.putx(key, val); - - unlock(ctx, key); - - return true; - } - - return false; - } - catch (IgniteCheckedException e) { - rollbackCurrentTx(); - - throw new CacheException(e); - } - } - - /** {@inheritDoc} */ - @Override protected boolean insert(Object key, Object val) throws CacheException { - return false; - } - - /** {@inheritDoc} */ - @Override protected boolean afterInsert(Object key, Object val) throws CacheException { - try { - cache.putx(key, val); - - return true; - } - catch (IgniteCheckedException e) { - rollbackCurrentTx(); - - throw new CacheException(e); - } - } - - /** {@inheritDoc} */ - @Override protected void remove(Object key) throws CacheException { - try { - TxContext ctx = txCtx.get(); - - if (ctx != null) - cache.removex(key); - } - catch (IgniteCheckedException e) { - rollbackCurrentTx(); - - throw new CacheException(e); - } - } - - /** - * - * @param ctx Transaction context. - * @param key Key. - * @throws IgniteCheckedException If failed. - */ - private void unlock(TxContext ctx, Object key) throws IgniteCheckedException { - if (ctx.unlocked(key)) { // Finish transaction if last key is unlocked. - txCtx.remove(); - - IgniteTx tx = cache.tx(); - - assert tx != null; - - try { - tx.commit(); - } - finally { - tx.close(); - } - - assert cache.tx() == null; - } - } - - /** - * Roll backs current transaction. - */ - private void rollbackCurrentTx() { - try { - TxContext ctx = txCtx.get(); - - if (ctx != null) { - txCtx.remove(); - - IgniteTx tx = cache.tx(); - - if (tx != null) - tx.rollback(); - } - } - catch (IgniteCheckedException e) { - log.error("Failed to rollback cache transaction.", e); - } - } - - /** - * @param key Key. - * @throws IgniteCheckedException If failed. - */ - private void lockKey(Object key) throws IgniteCheckedException { - if (cache.tx() == null) - cache.txStart(PESSIMISTIC, REPEATABLE_READ); - - cache.get(key); // Acquire distributed lock. - } - - /** - * Information about updates done during single database transaction. - */ - @SuppressWarnings("TypeMayBeWeakened") - private static class TxContext { - /** */ - private Set<Object> locked = new GridLeanSet<>(); - - /** - * Marks key as locked. - * - * @param key Key. - */ - void locked(Object key) { - locked.add(key); - } - - /** - * Marks key as unlocked. - * - * @param key Key. - * @return {@code True} if last locked key was unlocked. - */ - boolean unlocked(Object key) { - locked.remove(key); - - return locked.isEmpty(); - } - } -}
http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/ed7736f3/modules/hibernate/src/main/java/org/gridgain/grid/cache/hibernate/GridHibernateRegion.java ---------------------------------------------------------------------- diff --git a/modules/hibernate/src/main/java/org/gridgain/grid/cache/hibernate/GridHibernateRegion.java b/modules/hibernate/src/main/java/org/gridgain/grid/cache/hibernate/GridHibernateRegion.java deleted file mode 100644 index e958f8d..0000000 --- a/modules/hibernate/src/main/java/org/gridgain/grid/cache/hibernate/GridHibernateRegion.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.gridgain.grid.cache.hibernate; - -import org.apache.ignite.*; -import org.apache.ignite.cache.*; -import org.hibernate.cache.*; -import org.hibernate.cache.spi.*; - -import java.util.*; - -/** - * Implementation of {@link Region}. This interface defines base contract for all L2 cache regions. - */ -public class GridHibernateRegion implements Region { - /** */ - protected final GridHibernateRegionFactory factory; - - /** */ - private final String name; - - /** Cache instance. */ - protected final GridCache<Object, Object> cache; - - /** Grid instance. */ - protected Ignite ignite; - - /** - * @param factory Region factory. - * @param name Region name. - * @param ignite Grid. - * @param cache Region cache. - */ - public GridHibernateRegion(GridHibernateRegionFactory factory, String name, Ignite ignite, - GridCache<Object, Object> cache) { - this.factory = factory; - this.name = name; - this.ignite = ignite; - this.cache = cache; - } - - /** {@inheritDoc} */ - @Override public String getName() { - return name; - } - - /** {@inheritDoc} */ - @Override public void destroy() throws CacheException { - // No-op. - } - - /** {@inheritDoc} */ - @Override public boolean contains(Object key) { - return cache.containsKey(key); - } - - /** {@inheritDoc} */ - @Override public long getSizeInMemory() { - return -1; - } - - /** {@inheritDoc} */ - @Override public long getElementCountInMemory() { - return cache.size(); - } - - /** {@inheritDoc} */ - @Override public long getElementCountOnDisk() { - return -1; - } - - /** {@inheritDoc} */ - @Override public Map toMap() { - return cache.toMap(); - } - - /** {@inheritDoc} */ - @Override public long nextTimestamp() { - return System.currentTimeMillis(); - } - - /** {@inheritDoc} */ - @Override public int getTimeout() { - return 0; - } -} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/ed7736f3/modules/hibernate/src/main/java/org/gridgain/grid/cache/hibernate/GridHibernateRegionFactory.java ---------------------------------------------------------------------- diff --git a/modules/hibernate/src/main/java/org/gridgain/grid/cache/hibernate/GridHibernateRegionFactory.java b/modules/hibernate/src/main/java/org/gridgain/grid/cache/hibernate/GridHibernateRegionFactory.java deleted file mode 100644 index b9e3879..0000000 --- a/modules/hibernate/src/main/java/org/gridgain/grid/cache/hibernate/GridHibernateRegionFactory.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.gridgain.grid.cache.hibernate; - -import org.apache.ignite.*; -import org.apache.ignite.cache.*; -import org.apache.ignite.internal.util.typedef.*; -import org.hibernate.cache.*; -import org.hibernate.cache.spi.*; -import org.hibernate.cache.spi.RegionFactory; -import org.hibernate.cache.spi.access.AccessType; -import org.hibernate.cfg.*; - -import java.util.*; - -import static org.hibernate.cache.spi.access.AccessType.*; - -/** - * Hibernate L2 cache region factory. - * <p> - * Following Hibernate settings should be specified to enable second level cache and to use this - * region factory for caching: - * <pre name="code" class="brush: xml; gutter: false;"> - * hibernate.cache.use_second_level_cache=true - * hibernate.cache.region.factory_class=org.gridgain.grid.cache.hibernate.GridHibernateRegionFactory - * </pre> - * Note that before region factory is started you need to start properly configured GridGain node in the same JVM. - * For example to start GridGain node one of loader provided in {@code org.gridgain.grid.startup} package can be used. - * <p> - * Name of grid to be used for region factory must be specified as following Hibernate property: - * <pre name="code" class="brush: xml; gutter: false;"> - * org.gridgain.hibernate.grid_name=<grid name> - * </pre> - * Each Hibernate cache region must be associated with some {@link org.apache.ignite.cache.GridCache}, by default it is assumed that - * for each cache region there is a {@link org.apache.ignite.cache.GridCache} with the same name. Also it is possible to define - * region to cache mapping using properties with prefix {@code org.gridgain.hibernate.region_cache}. - * For example if for region with name "region1" cache with name "cache1" should be used then following - * Hibernate property should be specified: - * <pre name="code" class="brush: xml; gutter: false;"> - * org.gridgain.hibernate.region_cache.region1=cache1 - * </pre> - */ -public class GridHibernateRegionFactory implements RegionFactory { - /** */ - private static final long serialVersionUID = 0L; - - /** Hibernate L2 cache grid name property name. */ - public static final String GRID_NAME_PROPERTY = "org.gridgain.hibernate.grid_name"; - - /** Default cache property name. */ - public static final String DFLT_CACHE_NAME_PROPERTY = "org.gridgain.hibernate.default_cache"; - - /** Property prefix used to specify region name to cache name mapping. */ - public static final String REGION_CACHE_PROPERTY = "org.gridgain.hibernate.region_cache."; - - /** */ - public static final String DFLT_ACCESS_TYPE_PROPERTY = "org.gridgain.hibernate.default_access_type"; - - /** */ - public static final String GRID_CONFIG_PROPERTY = "org.gridgain.hibernate.grid_config"; - - /** Grid providing caches. */ - private Ignite ignite; - - /** Default cache. */ - private GridCache<Object, Object> dfltCache; - - /** Default region access type. */ - private AccessType dfltAccessType; - - /** Region name to cache name mapping. */ - private final Map<String, String> regionCaches = new HashMap<>(); - - /** Map needed to provide the same transaction context for different regions. */ - private final ThreadLocal threadLoc = new ThreadLocal(); - - /** {@inheritDoc} */ - @Override public void start(Settings settings, Properties props) throws CacheException { - String gridName = props.getProperty(GRID_NAME_PROPERTY); - - if (gridName != null) - ignite = G.ignite(gridName); - else { - String gridCfg = props.getProperty(GRID_CONFIG_PROPERTY); - - if (gridCfg == null) - throw new CacheException("Either grid name or path to grid configuration must be specified."); - - try { - ignite = G.start(gridCfg); - } - catch (IgniteCheckedException e) { - throw new CacheException(e); - } - } - - if (ignite == null) - throw new CacheException("Grid '" + gridName + "' for hibernate L2 cache is not started."); - - String accessType = props.getProperty(DFLT_ACCESS_TYPE_PROPERTY, NONSTRICT_READ_WRITE.name()); - - dfltAccessType = AccessType.valueOf(accessType); - - for (Map.Entry<Object, Object> prop : props.entrySet()) { - String key = prop.getKey().toString(); - - if (key.startsWith(REGION_CACHE_PROPERTY)) { - String regionName = key.substring(REGION_CACHE_PROPERTY.length()); - - String cacheName = prop.getValue().toString(); - - if (ignite.cache(cacheName) == null) - throw new CacheException("Cache '" + cacheName + "' specified for region '" + regionName + "' " + - "is not configured."); - - regionCaches.put(regionName, cacheName); - } - } - - String dfltCacheName = props.getProperty(DFLT_CACHE_NAME_PROPERTY); - - if (dfltCacheName != null) { - dfltCache = ignite.cache(dfltCacheName); - - if (dfltCache == null) - throw new CacheException("Cache specified as default is not configured: " + dfltCacheName); - } - - IgniteLogger log = ignite.log().getLogger(GridHibernateRegionFactory.class); - - if (log.isDebugEnabled()) - log.debug("GridHibernateRegionFactory started [grid=" + gridName + ']'); - } - - /** {@inheritDoc} */ - @Override public void stop() { - } - - /** {@inheritDoc} */ - @Override public boolean isMinimalPutsEnabledByDefault() { - return false; - } - - /** {@inheritDoc} */ - @Override public AccessType getDefaultAccessType() { - return dfltAccessType; - } - - /** {@inheritDoc} */ - @Override public long nextTimestamp() { - return System.currentTimeMillis(); - } - - /** {@inheritDoc} */ - @Override public EntityRegion buildEntityRegion(String regionName, Properties props, CacheDataDescription metadata) - throws CacheException { - return new GridHibernateEntityRegion(this, regionName, ignite, regionCache(regionName), metadata); - } - - /** {@inheritDoc} */ - @Override public NaturalIdRegion buildNaturalIdRegion(String regionName, Properties props, - CacheDataDescription metadata) throws CacheException { - return new GridHibernateNaturalIdRegion(this, regionName, ignite, regionCache(regionName), metadata); - } - - /** {@inheritDoc} */ - @Override public CollectionRegion buildCollectionRegion(String regionName, Properties props, - CacheDataDescription metadata) throws CacheException { - return new GridHibernateCollectionRegion(this, regionName, ignite, regionCache(regionName), metadata); - } - - /** {@inheritDoc} */ - @Override public QueryResultsRegion buildQueryResultsRegion(String regionName, Properties props) - throws CacheException { - return new GridHibernateQueryResultsRegion(this, regionName, ignite, regionCache(regionName)); - } - - /** {@inheritDoc} */ - @Override public TimestampsRegion buildTimestampsRegion(String regionName, Properties props) throws CacheException { - return new GridHibernateTimestampsRegion(this, regionName, ignite, regionCache(regionName)); - } - - /** - * Reuse same thread local for the same cache across different regions. - * - * @param cacheName Cache name. - * @return Thread local instance used to track updates done during one Hibernate transaction. - */ - ThreadLocal threadLocalForCache(String cacheName) { - return threadLoc; - } - - /** - * @param regionName L2 cache region name. - * @return Cache for given region. - * @throws CacheException If cache for given region is not configured. - */ - private GridCache<Object, Object> regionCache(String regionName) throws CacheException { - String cacheName = regionCaches.get(regionName); - - if (cacheName == null) { - if (dfltCache != null) - return dfltCache; - - cacheName = regionName; - } - - GridCache<Object, Object> cache = ignite.cache(cacheName); - - if (cache == null) - throw new CacheException("Cache '" + cacheName + "' for region '" + regionName + "' is not configured."); - - return cache; - } -} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/ed7736f3/modules/hibernate/src/main/java/org/gridgain/grid/cache/hibernate/GridHibernateTimestampsRegion.java ---------------------------------------------------------------------- diff --git a/modules/hibernate/src/main/java/org/gridgain/grid/cache/hibernate/GridHibernateTimestampsRegion.java b/modules/hibernate/src/main/java/org/gridgain/grid/cache/hibernate/GridHibernateTimestampsRegion.java deleted file mode 100644 index 736ae35..0000000 --- a/modules/hibernate/src/main/java/org/gridgain/grid/cache/hibernate/GridHibernateTimestampsRegion.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.gridgain.grid.cache.hibernate; - -import org.apache.ignite.*; -import org.apache.ignite.cache.*; -import org.hibernate.cache.spi.*; - -/** - * Implementation of {@link TimestampsRegion}. This region is automatically created when query - * caching is enabled and it holds most recent updates timestamps to queryable tables. - * Name of timestamps region is {@code "org.hibernate.cache.spi.UpdateTimestampsCache"}. - */ -public class GridHibernateTimestampsRegion extends GridHibernateGeneralDataRegion implements TimestampsRegion { - /** - * @param factory Region factory. - * @param name Region name. - * @param ignite Grid. - * @param cache Region cache. - */ - public GridHibernateTimestampsRegion(GridHibernateRegionFactory factory, String name, - Ignite ignite, GridCache<Object, Object> cache) { - super(factory, name, ignite, cache); - } -} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/ed7736f3/modules/hibernate/src/main/java/org/gridgain/grid/cache/hibernate/GridHibernateTransactionalAccessStrategy.java ---------------------------------------------------------------------- diff --git a/modules/hibernate/src/main/java/org/gridgain/grid/cache/hibernate/GridHibernateTransactionalAccessStrategy.java b/modules/hibernate/src/main/java/org/gridgain/grid/cache/hibernate/GridHibernateTransactionalAccessStrategy.java deleted file mode 100644 index 12d94d0..0000000 --- a/modules/hibernate/src/main/java/org/gridgain/grid/cache/hibernate/GridHibernateTransactionalAccessStrategy.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.gridgain.grid.cache.hibernate; - -import org.apache.ignite.*; -import org.apache.ignite.cache.*; -import org.hibernate.cache.*; -import org.hibernate.cache.spi.access.*; -import org.jetbrains.annotations.*; - -/** - * Implementation of {@link AccessType#TRANSACTIONAL} cache access strategy. - * <p> - * It is supposed that this strategy is used in JTA environment and Hibernate and - * {@link org.apache.ignite.cache.GridCache} corresponding to the L2 cache region are configured to use the same transaction manager. - * <p> - * Configuration of L2 cache and per-entity cache access strategy can be set in the - * Hibernate configuration file: - * <pre name="code" class="xml"> - * <hibernate-configuration> - * <!-- Enable L2 cache. --> - * <property name="cache.use_second_level_cache">true</property> - * - * <!-- Use GridGain as L2 cache provider. --> - * <property name="cache.region.factory_class">org.gridgain.grid.cache.hibernate.GridHibernateRegionFactory</property> - * - * <!-- Specify entity. --> - * <mapping class="com.example.Entity"/> - * - * <!-- Enable L2 cache with transactional access strategy for entity. --> - * <class-cache class="com.example.Entity" usage="transactional"/> - * </hibernate-configuration> - * </pre> - * Also cache access strategy can be set using annotations: - * <pre name="code" class="java"> - * @javax.persistence.Entity - * @javax.persistence.Cacheable - * @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL) - * public class Entity { ... } - * </pre> - */ -public class GridHibernateTransactionalAccessStrategy extends GridHibernateAccessStrategyAdapter { - /** - * @param ignite Grid. - * @param cache Cache. - */ - public GridHibernateTransactionalAccessStrategy(Ignite ignite, GridCache<Object, Object> cache) { - super(ignite, cache); - } - - /** {@inheritDoc} */ - @Nullable @Override protected Object get(Object key) throws CacheException { - try { - return cache.get(key); - } - catch (IgniteCheckedException e) { - throw new CacheException(e); - } - } - - /** {@inheritDoc} */ - @Override protected void putFromLoad(Object key, Object val) throws CacheException { - try { - cache.putx(key, val); - } - catch (IgniteCheckedException e) { - throw new CacheException(e); - } - } - - /** {@inheritDoc} */ - @Override protected SoftLock lock(Object key) throws CacheException { - return null; - } - - /** {@inheritDoc} */ - @Override protected void unlock(Object key, SoftLock lock) throws CacheException { - // No-op. - } - - /** {@inheritDoc} */ - @Override protected boolean update(Object key, Object val) throws CacheException { - try { - cache.putx(key, val); - - return true; - } - catch (IgniteCheckedException e) { - throw new CacheException(e); - } - } - - /** {@inheritDoc} */ - @Override protected boolean afterUpdate(Object key, Object val, SoftLock lock) throws CacheException { - return false; - } - - /** {@inheritDoc} */ - @Override protected boolean insert(Object key, Object val) throws CacheException { - try { - cache.putx(key, val); - - return true; - } - catch (IgniteCheckedException e) { - throw new CacheException(e); - } - } - - /** {@inheritDoc} */ - @Override protected boolean afterInsert(Object key, Object val) throws CacheException { - return false; - } - - /** {@inheritDoc} */ - @Override protected void remove(Object key) throws CacheException { - try { - cache.removex(key); - } - catch (IgniteCheckedException e) { - throw new CacheException(e); - } - } -} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/ed7736f3/modules/hibernate/src/main/java/org/gridgain/grid/cache/hibernate/GridHibernateTransactionalDataRegion.java ---------------------------------------------------------------------- diff --git a/modules/hibernate/src/main/java/org/gridgain/grid/cache/hibernate/GridHibernateTransactionalDataRegion.java b/modules/hibernate/src/main/java/org/gridgain/grid/cache/hibernate/GridHibernateTransactionalDataRegion.java deleted file mode 100644 index b8d916d..0000000 --- a/modules/hibernate/src/main/java/org/gridgain/grid/cache/hibernate/GridHibernateTransactionalDataRegion.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.gridgain.grid.cache.hibernate; - -import org.apache.ignite.*; -import org.apache.ignite.cache.*; -import org.hibernate.cache.*; -import org.hibernate.cache.spi.*; -import org.hibernate.cache.spi.access.*; - -import static org.apache.ignite.cache.GridCacheAtomicityMode.*; - -/** - * Implementation of {@link TransactionalDataRegion} (transactional means that - * data in the region is updated in connection with database transaction). - * This interface defines base contract for {@link EntityRegion}, {@link CollectionRegion} - * and {@link NaturalIdRegion}. - */ -public class GridHibernateTransactionalDataRegion extends GridHibernateRegion implements TransactionalDataRegion { - /** */ - private final CacheDataDescription dataDesc; - - /** - * @param factory Region factory. - * @param name Region name. - * @param ignite Grid. - * @param cache Region cache. - * @param dataDesc Region data description. - */ - public GridHibernateTransactionalDataRegion(GridHibernateRegionFactory factory, String name, - Ignite ignite, GridCache<Object, Object> cache, CacheDataDescription dataDesc) { - super(factory, name, ignite, cache); - - this.dataDesc = dataDesc; - } - - /** {@inheritDoc} */ - @Override public boolean isTransactionAware() { - return false; // This method is not used by Hibernate. - } - - /** {@inheritDoc} */ - @Override public CacheDataDescription getCacheDataDescription() { - return dataDesc; - } - - /** - * @param accessType Hibernate L2 cache access type. - * @return Access strategy for given access type. - */ - protected GridHibernateAccessStrategyAdapter createAccessStrategy(AccessType accessType) { - switch (accessType) { - case READ_ONLY: - return new GridHibernateReadOnlyAccessStrategy(ignite, cache); - - case NONSTRICT_READ_WRITE: - return new GridHibernateNonStrictAccessStrategy(ignite, cache, factory.threadLocalForCache(cache.name())); - - case READ_WRITE: - if (cache.configuration().getAtomicityMode() != TRANSACTIONAL) - throw new CacheException("Hibernate READ-WRITE access strategy must have GridGain cache with " + - "'TRANSACTIONAL' atomicity mode: " + cache.name()); - - return new GridHibernateReadWriteAccessStrategy(ignite, cache, factory.threadLocalForCache(cache.name())); - - case TRANSACTIONAL: - if (cache.configuration().getAtomicityMode() != TRANSACTIONAL) - throw new CacheException("Hibernate TRANSACTIONAL access strategy must have GridGain cache with " + - "'TRANSACTIONAL' atomicity mode: " + cache.name()); - - if (cache.configuration().getTransactionManagerLookupClassName() == null) - throw new CacheException("Hibernate TRANSACTIONAL access strategy must have GridGain cache with " + - "TransactionManagerLookup configured: " + cache.name()); - - return new GridHibernateTransactionalAccessStrategy(ignite, cache); - - default: - throw new IllegalArgumentException("Unknown Hibernate access type: " + accessType); - } - } -} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/ed7736f3/modules/hibernate/src/main/java/org/gridgain/grid/cache/hibernate/package.html ---------------------------------------------------------------------- diff --git a/modules/hibernate/src/main/java/org/gridgain/grid/cache/hibernate/package.html b/modules/hibernate/src/main/java/org/gridgain/grid/cache/hibernate/package.html deleted file mode 100644 index 02d737f..0000000 --- a/modules/hibernate/src/main/java/org/gridgain/grid/cache/hibernate/package.html +++ /dev/null @@ -1,26 +0,0 @@ -<!-- - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - --> - -<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> -<html> -<body> - <!-- Package description. --> - Contains implementation of Hibernate L2 cache. Refer to - <i>org.gridgain.examples.datagrid.hibernate.GridHibernateL2CacheExample</i> for more information on how to - configure and use GridGain with Hibernate. -</body> -</html> http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/ed7736f3/modules/hibernate/src/main/java/org/gridgain/grid/cache/store/hibernate/GridCacheHibernateBlobStore.java ---------------------------------------------------------------------- diff --git a/modules/hibernate/src/main/java/org/gridgain/grid/cache/store/hibernate/GridCacheHibernateBlobStore.java b/modules/hibernate/src/main/java/org/gridgain/grid/cache/store/hibernate/GridCacheHibernateBlobStore.java deleted file mode 100644 index 99022f5..0000000 --- a/modules/hibernate/src/main/java/org/gridgain/grid/cache/store/hibernate/GridCacheHibernateBlobStore.java +++ /dev/null @@ -1,592 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.gridgain.grid.cache.store.hibernate; - -import org.apache.ignite.*; -import org.apache.ignite.cache.store.*; -import org.apache.ignite.resources.*; -import org.apache.ignite.transactions.*; -import org.apache.ignite.internal.util.typedef.*; -import org.apache.ignite.internal.util.typedef.internal.*; -import org.apache.ignite.internal.util.tostring.*; -import org.hibernate.*; -import org.hibernate.cfg.*; -import org.jetbrains.annotations.*; - -import javax.cache.integration.*; -import java.io.*; -import java.net.*; -import java.util.*; -import java.util.concurrent.*; -import java.util.concurrent.atomic.*; - -/** - * {@link CacheStore} implementation backed by Hibernate. This implementation - * stores objects in underlying database in {@code BLOB} format. - * <h2 class="header">Configuration</h2> - * Either {@link #setSessionFactory(SessionFactory)} or - * {@link #setHibernateConfigurationPath(String)} or - * {@link #setHibernateProperties(Properties)} should be set. - * <p> - * If session factory is provided it should contain - * {@link GridCacheHibernateBlobStoreEntry} persistent class (via provided - * mapping file {@code GridCacheHibernateStoreEntry.hbm.xml} or by - * adding {@link GridCacheHibernateBlobStoreEntry} to annotated classes - * of session factory. - * <p> - * Path to hibernate configuration may be either an URL or a file path or - * a classpath resource. This configuration file should include provided - * mapping {@code GridCacheHibernateStoreEntry.hbm.xml} or include annotated - * class {@link GridCacheHibernateBlobStoreEntry}. - * <p> - * If hibernate properties are provided, mapping - * {@code GridCacheHibernateStoreEntry.hbm.xml} is included automatically. - * - * <h2 class="header">Java Example</h2> - * In this example existing session factory is provided. - * <pre name="code" class="java"> - * ... - * GridCacheHibernateBlobStore<String, String> store = new GridCacheHibernateBlobStore<String, String>(); - * - * store.setSessionFactory(sesFactory); - * ... - * </pre> - * - * <h2 class="header">Spring Example (using Spring ORM)</h2> - * <pre name="code" class="xml"> - * ... - * <bean id="cache.hibernate.store" - * class="org.gridgain.grid.cache.store.hibernate.GridCacheHibernateBlobStore"> - * <property name="sessionFactory"> - * <bean class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> - * <property name="hibernateProperties"> - * <value> - * connection.url=jdbc:h2:mem: - * show_sql=true - * hbm2ddl.auto=true - * hibernate.dialect=org.hibernate.dialect.H2Dialect - * </value> - * </property> - * <property name="mappingResources"> - * <list> - * <value> - * org/gridgain/grid/cache/store/hibernate/GridCacheHibernateBlobStoreEntry.hbm.xml - * </value> - * </list> - * </property> - * </bean> - * </property> - * </bean> - * ... - * </pre> - * - * <h2 class="header">Spring Example (using Spring ORM and persistent annotations)</h2> - * <pre name="code" class="xml"> - * ... - * <bean id="cache.hibernate.store1" - * class="org.gridgain.grid.cache.store.hibernate.GridCacheHibernateBlobStore"> - * <property name="sessionFactory"> - * <bean class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> - * <property name="hibernateProperties"> - * <value> - * connection.url=jdbc:h2:mem: - * show_sql=true - * hbm2ddl.auto=true - * hibernate.dialect=org.hibernate.dialect.H2Dialect - * </value> - * </property> - * <property name="annotatedClasses"> - * <list> - * <value> - * org.gridgain.grid.cache.store.hibernate.GridCacheHibernateBlobStoreEntry - * </value> - * </list> - * </property> - * </bean> - * </property> - * </bean> - * ... - * </pre> - * - * <h2 class="header">Spring Example</h2> - * <pre name="code" class="xml"> - * ... - * <bean id="cache.hibernate.store2" - * class="org.gridgain.grid.cache.store.hibernate.GridCacheHibernateBlobStore"> - * <property name="hibernateProperties"> - * <props> - * <prop key="connection.url">jdbc:h2:mem:</prop> - * <prop key="hbm2ddl.auto">update</prop> - * <prop key="show_sql">true</prop> - * </props> - * </property> - * </bean> - * ... - * </pre> - * <p> - * <img src="http://www.gridgain.com/images/spring-small.png"> - * <br> - * For information about Spring framework visit <a href="http://www.springframework.org/">www.springframework.org</a> - */ -public class GridCacheHibernateBlobStore<K, V> extends CacheStoreAdapter<K, V> { - /** - * Default connection URL - * (value is <tt>jdbc:h2:mem:hibernateCacheStore;DB_CLOSE_DELAY=-1;DEFAULT_LOCK_TIMEOUT=5000</tt>). - */ - public static final String DFLT_CONN_URL = "jdbc:h2:mem:hibernateCacheStore;DB_CLOSE_DELAY=-1;" + - "DEFAULT_LOCK_TIMEOUT=5000"; - - /** Default show SQL property value (value is <tt>true</tt>). */ - public static final String DFLT_SHOW_SQL = "true"; - - /** Default <tt>hibernate.hbm2ddl.auto</tt> property value (value is <tt>true</tt>). */ - public static final String DFLT_HBM2DDL_AUTO = "update"; - - /** Session attribute name. */ - private static final String ATTR_SES = "HIBERNATE_STORE_SESSION"; - - /** Name of Hibarname mapping resource. */ - private static final String MAPPING_RESOURCE = "org/gridgain/grid/cache/store/hibernate/GridCacheHibernateBlobStoreEntry.hbm.xml"; - - /** Init guard. */ - @GridToStringExclude - private final AtomicBoolean initGuard = new AtomicBoolean(); - - /** Init latch. */ - @GridToStringExclude - private final CountDownLatch initLatch = new CountDownLatch(1); - - /** Hibernate properties. */ - @GridToStringExclude - private Properties hibernateProps; - - /** Session factory. */ - @GridToStringExclude - private SessionFactory sesFactory; - - /** Path to hibernate configuration file. */ - private String hibernateCfgPath; - - /** Log. */ - @IgniteLoggerResource - private IgniteLogger log; - - /** Ignite instance. */ - @IgniteInstanceResource - private Ignite ignite; - - /** {@inheritDoc} */ - @SuppressWarnings({"unchecked", "RedundantTypeArguments"}) - @Override public V load(K key) { - init(); - - IgniteTx tx = transaction(); - - if (log.isDebugEnabled()) - log.debug("Store load [key=" + key + ", tx=" + tx + ']'); - - Session ses = session(tx); - - try { - GridCacheHibernateBlobStoreEntry entry = (GridCacheHibernateBlobStoreEntry) - ses.get(GridCacheHibernateBlobStoreEntry.class, toBytes(key)); - - if (entry == null) - return null; - - return fromBytes(entry.getValue()); - } - catch (IgniteCheckedException | HibernateException e) { - rollback(ses, tx); - - throw new CacheLoaderException("Failed to load value from cache store with key: " + key, e); - } - finally { - end(ses, tx); - } - } - - /** {@inheritDoc} */ - @Override public void write(javax.cache.Cache.Entry<? extends K, ? extends V> entry) { - init(); - - IgniteTx tx = transaction(); - - K key = entry.getKey(); - V val = entry.getValue(); - - if (log.isDebugEnabled()) - log.debug("Store put [key=" + key + ", val=" + val + ", tx=" + tx + ']'); - - if (val == null) { - delete(key); - - return; - } - - Session ses = session(tx); - - try { - GridCacheHibernateBlobStoreEntry entry0 = new GridCacheHibernateBlobStoreEntry(toBytes(key), toBytes(val)); - - ses.saveOrUpdate(entry0); - } - catch (IgniteCheckedException | HibernateException e) { - rollback(ses, tx); - - throw new CacheWriterException("Failed to put value to cache store [key=" + key + ", val" + val + "]", e); - } - finally { - end(ses, tx); - } - } - - /** {@inheritDoc} */ - @SuppressWarnings({"JpaQueryApiInspection", "JpaQlInspection"}) - @Override public void delete(Object key) { - init(); - - IgniteTx tx = transaction(); - - if (log.isDebugEnabled()) - log.debug("Store remove [key=" + key + ", tx=" + tx + ']'); - - Session ses = session(tx); - - try { - Object obj = ses.get(GridCacheHibernateBlobStoreEntry.class, toBytes(key)); - - if (obj != null) - ses.delete(obj); - } - catch (IgniteCheckedException | HibernateException e) { - rollback(ses, tx); - - throw new CacheWriterException("Failed to remove value from cache store with key: " + key, e); - } - finally { - end(ses, tx); - } - } - - /** - * Rolls back hibernate session. - * - * @param ses Hibernate session. - * @param tx Cache ongoing transaction. - */ - private void rollback(SharedSessionContract ses, IgniteTx tx) { - // Rollback only if there is no cache transaction, - // otherwise txEnd() will do all required work. - if (tx == null) { - Transaction hTx = ses.getTransaction(); - - if (hTx != null && hTx.isActive()) - hTx.rollback(); - } - } - - /** - * Ends hibernate session. - * - * @param ses Hibernate session. - * @param tx Cache ongoing transaction. - */ - private void end(Session ses, IgniteTx tx) { - // Commit only if there is no cache transaction, - // otherwise txEnd() will do all required work. - if (tx == null) { - Transaction hTx = ses.getTransaction(); - - if (hTx != null && hTx.isActive()) - hTx.commit(); - - ses.close(); - } - } - - /** {@inheritDoc} */ - @Override public void txEnd(boolean commit) { - init(); - - IgniteTx tx = transaction(); - - Map<String, Session> props = session().properties(); - - Session ses = props.remove(ATTR_SES); - - if (ses != null) { - Transaction hTx = ses.getTransaction(); - - if (hTx != null) { - try { - if (commit) { - ses.flush(); - - hTx.commit(); - } - else - hTx.rollback(); - - if (log.isDebugEnabled()) - log.debug("Transaction ended [xid=" + tx.xid() + ", commit=" + commit + ']'); - } - catch (HibernateException e) { - throw new CacheWriterException("Failed to end transaction [xid=" + tx.xid() + - ", commit=" + commit + ']', e); - } - finally { - ses.close(); - } - } - } - } - - /** - * Gets Hibernate session. - * - * @param tx Cache transaction. - * @return Session. - */ - Session session(@Nullable IgniteTx tx) { - Session ses; - - if (tx != null) { - Map<String, Session> props = session().properties(); - - ses = props.get(ATTR_SES); - - if (ses == null) { - ses = sesFactory.openSession(); - - ses.beginTransaction(); - - // Store session in transaction metadata, so it can be accessed - // for other operations on the same transaction. - props.put(ATTR_SES, ses); - - if (log.isDebugEnabled()) - log.debug("Hibernate session open [ses=" + ses + ", tx=" + tx.xid() + "]"); - } - } - else { - ses = sesFactory.openSession(); - - ses.beginTransaction(); - } - - return ses; - } - - /** - * Sets session factory. - * - * @param sesFactory Session factory. - */ - public void setSessionFactory(SessionFactory sesFactory) { - this.sesFactory = sesFactory; - } - - /** - * Sets hibernate configuration path. - * <p> - * This may be either URL or file path or classpath resource. - * - * @param hibernateCfgPath URL or file path or classpath resource - * pointing to hibernate configuration XML file. - */ - public void setHibernateConfigurationPath(String hibernateCfgPath) { - this.hibernateCfgPath = hibernateCfgPath; - } - - /** - * Sets Hibernate properties. - * - * @param hibernateProps Hibernate properties. - */ - public void setHibernateProperties(Properties hibernateProps) { - this.hibernateProps = hibernateProps; - } - - /** - * Initializes store. - * - * @throws IgniteException If failed to initialize. - */ - private void init() throws IgniteException { - if (initGuard.compareAndSet(false, true)) { - if (log.isDebugEnabled()) - log.debug("Initializing cache store."); - - try { - if (sesFactory != null) - // Session factory has been provided - nothing to do. - return; - - if (!F.isEmpty(hibernateCfgPath)) { - try { - URL url = new URL(hibernateCfgPath); - - sesFactory = new Configuration().configure(url).buildSessionFactory(); - - if (log.isDebugEnabled()) - log.debug("Configured session factory using URL: " + url); - - // Session factory has been successfully initialized. - return; - } - catch (MalformedURLException e) { - if (log.isDebugEnabled()) - log.debug("Caught malformed URL exception: " + e.getMessage()); - } - - // Provided path is not a valid URL. File? - File cfgFile = new File(hibernateCfgPath); - - if (cfgFile.exists()) { - sesFactory = new Configuration().configure(cfgFile).buildSessionFactory(); - - if (log.isDebugEnabled()) - log.debug("Configured session factory using file: " + hibernateCfgPath); - - // Session factory has been successfully initialized. - return; - } - - // Provided path is not a file. Classpath resource? - sesFactory = new Configuration().configure(hibernateCfgPath).buildSessionFactory(); - - if (log.isDebugEnabled()) - log.debug("Configured session factory using classpath resource: " + hibernateCfgPath); - } - else { - if (hibernateProps == null) { - U.warn(log, "No Hibernate configuration has been provided for store (will use default)."); - - hibernateProps = new Properties(); - - hibernateProps.setProperty("hibernate.connection.url", DFLT_CONN_URL); - hibernateProps.setProperty("hibernate.show_sql", DFLT_SHOW_SQL); - hibernateProps.setProperty("hibernate.hbm2ddl.auto", DFLT_HBM2DDL_AUTO); - } - - Configuration cfg = new Configuration(); - - cfg.setProperties(hibernateProps); - - assert resourceAvailable(MAPPING_RESOURCE) : MAPPING_RESOURCE; - - cfg.addResource(MAPPING_RESOURCE); - - sesFactory = cfg.buildSessionFactory(); - - if (log.isDebugEnabled()) - log.debug("Configured session factory using properties: " + hibernateProps); - } - } - catch (HibernateException e) { - throw new IgniteException("Failed to initialize store.", e); - } - finally { - initLatch.countDown(); - } - } - else if (initLatch.getCount() > 0) { - try { - U.await(initLatch); - } - catch (IgniteInterruptedException e) { - throw new IgniteException(e); - } - } - - if (sesFactory == null) - throw new IgniteException("Cache store was not properly initialized."); - } - - /** - * Checks availability of a classpath resource. - * - * @param name Resource name. - * @return {@code true} if resource is available and ready for read, {@code false} otherwise. - */ - private boolean resourceAvailable(String name) { - InputStream cfgStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(name); - - if (cfgStream == null) { - log.error("Classpath resource not found: " + name); - - return false; - } - - try { - // Read a single byte to force actual content access by JVM. - cfgStream.read(); - - return true; - } - catch (IOException e) { - log.error("Failed to read classpath resource: " + name, e); - - return false; - } - finally { - U.close(cfgStream, log); - } - } - - /** {@inheritDoc} */ - @Override public String toString() { - return S.toString(GridCacheHibernateBlobStore.class, this); - } - - /** - * Serialize object to byte array using marshaller. - * - * @param obj Object to convert to byte array. - * @return Byte array. - * @throws IgniteCheckedException If failed to convert. - */ - protected byte[] toBytes(Object obj) throws IgniteCheckedException { - return ignite.configuration().getMarshaller().marshal(obj); - } - - /** - * Deserialize object from byte array using marshaller. - * - * @param bytes Bytes to deserialize. - * @param <X> Result object type. - * @return Deserialized object. - * @throws IgniteCheckedException If failed. - */ - protected <X> X fromBytes(byte[] bytes) throws IgniteCheckedException { - if (bytes == null || bytes.length == 0) - return null; - - return ignite.configuration().getMarshaller().unmarshal(bytes, getClass().getClassLoader()); - } - - /** - * @return Current transaction. - */ - @Nullable private IgniteTx transaction() { - CacheStoreSession ses = session(); - - return ses != null ? ses.transaction() : null; - } -} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/ed7736f3/modules/hibernate/src/main/java/org/gridgain/grid/cache/store/hibernate/GridCacheHibernateBlobStoreEntry.hbm.xml ---------------------------------------------------------------------- diff --git a/modules/hibernate/src/main/java/org/gridgain/grid/cache/store/hibernate/GridCacheHibernateBlobStoreEntry.hbm.xml b/modules/hibernate/src/main/java/org/gridgain/grid/cache/store/hibernate/GridCacheHibernateBlobStoreEntry.hbm.xml deleted file mode 100644 index 97865a8..0000000 --- a/modules/hibernate/src/main/java/org/gridgain/grid/cache/store/hibernate/GridCacheHibernateBlobStoreEntry.hbm.xml +++ /dev/null @@ -1,29 +0,0 @@ -<?xml version="1.0"?> -<!-- - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - --> - -<!DOCTYPE hibernate-mapping PUBLIC - "-//Hibernate/Hibernate Mapping DTD 3.0//EN" - "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> - -<hibernate-mapping package="org.gridgain.examples.datagrid.store" default-access="field"> - <class name="org.gridgain.grid.cache.store.hibernate.GridCacheHibernateBlobStoreEntry" table="ENTRIES"> - <id name="key"/> - - <property name="val"/> - </class> -</hibernate-mapping> http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/ed7736f3/modules/hibernate/src/main/java/org/gridgain/grid/cache/store/hibernate/GridCacheHibernateBlobStoreEntry.java ---------------------------------------------------------------------- diff --git a/modules/hibernate/src/main/java/org/gridgain/grid/cache/store/hibernate/GridCacheHibernateBlobStoreEntry.java b/modules/hibernate/src/main/java/org/gridgain/grid/cache/store/hibernate/GridCacheHibernateBlobStoreEntry.java deleted file mode 100644 index f8267fb..0000000 --- a/modules/hibernate/src/main/java/org/gridgain/grid/cache/store/hibernate/GridCacheHibernateBlobStoreEntry.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.gridgain.grid.cache.store.hibernate; - -import javax.persistence.*; - -/** - * Entry that is used by {@link GridCacheHibernateBlobStore} implementation. - * <p> - * Note that this is a reference implementation for tests only. - * When running on production systems use concrete key-value types to - * get better performance. - */ -@Entity -@Table(name = "ENTRIES") -public class GridCacheHibernateBlobStoreEntry { - /** Key (use concrete key type in production). */ - @Id - @Column(length = 65535) - private byte[] key; - - /** Value (use concrete value type in production). */ - @Column(length = 65535) - private byte[] val; - - /** - * Constructor. - */ - GridCacheHibernateBlobStoreEntry() { - // No-op. - } - - /** - * Constructor. - * - * @param key Key. - * @param val Value. - */ - GridCacheHibernateBlobStoreEntry(byte[] key, byte[] val) { - this.key = key; - this.val = val; - } - - /** - * @return Key. - */ - public byte[] getKey() { - return key; - } - - /** - * @param key Key. - */ - public void setKey(byte[] key) { - this.key = key; - } - - /** - * @return Value. - */ - public byte[] getValue() { - return val; - } - - /** - * @param val Value. - */ - public void setValue(byte[] val) { - this.val = val; - } -} http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/ed7736f3/modules/hibernate/src/main/java/org/gridgain/grid/cache/store/hibernate/package.html ---------------------------------------------------------------------- diff --git a/modules/hibernate/src/main/java/org/gridgain/grid/cache/store/hibernate/package.html b/modules/hibernate/src/main/java/org/gridgain/grid/cache/store/hibernate/package.html deleted file mode 100644 index 46ebe39..0000000 --- a/modules/hibernate/src/main/java/org/gridgain/grid/cache/store/hibernate/package.html +++ /dev/null @@ -1,23 +0,0 @@ -<!-- - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - --> -<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> -<html> -<body> - <!-- Package description. --> - Contains reference Hibernate-based cache store implementation. -</body> -</html> http://git-wip-us.apache.org/repos/asf/incubator-ignite/blob/ed7736f3/modules/hibernate/src/test/java/org/apache/ignite/cache/hibernate/GridHibernateL2CacheConfigurationSelfTest.java ---------------------------------------------------------------------- diff --git a/modules/hibernate/src/test/java/org/apache/ignite/cache/hibernate/GridHibernateL2CacheConfigurationSelfTest.java b/modules/hibernate/src/test/java/org/apache/ignite/cache/hibernate/GridHibernateL2CacheConfigurationSelfTest.java new file mode 100644 index 0000000..f441fff --- /dev/null +++ b/modules/hibernate/src/test/java/org/apache/ignite/cache/hibernate/GridHibernateL2CacheConfigurationSelfTest.java @@ -0,0 +1,379 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.ignite.cache.hibernate; + +import org.apache.ignite.cache.*; +import org.apache.ignite.configuration.*; +import org.apache.ignite.spi.discovery.tcp.*; +import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.*; +import org.apache.ignite.testframework.junits.common.*; +import org.hibernate.*; +import org.hibernate.annotations.*; +import org.hibernate.cache.spi.access.AccessType; +import org.hibernate.cfg.*; +import org.hibernate.service.*; + +import javax.persistence.*; + +import java.util.*; + +import static org.apache.ignite.cache.GridCacheAtomicityMode.*; +import static org.apache.ignite.cache.GridCacheMode.*; +import static org.apache.ignite.cache.hibernate.GridHibernateRegionFactory.*; +import static org.hibernate.cfg.AvailableSettings.*; + +/** + * Tests Hibernate L2 cache configuration. + */ +public class GridHibernateL2CacheConfigurationSelfTest extends GridCommonAbstractTest { + /** */ + public static final String ENTITY1_NAME = Entity1.class.getName(); + + /** */ + public static final String ENTITY2_NAME = Entity2.class.getName(); + + /** */ + public static final String ENTITY3_NAME = Entity3.class.getName(); + + /** */ + public static final String ENTITY4_NAME = Entity4.class.getName(); + + /** */ + public static final String TIMESTAMP_CACHE = "org.hibernate.cache.spi.UpdateTimestampsCache"; + + /** */ + public static final String QUERY_CACHE = "org.hibernate.cache.internal.StandardQueryCache"; + + /** */ + public static final String CONNECTION_URL = "jdbc:h2:mem:example;DB_CLOSE_DELAY=-1"; + + /** If {@code true} then sets default cache in configuration. */ + private boolean dfltCache; + + /** {@inheritDoc} */ + @Override protected void beforeTestsStarted() throws Exception { + startGrid(0); + } + + /** {@inheritDoc} */ + @Override protected void afterTestsStopped() throws Exception { + stopAllGrids(); + } + + /** {@inheritDoc} */ + @Override protected void afterTest() throws Exception { + for (GridCache<?, ?> cache : grid(0).caches()) + cache.clearAll(); + } + + /** {@inheritDoc} */ + @Override protected IgniteConfiguration getConfiguration(String gridName) throws Exception { + IgniteConfiguration cfg = super.getConfiguration(gridName); + + TcpDiscoverySpi discoSpi = new TcpDiscoverySpi(); + + discoSpi.setIpFinder(new TcpDiscoveryVmIpFinder(true)); + + cfg.setDiscoverySpi(discoSpi); + + cfg.setCacheConfiguration(cacheConfiguration(ENTITY3_NAME), cacheConfiguration(ENTITY4_NAME), + cacheConfiguration("cache1"), cacheConfiguration("cache2"), cacheConfiguration("cache3"), + cacheConfiguration(TIMESTAMP_CACHE), cacheConfiguration(QUERY_CACHE)); + + return cfg; + } + + /** + * @param cacheName Cache name. + * @return Cache configuration. + */ + private CacheConfiguration cacheConfiguration(String cacheName) { + CacheConfiguration cfg = new CacheConfiguration(); + + cfg.setName(cacheName); + + cfg.setCacheMode(PARTITIONED); + + cfg.setAtomicityMode(ATOMIC); + + return cfg; + } + /** + * @param gridName Grid name. + * @return Hibernate configuration. + */ + protected Configuration hibernateConfiguration(String gridName) { + Configuration cfg = new Configuration(); + + cfg.addAnnotatedClass(Entity1.class); + cfg.addAnnotatedClass(Entity2.class); + cfg.addAnnotatedClass(Entity3.class); + cfg.addAnnotatedClass(Entity4.class); + + cfg.setProperty(DFLT_ACCESS_TYPE_PROPERTY, AccessType.NONSTRICT_READ_WRITE.name()); + + cfg.setProperty(HBM2DDL_AUTO, "create"); + + cfg.setProperty(GENERATE_STATISTICS, "true"); + + cfg.setProperty(USE_SECOND_LEVEL_CACHE, "true"); + + cfg.setProperty(USE_QUERY_CACHE, "true"); + + cfg.setProperty(CACHE_REGION_FACTORY, GridHibernateRegionFactory.class.getName()); + + cfg.setProperty(RELEASE_CONNECTIONS, "on_close"); + + cfg.setProperty(GRID_NAME_PROPERTY, gridName); + + cfg.setProperty(REGION_CACHE_PROPERTY + ENTITY1_NAME, "cache1"); + cfg.setProperty(REGION_CACHE_PROPERTY + ENTITY2_NAME, "cache2"); + cfg.setProperty(REGION_CACHE_PROPERTY + TIMESTAMP_CACHE, TIMESTAMP_CACHE); + cfg.setProperty(REGION_CACHE_PROPERTY + QUERY_CACHE, QUERY_CACHE); + + if (dfltCache) + cfg.setProperty(DFLT_CACHE_NAME_PROPERTY, "cache3"); + + return cfg; + } + + /** + * Tests property {@link GridHibernateRegionFactory#REGION_CACHE_PROPERTY}. + */ + public void testPerRegionCacheProperty() { + testCacheUsage(1, 1, 0, 1, 1); + } + + /** + * Tests property {@link GridHibernateRegionFactory#DFLT_CACHE_NAME_PROPERTY}. + */ + public void testDefaultCache() { + dfltCache = true; + + testCacheUsage(1, 1, 2, 0, 0); + } + + /** + * @param expCache1 Expected size of cache with name 'cache1'. + * @param expCache2 Expected size of cache with name 'cache2'. + * @param expCache3 Expected size of cache with name 'cache3'. + * @param expCacheE3 Expected size of cache with name {@link #ENTITY3_NAME}. + * @param expCacheE4 Expected size of cache with name {@link #ENTITY4_NAME}. + */ + @SuppressWarnings("unchecked") + private void testCacheUsage(int expCache1, int expCache2, int expCache3, int expCacheE3, int expCacheE4) { + SessionFactory sesFactory = startHibernate(getTestGridName(0)); + + try { + Session ses = sesFactory.openSession(); + + try { + Transaction tx = ses.beginTransaction(); + + ses.save(new Entity1()); + ses.save(new Entity2()); + ses.save(new Entity3()); + ses.save(new Entity4()); + + tx.commit(); + } + finally { + ses.close(); + } + + ses = sesFactory.openSession(); + + try { + List<Entity1> list1 = ses.createCriteria(ENTITY1_NAME).list(); + + assertEquals(1, list1.size()); + + for (Entity1 e : list1) { + ses.load(ENTITY1_NAME, e.getId()); + assertNotNull(e.getId()); + } + + List<Entity2> list2 = ses.createCriteria(ENTITY2_NAME).list(); + + assertEquals(1, list2.size()); + + for (Entity2 e : list2) + assertNotNull(e.getId()); + + List<Entity3> list3 = ses.createCriteria(ENTITY3_NAME).list(); + + assertEquals(1, list3.size()); + + for (Entity3 e : list3) + assertNotNull(e.getId()); + + List<Entity4> list4 = ses.createCriteria(ENTITY4_NAME).list(); + + assertEquals(1, list4.size()); + + for (Entity4 e : list4) + assertNotNull(e.getId()); + } + finally { + ses.close(); + } + + GridCache<Object, Object> cache1 = grid(0).cache("cache1"); + GridCache<Object, Object> cache2 = grid(0).cache("cache2"); + GridCache<Object, Object> cache3 = grid(0).cache("cache3"); + GridCache<Object, Object> cacheE3 = grid(0).cache(ENTITY3_NAME); + GridCache<Object, Object> cacheE4 = grid(0).cache(ENTITY4_NAME); + + assertEquals("Unexpected entries: " + cache1.entrySet(), expCache1, cache1.size()); + assertEquals("Unexpected entries: " + cache2.entrySet(), expCache2, cache2.size()); + assertEquals("Unexpected entries: " + cache3.entrySet(), expCache3, cache3.size()); + assertEquals("Unexpected entries: " + cacheE3.entrySet(), expCacheE3, cacheE3.size()); + assertEquals("Unexpected entries: " + cacheE4.entrySet(), expCacheE4, cacheE4.size()); + } + finally { + sesFactory.close(); + } + } + + /** + * @param gridName Name of the grid providing caches. + * @return Session factory. + */ + private SessionFactory startHibernate(String gridName) { + Configuration cfg = hibernateConfiguration(gridName); + + ServiceRegistryBuilder builder = new ServiceRegistryBuilder(); + + builder.applySetting("hibernate.connection.url", CONNECTION_URL); + builder.applySetting("hibernate.show_sql", false); + + return cfg.buildSessionFactory(builder.buildServiceRegistry()); + } + + /** + * Test Hibernate entity1. + */ + @javax.persistence.Entity + @SuppressWarnings({"PublicInnerClass", "UnnecessaryFullyQualifiedName"}) + @Cacheable + @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) + public static class Entity1 { + /** */ + private int id; + + /** + * @return ID. + */ + @Id + @GeneratedValue + public int getId() { + return id; + } + + /** + * @param id ID. + */ + public void setId(int id) { + this.id = id; + } + } + + /** + * Test Hibernate entity2. + */ + @javax.persistence.Entity + @SuppressWarnings({"PublicInnerClass", "UnnecessaryFullyQualifiedName"}) + @Cacheable + @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) + public static class Entity2 { + /** */ + private int id; + + /** + * @return ID. + */ + @Id + @GeneratedValue + public int getId() { + return id; + } + + /** + * @param id ID. + */ + public void setId(int id) { + this.id = id; + } + } + + /** + * Test Hibernate entity3. + */ + @javax.persistence.Entity + @SuppressWarnings({"PublicInnerClass", "UnnecessaryFullyQualifiedName"}) + @Cacheable + @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) + public static class Entity3 { + /** */ + private int id; + + /** + * @return ID. + */ + @Id + @GeneratedValue + public int getId() { + return id; + } + + /** + * @param id ID. + */ + public void setId(int id) { + this.id = id; + } + } + + /** + * Test Hibernate entity4. + */ + @javax.persistence.Entity + @SuppressWarnings({"PublicInnerClass", "UnnecessaryFullyQualifiedName"}) + @Cacheable + @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) + public static class Entity4 { + /** */ + private int id; + + /** + * @return ID. + */ + @Id + @GeneratedValue + public int getId() { + return id; + } + + /** + * @param id ID. + */ + public void setId(int id) { + this.id = id; + } + } +}