Hibernate Search does not work woth composite primary key using #IdClass - lucene

I've configured with hibernate-search annotation (4.1.1 version library) my class Intervento. So, I'm using jpa and in my case i can omit #DocumentId but I have a composite primary key...
#IdClass(it.domain.InterventoPK.class)
#Entity
#Indexed
#AnalyzerDef(name = "interventongram", tokenizer = #TokenizerDef(factory = StandardTokenizerFactory.class),
filters = {
#TokenFilterDef(factory = LowerCaseFilterFactory.class),
#TokenFilterDef(factory = StopFilterFactory.class, params = {
#Parameter(name = "words", value = "lucene/dictionary/stopwords.txt"),
#Parameter(name = "ignoreCase", value = "true"),
#Parameter(name = "enablePositionIncrements", value = "true")
}),
#TokenFilterDef(factory = ItalianLightStemFilterFactory.class),
#TokenFilterDef(factory = SynonymFilterFactory.class, params = {
#Parameter(name = "synonyms", value = "lucene/dictionary/synonyms.txt"),
#Parameter(name = "expand", value = "true")
}),
#TokenFilterDef(factory = SnowballPorterFilterFactory.class, params = {
#Parameter(name = "language", value = "Italian")
})
})
#Table(name = "intervento", catalog = "gestionale")
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(namespace = "Clinigo/it/domain", name = "Intervento")
#XmlRootElement(namespace = "Clinigo/it/domain")
public class Intervento implements Serializable {
private static final long serialVersionUID = 1L;
/**
*/
#Column(name = "idintervento", nullable = false)
#Basic(fetch = FetchType.EAGER)
#Id
#XmlElement
Integer idintervento;
/**
*/
#Column(name = "lingua_idlingua", nullable = false)
#Basic(fetch = FetchType.EAGER)
#Id
#XmlElement
Integer linguaIdlingua;
/**
*/
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "version", nullable = false)
#Basic(fetch = FetchType.EAGER)
#XmlElement
Calendar version;
...
I'm getting....can you help me?
ERROR: HSEARCH000058: HSEARCH000116: Unexpected error during MassIndexer operation
java.lang.ClassCastException: it.domain.InterventoPK cannot be cast to java.lang.Integer
at org.hibernate.type.descriptor.java.IntegerTypeDescriptor.unwrap(IntegerTypeDescriptor.java:36)
at org.hibernate.type.descriptor.sql.IntegerTypeDescriptor$1.doBind(IntegerTypeDescriptor.java:57)
at org.hibernate.type.descriptor.sql.BasicBinder.bind(BasicBinder.java:92)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:305)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:300)
at org.hibernate.loader.Loader.bindPositionalParameters(Loader.java:1891)
at org.hibernate.loader.Loader.bindParameterValues(Loader.java:1862)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1737)
at org.hibernate.loader.Loader.doQuery(Loader.java:828)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:289)
at org.hibernate.loader.Loader.doList(Loader.java:2447)
at org.hibernate.loader.Loader.doList(Loader.java:2433)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2263)
at org.hibernate.loader.Loader.list(Loader.java:2258)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:122)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1535)
at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:374)
at org.hibernate.search.batchindexing.impl.IdentifierConsumerEntityProducer.loadList(IdentifierConsumerEntityProducer.java:150)
at org.hibernate.search.batchindexing.impl.IdentifierConsumerEntityProducer.loadAllFromQueue(IdentifierConsumerEntityProducer.java:117)
at org.hibernate.search.batchindexing.impl.IdentifierConsumerEntityProducer.run(IdentifierConsumerEntityProducer.java:94)
at org.hibernate.search.batchindexing.impl.OptionallyWrapInJTATransaction.run(OptionallyWrapInJTATransaction.java:84)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)

Hibernate Search does not handle composite id classes used with #IdClass. A workaround would be to use #EmbeddedId and place idintervento and linguaIdlingua into InterventoPK.
Seems also that you asked the same question on the Hibernate Search forum - https://forum.hibernate.org/viewtopic.php?f=9&t=1024512

You can convert your custom object / composite key to Lucene Understandable format by using bridges. For example for a class
#Entity
#Indexed
public class Person {
#EmbeddedId #DocumentId Embedded id
#FieldBridge(impl=PersonPkBridge.class)
private PersonPK id;
...
}
You can write the bridge as like this. These codes are from the book 'Hibernate Search In Action'. I found it very helpful.

