Skip to content

Commit

Permalink
hibernate 6 adaptation
Browse files Browse the repository at this point in the history
  • Loading branch information
mbussolotto committed Oct 4, 2024
1 parent ed3bd1c commit 62820ae
Show file tree
Hide file tree
Showing 40 changed files with 849 additions and 532 deletions.
15 changes: 12 additions & 3 deletions java/.vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,18 @@
"vmArgs": [
"-Drhn.config.dir=${workspaceFolder}/buildconf/test",
"-Dlog4j2.configurationFile=${workspaceFolder}/buildconf/test/log4j2.properties"
]
]
},
"ant.buildFilenames": "manager-build.xml",
"java.jdt.ls.vmargs": "-XX:+UseParallelGC -XX:GCTimeRatio=4 -XX:AdaptiveSizePolicyWeight=90 -Dsun.zip.disableMemoryMapping=true -Xmx2G -Xms100m -Xlog:disable",
"java.compile.nullAnalysis.mode": "automatic"
}
"java.compile.nullAnalysis.mode": "automatic",
"java.checkstyle.configuration": "${workspaceFolder}/buildconf/checkstyle.xml",
"java.project.sourcePaths": [
"lib",
"code/src",
"buildconf/ivy/repository/suse",
"build/java-branding",
"build/classes",
"build/webapp"
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,9 @@
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.metadata.ClassMetadata;

import io.prometheus.client.hibernate.HibernateStatisticsCollector;
import jakarta.persistence.metamodel.Metamodel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
Expand All @@ -36,9 +37,6 @@
import java.util.Properties;
import java.util.Set;

import io.prometheus.client.hibernate.HibernateStatisticsCollector;


/**
* Manages the lifecycle of Hibernate SessionFactory and associated
* thread-scoped Hibernate sessions.
Expand Down Expand Up @@ -110,16 +108,12 @@ public boolean isTransactionPending() {
* {@inheritDoc}
*/
@Override
public ClassMetadata getMetadata(Object target) {
public Metamodel getMetadata(Object target) {
if (target == null) {
return null;
}

if (target instanceof Class) {
return sessionFactory.getClassMetadata((Class<?>) target);
}

return sessionFactory.getClassMetadata(target.getClass());
return sessionFactory.getMetamodel();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import org.hibernate.Session;
import org.hibernate.metadata.ClassMetadata;

import jakarta.persistence.metamodel.Metamodel;
import java.util.Optional;

/**
Expand Down Expand Up @@ -113,7 +114,7 @@ public interface ConnectionManager {
* @param target an object instance or a class to retrieve the metadata for
* @return the {@link ClassMetadata} for the given object.
*/
ClassMetadata getMetadata(Object target);
Metamodel getMetadata(Object target);

/**
* Closes Hibernate Session stored in ThreadLocal storage.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.EmptyInterceptor;
import org.hibernate.Interceptor;
import org.hibernate.type.Type;

import java.io.Serializable;
Expand All @@ -27,7 +27,7 @@
* convert empty varchar to null automatically. It depends on the setting of the
* interceptor.
*/
public class EmptyVarcharInterceptor extends EmptyInterceptor {
public class EmptyVarcharInterceptor implements Interceptor {

private static final long serialVersionUID = 5351605245345217308L;

Expand Down Expand Up @@ -58,8 +58,7 @@ protected static boolean emptyStringToNull(Object entity, Serializable id,
boolean modified = false;

for (int i = 0; i < types.length; i++) {
// type is string (VARCHAR) and state is empty string
if ((types[i] instanceof StringType) && "".equals(state[i])) {
if ("".equals(state[i])) {
if (LOG.isDebugEnabled()) {
LOG.debug("Object {} is setting empty string {}", entity.getClass().getCanonicalName(),
propertyNames[i]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,10 @@
package com.redhat.rhn.common.hibernate;

import org.hibernate.HibernateException;
import org.hibernate.collection.spi.PersistentList;
import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.collection.spi.PersistentList;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.metamodel.CollectionClassification;
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.usertype.UserCollectionType;

Expand Down Expand Up @@ -155,7 +156,19 @@ public Object instantiate() {
}

/**
*
* {@inheritDoc}
*/
@Override
public Class<?> getCollectionClass() {
return null;
}

@Override
public CollectionClassification getClassification() {
return null;
}

/**
* ForceRecreationList
*/
private static class ForceRecreationList extends PersistentList {
Expand Down
38 changes: 13 additions & 25 deletions java/code/src/com/redhat/rhn/common/hibernate/HibernateFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,15 @@
import org.apache.logging.log4j.Logger;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.LockOptions;
import org.hibernate.MappingException;
import org.hibernate.Session;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.query.Query;

import jakarta.persistence.FlushModeType;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaDelete;
import jakarta.persistence.criteria.Root;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
Expand All @@ -53,11 +55,6 @@
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import jakarta.persistence.FlushModeType;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaDelete;
import jakarta.persistence.criteria.Root;

/**
* HibernateFactory - Helper superclass that contains methods for fetching and
* storing Objects from the DB using Hibernate.
Expand Down Expand Up @@ -462,7 +459,7 @@ protected Object lockObject(Class clazz, Serializable id) {
try {
session = HibernateFactory.getSession();

retval = session.get(clazz, id, LockMode.UPGRADE);
retval = session.get(clazz, id, LockOptions.UPGRADE);
}
catch (MappingException me) {
getLogger().error("Mapping not found for {}", clazz.getName(), me);
Expand All @@ -483,21 +480,8 @@ protected Object lockObject(Class clazz, Serializable id) {
* @param <T> the entity type
*/
public static <T> T reload(T obj) throws HibernateException {
// assertNotNull(obj);
ClassMetadata cmd = connectionManager.getMetadata(obj);
Serializable id = cmd.getIdentifier(obj, (SessionImplementor) getSession());
Session session = getSession();
session.flush();
session.evict(obj);
/*
* In hibernate 3, the following doesn't work:
* session.load(obj.getClass(), id);
* load returns the proxy class instead of the persisted class, ie,
* Filter$$EnhancerByCGLIB$$9bcc734d_2 instead of Filter.
* session.get is set to not return the proxy class, so that is what we'll use.
*/
// assertNotSame(obj, result);
return (T) session.get(obj.getClass(), id);
// TODO
return null;
}

/**
Expand Down Expand Up @@ -574,8 +558,12 @@ public static Blob byteArrayToBlob(byte[] data) {
if (data.length == 0) {
return null;
}
return Hibernate.getLobCreator(getSession()).createBlob(data);

Session session = getSession();
if (session == null) {
return null;
}
return session.getLobHelper().createBlob(data);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.query.Query;

import jakarta.persistence.FlushModeType;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
Expand All @@ -46,7 +46,6 @@
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import jakarta.persistence.FlushModeType;

/**
* HibernateFactory - Helper superclass that contains methods for fetching and
Expand Down Expand Up @@ -563,7 +562,11 @@ public Blob byteArrayToBlob(byte[] data) {
if (data.length == 0) {
return null;
}
return Hibernate.getLobCreator(getSession()).createBlob(data);
Session session = getSession();
if (session == null) {
return null;
}
return session.getLobHelper().createBlob(data);

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ public void testLongField() {
TestObject to = new TestObject();
to.setLongField(10L);
assertNull(validator.validate("longField", to));
to.setParameterField(100L);
to.setLongField(100L);
assertNotNull(validator.validate("longField", to));
to.setThirdLongField(Long.MAX_VALUE);
assertNull(validator.validate("thirdLongFiled", to));
Expand Down
24 changes: 12 additions & 12 deletions java/code/src/com/redhat/rhn/domain/audit/ScapFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,7 @@ public static void clearTestResult(long serverId, long actionId) {
* @return the {@link XccdfBenchmark} if any
*/
public static Optional<XccdfBenchmark> lookupBenchmarkById(long benchmarkId) {
return Optional.ofNullable(
(XccdfBenchmark)getSession().get(XccdfBenchmark.class, benchmarkId));
return Optional.ofNullable(getSession().get(XccdfBenchmark.class, benchmarkId));
}

/**
Expand All @@ -98,7 +97,7 @@ public static Optional<XccdfBenchmark> lookupBenchmarkById(long benchmarkId) {
* @return the {@link XccdfIdent} if any
*/
public static Optional<XccdfIdent> lookupIdentById(long identId) {
return Optional.ofNullable((XccdfIdent)getSession().get(XccdfIdent.class, identId));
return Optional.ofNullable(getSession().get(XccdfIdent.class, identId));
}

/**
Expand All @@ -107,20 +106,21 @@ public static Optional<XccdfIdent> lookupIdentById(long identId) {
* @return the {@link XccdfProfile} if any
*/
public static Optional<XccdfProfile> lookupProfileById(long profileId) {
return Optional.ofNullable(
(XccdfProfile)getSession().get(XccdfProfile.class, profileId));
return Optional.ofNullable(getSession().get(XccdfProfile.class, profileId));
}

/**
* Find a {@link XccdfRuleResultType} by id.
* @param label label id
* @return the {@link XccdfRuleResultType} if any
* Queries an XccdfRuleResultType by its label.
*
* @param label the label of the XccdfRuleResultType
* @return optional of XccdfRuleResultType
*/
public static Optional<XccdfRuleResultType> lookupRuleResultType(String label) {
return getSession().getCriteriaBuilder().createQuery(XccdfRuleResultType.class)
.add(Restrictions.eq("label", label))
.list()
.stream().findFirst();
String sql = "SELECT * FROM rhnXccdfRuleResultType WHERE label = :label";
XccdfRuleResultType result =
getSession().createNativeQuery(sql, XccdfRuleResultType.class)
.setParameter("label", label).getResultStream().findFirst().orElse(null);
return Optional.ofNullable(result);
}

/**
Expand Down
27 changes: 12 additions & 15 deletions java/code/src/com/redhat/rhn/domain/channel/AccessTokenFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -57,22 +57,21 @@ public class AccessTokenFactory extends HibernateFactory {
* @return optional of AccessToken
*/
public static Optional<AccessToken> lookupById(long id) {
return Optional.ofNullable(
(AccessToken)HibernateFactory.getSession()
.getCriteriaBuilder().createQuery(AccessToken.class)
.add(Restrictions.eq("id", id))
.uniqueResult()
);
String sql = "SELECT * FROM suseChannelAccessToken WHERE id = :id";
AccessToken accessToken = HibernateFactory.getSession().createNativeQuery(sql, AccessToken.class)
.setParameter("id", id).uniqueResult();
return Optional.ofNullable(accessToken);
}

/**
* Queries all AccessTokens
* @return list of AccessTokens
*/
public static List<AccessToken> all() {
return (List<AccessToken>) HibernateFactory.getSession()
.getCriteriaBuilder().createQuery(AccessToken.class)
.list();
String sql = "SELECT * FROM suseChannelAccessToken";
List<AccessToken> accessTokens =
HibernateFactory.getSession().createNativeQuery(sql, AccessToken.class).getResultList();
return accessTokens;
}

/**
Expand All @@ -81,12 +80,10 @@ public static List<AccessToken> all() {
* @return optional of AccessToken
*/
public static Optional<AccessToken> lookupByToken(String token) {
return Optional.ofNullable(
(AccessToken)HibernateFactory.getSession()
.getCriteriaBuilder().createQuery(AccessToken.class)
.add(Restrictions.eq("token", token))
.uniqueResult()
);
String sql = "SELECT * FROM suseChannelAccessToken WHERE token = :token";
AccessToken accessToken = HibernateFactory.getSession().createNativeQuery(sql, AccessToken.class)
.setParameter("token", token).uniqueResult();
return Optional.ofNullable(accessToken);
}

/**
Expand Down
Loading

0 comments on commit 62820ae

Please sign in to comment.