Skip to content

Commit

Permalink
Use setParameter in Hibernate queries
Browse files Browse the repository at this point in the history
  • Loading branch information
mbussolotto committed Dec 19, 2024
1 parent b3cf9ef commit f3cd90b
Show file tree
Hide file tree
Showing 33 changed files with 202 additions and 169 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.EmptyInterceptor;
import org.hibernate.type.StringType;
import org.hibernate.type.Type;

import java.io.Serializable;
Expand Down Expand Up @@ -59,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
3 changes: 2 additions & 1 deletion java/code/src/com/redhat/rhn/domain/BaseDomainHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
Expand All @@ -31,7 +32,7 @@
* DB table: web_contact
*/
@MappedSuperclass
public abstract class BaseDomainHelper {
public abstract class BaseDomainHelper implements Serializable {
private Date created = new Date();
private Date modified;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import com.redhat.rhn.testing.RhnBaseTestCase;

import org.hibernate.Session;
import org.hibernate.type.StringType;
import org.junit.jupiter.api.Test;

/**
Expand Down Expand Up @@ -70,7 +71,7 @@ public void testFindByLabel() throws Exception {
private ActionType lookupByLabel(String label) {
Session session = HibernateFactory.getSession();
return (ActionType) session.getNamedQuery("ActionType.findByLabel")
.setString("label", label)
.setParameter("label", label, StringType.INSTANCE)
//Retrieve from cache if there
.setCacheable(true)
.uniqueResult();
Expand Down
31 changes: 16 additions & 15 deletions java/code/src/com/redhat/rhn/domain/audit/ScapFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.criterion.Restrictions;
import org.hibernate.type.LongType;
import org.hibernate.type.StringType;

import java.util.List;
import java.util.Map;
Expand Down Expand Up @@ -77,8 +78,8 @@ public static void delete(XccdfTestResult tr) {
public static void clearTestResult(long serverId, long actionId) {
List<XccdfTestResult> results = getSession()
.getNamedQuery("XccdfTestResult.findByActionId")
.setLong("serverId", serverId)
.setLong("actionId", actionId)
.setParameter("serverId", serverId, LongType.INSTANCE)
.setParameter("actionId", actionId, LongType.INSTANCE)
.list();
results.forEach(ScapFactory::delete);
}
Expand All @@ -89,8 +90,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 @@ -99,7 +99,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 @@ -108,20 +108,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().createCriteria(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, StringType.INSTANCE).getResultStream().findFirst().orElse(null);
return Optional.ofNullable(result);
}

/**
Expand Down
21 changes: 14 additions & 7 deletions java/code/src/com/redhat/rhn/domain/common/CommonFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.type.LongType;
import org.hibernate.type.StringType;

import java.util.Calendar;
import java.util.Date;
Expand Down Expand Up @@ -87,9 +89,12 @@ public static FileList lookupFileList(Long idIn, Org org) {
Session session = null;
//look for Kickstart data by id
session = HibernateFactory.getSession();
return (FileList) session.getNamedQuery("FileList.findByIdAndOrg")
.setLong("id", idIn)
.setLong("org_id", org.getId())
return session.createNativeQuery("""
SELECT * from rhnFileList
WHERE id = :id
and org_id = :org_id """, FileList.class)
.setParameter("id", idIn, LongType.INSTANCE)
.setParameter("org_id", org.getId(), LongType.INSTANCE)
.uniqueResult();
}

Expand All @@ -103,8 +108,10 @@ public static FileList lookupFileList(String labelIn, Org org) {
Session session = null;
//look for Kickstart data by label
session = HibernateFactory.getSession();
return (FileList) session.getNamedQuery("FileList.findByLabelAndOrg").setString("label", labelIn)
.setLong("org_id", org.getId()).uniqueResult();
return (FileList) session.getNamedQuery("FileList.findByLabelAndOrg")
.setParameter("label", labelIn, StringType.INSTANCE)
.setParameter("org_id", org.getId(), LongType.INSTANCE)
.uniqueResult();
}

/**
Expand Down Expand Up @@ -150,7 +157,7 @@ public static void saveTinyUrl(TinyUrl urlIn) {
public static TinyUrl lookupTinyUrl(String tokenIn) {
Session session = HibernateFactory.getSession();
return (TinyUrl) session.getNamedQuery("TinyUrl.findByToken")
.setString("token", tokenIn)
.uniqueResult();
.setParameter("token", tokenIn, StringType.INSTANCE)
.uniqueResult();
}
}
4 changes: 0 additions & 4 deletions java/code/src/com/redhat/rhn/domain/common/FileList.hbm.xml
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,6 @@ PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

</class>

<query name="FileList.findByIdAndOrg">
<![CDATA[from com.redhat.rhn.domain.common.FileList as f where f.id = :id
and f.org = :org_id]]>
</query>
<query name="FileList.findByLabelAndOrg">
<![CDATA[from com.redhat.rhn.domain.common.FileList as f where f.label = :label
and f.org = :org_id]]>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,14 @@
import com.redhat.rhn.domain.user.User;
import com.redhat.rhn.manager.configuration.ConfigurationManager;

import java.io.Serializable;
import java.util.List;

/**
*
* ConfigChannelListProcessor
*/
public class ConfigChannelListProcessor {
public class ConfigChannelListProcessor implements Serializable {

private void check(ConfigChannel cc) {
if (cc == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.hibernate.query.Query;
import org.hibernate.type.LongType;
import org.hibernate.type.StringType;

import java.io.IOException;
import java.io.InputStream;
Expand Down Expand Up @@ -431,10 +433,9 @@ public static ConfigFile lookupConfigFileByChannelAndName(Long channel, Long nam
Session session = HibernateFactory.getSession();
Query<ConfigFile> query =
session.getNamedQuery("ConfigFile.findByChannelAndName")
.setLong("channel_id", channel)
.setLong("name_id", name)
.setLong("state_id", ConfigFileState.normal().
getId());
.setParameter("channel_id", channel, LongType.INSTANCE)
.setParameter("name_id", name, LongType.INSTANCE)
.setParameter("state_id", ConfigFileState.normal().getId(), LongType.INSTANCE);
try {
return query.uniqueResult();
}
Expand Down Expand Up @@ -464,7 +465,7 @@ public static ConfigRevision lookupConfigRevisionById(Long id) {
public static ConfigRevision lookupConfigRevisionByRevId(ConfigFile cf, Long revId) {
Session session = HibernateFactory.getSession();
Query<ConfigRevision> q = session.getNamedQuery("ConfigRevision.findByRevisionAndConfigFile");
q.setLong("rev", revId);
q.setParameter("rev", revId, LongType.INSTANCE);
q.setParameter("cf", cf);
return q.uniqueResult();
}
Expand Down Expand Up @@ -515,7 +516,7 @@ static ConfigChannelType lookupConfigChannelTypeByLabel(String label) {
Session session = HibernateFactory.getSession();
return (ConfigChannelType)
session.getNamedQuery("ConfigChannelType.findByLabel")
.setString("label", label)
.setParameter("label", label, StringType.INSTANCE)
//Retrieve from cache if there
.setCacheable(true)
.uniqueResult();
Expand All @@ -532,7 +533,7 @@ static ConfigChannelType lookupConfigChannelTypeByLabel(String label) {
static ConfigFileState lookupConfigFileStateByLabel(String label) {
Session session = HibernateFactory.getSession();
return (ConfigFileState)session.getNamedQuery("ConfigFileState.findByLabel")
.setString("label", label)
.setParameter("label", label, StringType.INSTANCE)
//Retrieve from cache if there
.setCacheable(true)
.uniqueResult();
Expand All @@ -546,7 +547,7 @@ static ConfigFileState lookupConfigFileStateByLabel(String label) {
static ConfigFileType lookupConfigFileTypeByLabel(String label) {
Session session = HibernateFactory.getSession();
return (ConfigFileType)session.getNamedQuery("ConfigFileType.findByLabel")
.setString("label", label)
.setParameter("label", label, StringType.INSTANCE)
//Retrieve from cache if there
.setCacheable(true)
.uniqueResult();
Expand Down
31 changes: 18 additions & 13 deletions java/code/src/com/redhat/rhn/domain/errata/ErrataFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.hibernate.type.LongType;
import org.hibernate.type.StringType;

import java.util.ArrayList;
import java.util.Collection;
Expand Down Expand Up @@ -396,7 +398,8 @@ public static ErrataFileType lookupErrataFileType(String label) {
ErrataFileType retval;
try {
retval = (ErrataFileType) getSession().getNamedQuery("ErrataFileType.findByLabel")
.setString("label", label).setCacheable(true).uniqueResult();
.setParameter("label", label, StringType.INSTANCE)
.setCacheable(true).uniqueResult();
}
catch (HibernateException e) {
throw new HibernateRuntimeException(e.getMessage(), e);
Expand All @@ -413,9 +416,9 @@ public static ErrataFileType lookupErrataFileType(String label) {
public static List<ErrataFile> lookupErrataFilesByErrataAndFileType(Long errataId, String fileType) {
List<ErrataFile> retval;
try {
Query<ErrataFile> q = getSession().getNamedQuery("ErrataFile.listByErrataAndFileType");
q.setLong("errata_id", errataId);
q.setString("file_type", fileType.toUpperCase());
Query<ErrataFile> q = getSession().getNamedQuery("ErrataFile.listByErrataAndFileType")
.setParameter("errata_id", errataId, LongType.INSTANCE)
.setParameter("file_type", fileType.toUpperCase(), StringType.INSTANCE);
retval = q.list();
}
catch (HibernateException e) {
Expand Down Expand Up @@ -446,7 +449,7 @@ public static List<Errata> lookupErratasByAdvisoryType(String advisoryType) {
List<Errata> retval;
try {
retval = getSession().getNamedQuery("Errata.findByAdvisoryType")
.setString("type", advisoryType)
.setParameter("type", advisoryType, StringType.INSTANCE)
//Retrieve from cache if there
.setCacheable(true).list();
}
Expand All @@ -466,7 +469,8 @@ public static Errata lookupErrataById(Long id) {
Errata retval;
try {
retval = (Errata) getSession().getNamedQuery("Errata.findById")
.setLong("id", id).uniqueResult();
.setParameter("id", id, LongType.INSTANCE)
.uniqueResult();
}
catch (HibernateException he) {
log.error("Error loading ActionArchTypes from DB", he);
Expand All @@ -485,7 +489,7 @@ public static Errata lookupErrataById(Long id) {
public static List<Errata> lookupVendorAndUserErrataByAdvisoryAndOrg(String advisory, Org org) {
Session session = HibernateFactory.getSession();
return session.getNamedQuery("Errata.findVendorAnUserErrataByAdvisoryNameAndOrg")
.setParameter("advisory", advisory)
.setParameter("advisory", advisory, StringType.INSTANCE)
.setParameter("org", org)
.getResultList();
}
Expand All @@ -499,7 +503,7 @@ public static List<Errata> lookupVendorAndUserErrataByAdvisoryAndOrg(String advi
public static Errata lookupByAdvisoryAndOrg(String advisory, Org org) {
return (Errata) HibernateFactory.getSession()
.getNamedQuery("Errata.findByAdvisoryNameAndOrg")
.setParameter("advisory", advisory)
.setParameter("advisory", advisory, StringType.INSTANCE)
.setParameter("org", org)
.uniqueResult();
}
Expand All @@ -515,7 +519,7 @@ public static List<Errata> lookupByAdvisoryId(String advisoryId, Org org) {
List<Errata> retval;
try {
retval = getSession().getNamedQuery("Errata.findByAdvisory")
.setParameter("advisory", advisoryId)
.setParameter("advisory", advisoryId, StringType.INSTANCE)
.setParameter("org", org)
.getResultList();
}
Expand Down Expand Up @@ -712,8 +716,8 @@ public static List<Errata> lookupByChannelBetweenDates(Org org, Channel channel,
getNamedQuery("Errata.lookupByChannelBetweenDates")
.setParameter("org", org)
.setParameter("channel", channel)
.setParameter("start_date", startDate)
.setParameter("end_date", endDate)
.setParameter("start_date", startDate, StringType.INSTANCE)
.setParameter("end_date", endDate, StringType.INSTANCE)
.list();
}

Expand All @@ -731,8 +735,9 @@ public static List<Errata> lookupByChannelBetweenDates(Org org, Channel channel,
public static Optional<ErrataFile> lookupErrataFile(Long errataId, String filename) {
Session session = HibernateFactory.getSession();
return session.getNamedQuery("ErrataFile.lookupByErrataAndPackage")
.setParameter("errata_id", errataId)
.setParameter("filename", filename).uniqueResultOptional();
.setParameter("errata_id", errataId, LongType.INSTANCE)
.setParameter("filename", filename, StringType.INSTANCE)
.uniqueResultOptional();
}

/**
Expand Down
Loading

0 comments on commit f3cd90b

Please sign in to comment.