Does your class declared as composite key (it.domain.InterventoPK.class, as declared via #IdClass class-level annotation) only contain two integer fields? Since you've also annotated two such Integer fields with #Id on your Intervento class, the composite key class must only contain those fields and they must have the same name. Also that composite PK class needs to be Serializable. From the docs:
"map multiple properties as #Id properties and declare an external class to be the identifier type. This class, which needs to be Serializable, is declared on the entity via the #IdClass annotation. The identifier type must contain the same properties as the identifier properties of the entity: each property name must be the same, its type must be the same as well if the entity property is of a basic type, its type must be the type of the primary key of the associated entity if the entity property is an association (either a #OneToOne or a #ManyToOne)."
http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/
(search "Composite identifier" in page)

I had already replied on your question on the Hibernate forums, but to complete my suggestion:
An alternative to changing your mapping is that you add add a #DocumentId on a new getter, and return any object - maybe even a string - which is a unique composite of the two ids components.
(This requires defining mapping on getters and setters however)
When using JPA you can avoid specifying the #DocumentId but you don't have to, you can still use the annotation to override the definition of identity which you want to apply on the index mapping.

Related

Returning one of multiple class types from a data class

I have scenario where in I have a "Lookup Table" class that holds getters and setters for multiple class types. As I'm interfacing with a database, I need to provide a way to provide a result boolean and then the class instance which was requested.
For example. Say I have an AssetStatus, StockItemStatus and NominalCode class. I would have to write the following data class for each:
data class LookupResult(
val wasSuccessful: Boolean = false,
val resultClass: AssetStatus? = null,
)
// or
data class LookupResult(
val wasSuccessful: Boolean = false,
val resultClass: StockItemStatus? = null,
)
// or
data class LookupResult(
val wasSuccessful: Boolean = false,
val resultClass: NominalCode? = null,
)
Ideally I don't want to have to repeat myself so I was wondering if I could write one data class (or normal class?) which is able to return one of my multiple Lookup classes?
Initially I thought it would have needed to be Any but after looking into this, that might not be the best case for what I want.
So is there a way of sticking to writing once but not repeating? Or is it something I have to do?
Edit:-
All of my class types would have the following structure (note: I'm using Spring Boot as back end) :
#Entity
#Table(name = "lookup_asset_status")
data class AssetStatus(
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "asset_status_id")
val id: Long? = null,
#Column(name = "asset_status_name")
val name: String = "",
)
...
// Repeat for each entity type
...
If I understand correctly, you want something like this:
data class LookupResult<T>(
val wasSuccessful: Boolean = false,
val resultClass: T? = null,
)
Each of the classes would be written as LookupResult<AssetStatus>, LookupResult<StockItemStatus> and LookupResult<NominalCode>.
If your method needs to be able to return any of those three classes, then it should be declared to return LookupResult<*>. Note that you can only access the members of Any when you access the resultClass of a LookupResult<*>, because you don't know which exact look up result it is.

JPA EntityGraph making a Cartesian Product with subgraph

I am working with Spring Data JPA and Entity Graphs.
I have the following Entity structure:
Result entity has a list of SingleQuestionResponse entities, and the SingleQuestionResponse entity has a set of Answer entities (markedAnswers).
public class Result {
...
#OneToMany(cascade = CascadeType.PERSIST)
#JoinColumn(name = "result_id", nullable = false)
private List<SingleQuestionResponse> responses;
...
}
public class SingleQuestionResponse {
...
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(
name = "singlequestionresponses_answers",
joinColumns = #JoinColumn(name = "single_question_response_id"),
inverseJoinColumns = #JoinColumn(name = "answer_id")
)
private Set<Answer> markedAnswers;
...
}
and Answer just has simple-type fields.
Now, I would like to be able to fetch Result, along with all responses, and the markedAnswers in one query. For that I annotated the Result class with:
#NamedEntityGraph(name = "graph.Result.responsesWithQuestionsAndAnswersEager",
attributeNodes = #NamedAttributeNode(value = "responses", subgraph = "responsesWithMarkedAnswersAndQuestion"),
subgraphs = {
#NamedSubgraph(name = "responsesWithMarkedAnswersAndQuestion", attributeNodes = {
#NamedAttributeNode("markedAnswers"),
#NamedAttributeNode("question")
})
}
)
an example of usage is:
#EntityGraph("graph.Result.responsesWithQuestionsAndAnswersEager")
List<Result> findResultsByResultSetId(Long resultSetId);
I noticed, that calling the findResultsByResultSetId method (and other methods using this entity graph) results in responses (SingleQuestionResponse entities) being multiplied by the number of markedAnswers. What I mean by that is that result.getResponses() returns more SingleQuestionResponse objects than it should (it returns one response object per each markedAnswer).
I realize this is due to Hibernate making a Cartesian product with the join, but I have no idea how to fix it.
Can you help please? Thanks
You have to use the DISTINCT operator. With Spring Data JPA, this can be done by naming the method findDistinctResultsByResultSetId

CriteriaBuilder.size() and Hibernate's #Where annotation

I have the following setup:
#Entity
public class Function {
private String name;
#OneToMany(mappedBy = "function", cascade = CascadeType.ALL, orphanRemoval = true)
#Where(clause = "type = 'In'") // <=== seems to cause problems for CriteriaBuilder::size
private Set<Parameter> inParameters = new HashSet<>();
#OneToMany(mappedBy = "function", cascade = CascadeType.ALL, orphanRemoval = true)
#Where(clause = "type = 'Out'") // <=== seems to cause problems for CriteriaBuilder::size
private Set<Parameter> outParameters = new HashSet<>();
}
#Entity
public class Parameter {
private String name;
#Enumerated(EnumType.STRING)
private ParameterType type;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "function_id")
private Function function;
}
The overall problem I am trying to solve is find all functions that have outParameters with an exact dynamic set of names. E.g. find all function with outParameters whose names are exactly ('outParam1', 'outParam2')
This seems to be an "exact relational division" problem in SQL, so there might be better solutions out there, but the way I've gone about doing it is like this:
List<String> paramNames = ...
Root<Function> func = criteria.from(Function.class);
Path outParams = func.get("outParameters");
Path paramName = func.join("outParameters").get("name");
...
// CriteriaBuilder Code
builder.and(
builder.or(paramNames.stream().map(name -> builder.like(builder.lower(paramName), builder.literal(name))).toArray(Predicate[]::new)),
builder.equal(builder.size(outParams), paramNames.size()));
The problem I get is that the builder.size() does not seem to take into account the #Where annotation. Because the "CriteriaBuilder code" is nested in a generic Specification that should work for any type of Entity, I am not able to simply add a query.where() clause.
The code works when a function has 0 input parameters, but it does not work when it has more. I have taken a look at the SQL that is generated and I can see that it's missing:
SELECT DISTINCT
function0_.id AS id1_37_,
function0_.name AS name4_37_,
FROM
functions function0_
LEFT OUTER JOIN parameters outparamet2_ ON function0_.id = outparamet2_.function_id
AND (outparamet2_.type = 'Out') -- <== where clause added here
WHERE (lower(outparamet2_.name)
LIKE lower(?)
OR lower(outparamet2_.name)
LIKE lower(?))
AND (
SELECT
count(outparamet4_.function_id)
FROM
parameters outparamet4_
WHERE
function0_.id = outparamet4_.function_id) = 2 -- <== where clause NOT added here
Any help appreciated (either with a different approach to the problem, or with a workaround to builder.size() not working).
The where annotation is in the function entity, in the subquery you have not used that entity so the operation is correct, try using the function entity as root of the subquery, or to implement the where manually.
For the next one, it would be recommended that you include the complete Criteria API code to be more precise in the answers.

Spring Data Jpa, select based on two column values

Good Morning,
I have the following table:
_____________________
Name Status Num
A Good 6
B Bad 6
C Bad 7
I want to select all rows where "Status = 'Good' AND Num = '6'" OR "Status = 'Bad' AND Num = '7'"
So I would select rows with Names A and C from the above reference data.
I am hoping to be able to pass in two equal sized lists (ordered in the way I desire the query to be constructed), but have been unable to figure this out. The standard queries (SelectXByStatusAndNum) query generates SQL using 'IN' statements, and returns all 3 rows in the above data instead of just two.
Any insight appreciated
I believe the best way is to use a #Query annotation in the repository:
#Entity
#Table(name = "table_name")
public class TableName {
#Id
#Basic(optional = false)
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID")
private Long id;
#Column(name = "name")
private String name;
#Column(name = "status")
private String status;
#Column(name = "num")
private Integer num;
/**
* getters/setters, etc
**/
public interface TableNameRepository extends CrudRepository<TableName, Long> {
#Query("select t from TableName t where (status = :status1 and num = :num1 or status = :status2 and num = :num2)")
List<TableName> findByStatusAndNumOrStatusAndNum(#Param("status1") String status1,
#Param("num1") Integer num1, #Param("status2") String status2, #Param("num2") Integer num2);
}
It's a way to get values for a given parameters. In case of collections as parameters there is no in-box case due to RDBMS concept. You just can write some java code based on the key-valued parameter and collect results:
public interface TableNameRepository extends CrudRepository<TableName, Long> {
List<TableName> findByStatusAndNumIn(String status, Collection<Integer> nums);
}
List<TableName> result = new ArrayList<>();
List<TableName> itemGood = findByStatusAndNumIn("Good", numsGood);
List<TableName> itemBad = findByStatusAndNumIn("Bad", numsBad);
result.addAll(itemGood);
result.addAll(itemBad);
Instead of equal size lists, I suggest creating an object with both status and num and provide a list of those - I called it CustomCriteria below. Since there is no straightforward way to handle this with standard spring data query methods I believe the best way is to do this with criteria builder in a custom repository that builds the list of OR's from a list of AND predicates based on the criteria entries in the provided list. For example:
public List<YourTable> findMatching(List<CustomCriteria> customCriteriaList) {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<YourTable> criteriaQuery = criteriaBuilder.createQuery(YourTable.class);
Root<YourTable> itemRoot = criteriaQuery.from(YourTable.class);
List<Predicate> predicates = new ArrayList<>(customCriteriaList.size());
for (CustomCriteria customCriteria : customCriteriaList) {
Predicate predicateForNum
= criteriaBuilder.equal(itemRoot.get("num"), customCriteria.getNum());
Predicate predicateForStatus
= criteriaBuilder.equal(itemRoot.get("status"), customCriteria.getStatus());
predicates.add(criteriaBuilder.and(predicateForNum, predicateForStatus));
}
Predicate finalPredicate = criteriaBuilder.or(predicates.toArray(new Predicate[predicates.size()]));
criteriaQuery.where(finalPredicate);
return entityManager.createQuery(criteriaQuery).getResultList();
}

autoincrement id is not reflecting in composite key using JPA

I have a below mapping
#Entity
#Table(name = "auctions")
public class Auction{
.
.
#OneToMany(cascade = CascadeType.ALL, mappedBy = "auction")
private List<AuctionParamValue> auctionParamValueList;
.
.
}
#Entity
#Table(name = "auction_param_values")
public class AuctionParamValue {
#EmbeddedId
protected AuctionParamValuePK auctionParamValuePK;
#JoinColumn(name = "auction_param_id", referencedColumnName = "auction_param_id",updatable=false,insertable=false)
#ManyToOne #MapsId("auctionParamId")
private AuctionParam auctionParam;
#JoinColumn(name = "auction_id", referencedColumnName = "auction_id",updatable=false,insertable=false)
#ManyToOne #MapsId("auctionId")
private Auction auction;
}
#Embeddable
public class AuctionParamValuePK {
#Id
#Basic(optional = false)
#Column(name = "auction_id")
#Nullable
private Long auctionId = null;
#Id
#Basic(optional = false)
#Column(name = "auction_param_id")
#Nullable
private Long auctionParamId = null;
}
#Entity
#Table(name = "auction_params")
public class AuctionParam {
#OneToMany(cascade = CascadeType.ALL, mappedBy = "auctionParam")
private List<AuctionTypeParam> auctionTypeParamList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "auctionParam")
private List<AuctionParamValue> auctionParamValueList;
}
}
When I try to persist auction (I am manually setting the auctionParamId and expecting the auctionId to be automaticlly set (may be the last inserted id) )
but I am getting below error, I am not sure why the auctionId in the query is going as 0 instead of latest id in the auction.(I am using eclipselink jpa provider)
Internal Exception: com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`portaldemo`.`auction_param_values`, CONSTRAINT `auction_param_values_auction_id_fk` FOREIGN KEY (`auction_id`) REFERENCES `auctions` (`auction_id`))
Error Code: 1452
Call: INSERT INTO auction_param_values (auction_param_val, create_ts, last_updt_ts, auction_param_id, auction_id) VALUES (?, ?, ?, ?, ?)
bind => [2011-02-12 04:00:00, 2011-01-27 12:02:00.28, 2011-01-27 12:17:43.25, 2, 0]
Query: InsertObjectQuery(com.eaportal.domain.AuctionParamValue[auctionParamValuePK=com.eaportal.domain.AuctionParamValuePK[auctionId=0, auctionParamId=2]])
Here the [auctionId=0 is always comming as 0 and not the last inserted id :(
What is theproblem with this mapping ?
An #GeneratedValue will only set the value of the attribute it is annotated on, if you have other attributes in other classes that reference the id you are responsible for setting these.
i.e. you would need to first persist and flush the Auction, and then create the AuctionParamValue using its generate Id.
Or, if you used TABLE or SEQUENCE id generation then you would just need to call persist, and not the flush. In general I would never recommend IDENTITY sequencing as its values cannot be preallocated.
But really you should not have the duplicate fields as all. Remove the #EmbeddedId auctionParamValuePK entirely and just add #Id to the two #ManyToOnes, and use an #IdClass instead. This will make things much simplier and will just work, even with IDENTITY id generation.
You could also instead remove the insertable/updateable=false on the two #ManyToOne mappings and instead put them on the #EmbeddedId attributes, this will have the foreign key written from the relationships, but your object will still be corrupt in memory.
See,
http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Primary_Keys_through_OneToOne_and_ManyToOne_Relationships
You could try two things:
make the two ids nullable: Use wrapper Types instead of primitives (Integer, Long), and set it to null before saving
leave the combinded Primary ID field (auctionParamValuePK) empty (null) when you save it.
I don't know if this fix the problem, but I am sure that you need to do at least one of them to get it working.