How else to ensure the order of a #ManyToMany List? - jpa

Consider:
#Entity
public class M {
#ManyToMany
private List<E> es = new ArrayList<E>();
private E newE;
public M(E newE) {
this.newE = newE;
es.add(newE);
}
Cannot I assert(m.newE == m.getEs(0))?
I could only if after rebooting the app/PU is:
public List<E> getEs() {
final int indexOf = es.indexOf(newE);
if (indexOf != 0) {
es.remove(indexOf);
es.add(0, newE);
}
return Collections.unmodifiableList(es);
}
However this burdensome code is even inefficient as it forces loading the E entitities from the PU before they may actually be needed. Any alternative that works?

Cannot I assert(m.newE == m.getEs(0))?
No, if there are any objects in the #ManyToMany, newE will be added at the end of the list. Also, I believe the list will be lazy-loaded before the insert, so your concern about things being inefficient doesn't really apply.
If you're only concerned about the ordering of elements when loaded from the persistence unit, #OrderBy will do the trick.
#ManyToMany
#Orderby("someproperty ASC")
private List<E> es = new ArrayList<E>();
If you also want to maintain order at runtime while adding elements, you'll have to implement compareTo() or a separate Comparator, then use Collections.sort(), or use a naturally sorted collection like SortedSet.

JPA also provides an #OrderColumn if you want the order maintained.
See this link
Otherwise changes to the order of the elements of the list are not considered a persistent change.

Related

How to query for empty collection in hibernate search

We are using hibernate-search with ES back end. Parent class has multiple collection of different children objects. We can filter parents based on the value of the child as the collections are annotated with #IndexedEmbedded.
We want to be able to filter parents based on if the collection of children is empty or not. We have tried using #IndexedEmbedded(indexNullAs = "null"), and then filtering on queryBuilder.phrase().onField("parent.children").sentence("null").createQuery(), which has made no difference. Using the ES console we can show the parent, but when the collection is empty it isn't listed at all, leading us to believe it hasn't been indexed due to it being empty.
Another option would be to filter on parent.collection.field using a wildcard, however this would not be recommended by the hibernate search docs due to the performance.
If you upgrade to Hibernate Search 6, you will be able to use the exists predicate:
List<MyEntity> hits = Search.session(entityManager)
.search(MyEntity.class)
.where(f -> f.matchAll().except(f.exists().field(“parent.children”))
.fetchHits(20);
That would solve your problem, and then you can start worrying about performance in your specific case.
Still in Hibernate Search 6, if your tests show that performance of the first solution really is problematic, I would suggest using a custom bridge on children that indexes whether the collection is empty or not. Something like this:
#SuppressWarnings("rawtypes")
public class MyCollectionEmptyBridge implements ValueBridge<Collection, Boolean> {
#Override
public Boolean toIndexedValue(Collection value, ValueBridgeToIndexedValueContext context) {
return value == null || value.isEmpty();
}
}
public class MyParentEntity {
// ...
#GenericField(
name = "childrenAreEmpty",
valueBridge = #ValueBridgeRef(type = MyCollectionEmptyBridge.class),
// Apply the bridge directly to the collection and not to its elements
// See https://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/#_disabling_container_extraction
extraction = #ContainerExtraction(extract = ContainerExtract.NO)
)
private List<Child> children = new ArrayList<>();
}
List<MyEntity> hits = Search.session(entityManager)
.search(MyEntity.class)
.where(f -> f.match().field(“parent.childrenAreEmpty”).matching(true))
.fetchHits();
That second solution can be implemented with Hibernate Search 5 as well, though Hibernate Search 5's custom bridges are somewhat harder to work with.

mapStruct: map list to other list?

I have a list List<Payment> which I'd like to map to another list List<PaymentPlan>. These types look like this:
public class Payment {
#XmlElement(name = "Installment")
#JsonProperty("Installment")
private List<Installment> installments = new ArrayList<>();
#XmlElement(name = "OriginalAmount")
#JsonProperty("OriginalAmount")
private BigDecimal originalAmount;
//getters setters, more attributes
}
and....
public class PaymentPlan {
//(Installment in different package)
private List<Installment> installments;
#XmlElement(name = "OriginalAmount")
#JsonProperty("OriginalAmount")
private BigDecimal originalAmount;
//getters setters, more attributes
}
I expect that something like this is working...
#Mappings({
#Mapping(//other mappings...),
#Mapping(source = "payments", target = "paymentInformation.paymentPlans")
})
ResultResponse originalResponseToResultResponse(OrigResponse originalResponse);
...but I get:
Can't map property java.util.List<Payment> to java.util.List<PaymentPlan>.
Consider to declare/implement a mapping method java.util.List<PaymentPlan> map(java.util.List<Payment> value);
I don't know how to apply this information. First I though I need to declare some extra mapping (in the same mapper class) for the lists, so MapStruct knows how to map each field of the List types like this:
#Mappings({
#Mapping(source = "payment.originalAmount", target = "paymentInformation.paymentPlan.originalAmount")
})
List<PaymentPlan> paymentToPaymentPlan(List<Payment> payment);
...but I get error messages like
The type of parameter "payment" has no property named "originalAmount".
Obviously I do something completely wrong, since it sound like it does not even recognize the types of the List.
How can I basically map from one List to another similar List? Obviously I somehow need to combine different mapping strategies.
btw: I know how to do it with expression mapping, like...
#Mapping(target = "paymentPlans",expression="java(Helper.mapManually(payments))")
but I guess MapStruct can handle this by iself.
I presume you are using version 1.1.0.Final. Your extra mapping is correct, the only difference is that you need to define a mapping without the lists MapStruct will then use that to do the mapping (the example message is a bit misleading for collections).
PaymentPlan paymentToPaymentPlan(Payment payment);
You don't even need the #Mappings as they would be automatically mapped. You might also need to define methods for the Instalment (as they are in different packages).
If you switch to 1.2.0.CR2 then MapStruct can automatically generate the methods for you.

Generic way to initialize a JPA 2 lazy association

So, the question at hand is about initializing the lazy collections of an "unknown" entity, as long as these are known at least by name. This is part of a more wide effort of mine to build a generic DataTable -> RecordDetails miniframework in JSF + Primefaces.
So, the associations are usually lazy, and the only moment i need them loaded is when someone accesses one record of the many in the datatable in order to view/edit it. The issues here is that the controllers are generic, and for this I also use just one service class backing the whole LazyLoading for the datatable and loading/saving the record from the details section.
What I have with come so far is the following piece of code:
public <T> T loadWithDetails(T record, String... associationsToInitialize) {
final PersistenceUnitUtil pu = em.getEntityManagerFactory().getPersistenceUnitUtil();
record = (T) em.find(record.getClass(), pu.getIdentifier(record));
for (String association : associationsToInitialize) {
try {
if (!pu.isLoaded(record, association)) {
loadAssociation(record, association);
}
} catch (..... non significant) {
e.printStackTrace(); // Nothing else to do
}
}
return record;
}
private <T> void loadAssociation(T record, String associationName) throws IntrospectionException, InvocationTargetException, IllegalAccessException, NoSuchFieldException {
BeanInfo info = Introspector.getBeanInfo(record.getClass(), Object.class);
PropertyDescriptor[] props = info.getPropertyDescriptors();
for (PropertyDescriptor pd : props) {
if (pd.getName().equals(associationName)) {
Method getter = pd.getReadMethod();
((Collection) getter.invoke(record)).size();
}
}
throw new NoSuchFieldException(associationName);
}
And the question is, did anyone start any similar endeavor, or does anyone know of a more pleasant way to initialize collections in a JPA way (not Hibernate / Eclipselink specific) without involving reflection?
Another alternative I could think of is forcing all entities to implement some interface with
Object getId();
void loadAssociations();
but I don't like the idea of forcing my pojos to implement some interface just for this.
With the reflection solution you would suffer the N+1 effect detailed here: Solve Hibernate Lazy-Init issue with hibernate.enable_lazy_load_no_trans
You could use the OpenSessionInView instead, you will be affected by the N+1 but you will not need to use reflection. If you use this pattern your transaction will remain opened until the end of the transaction and all the LAZY relationships will be loaded without a problem.
For this pattern you will need to do a WebFilter that will open and close the transaction.

How to avoid anemic domain model with business logic in the form of rules

I am designing a system that has a simple Entity Framework backed domain object that has fields I need to update based on a series of rules - I want to implement these rules progressively (in an agile style) and as I am using EF I am sceptical about putting each rule into the domain object. However, I want to avoid writing "procedural code" and using anemic domain models. This all needs to be testable as well.
As an example, the object is:
class Employee {
private string Name;
private float Salary;
private float PensionPot;
private bool _pension;
private bool _eligibleForPension;
}
I need to build rules such as "if Salary is higher than 100,000 and _eligibleForPension is false then set _eligibleForPension as true" and "if _pension is true then set _eligibleForPension as true".
There are approximately 20 such rules and I am looking for advice whether they should be implemented in the Employee class or in something like an EmployeeRules class? My first thought was to create a separate class for each rule inheriting from "Rule" and then apply each rule to the Employee class, maybe using the Visitor pattern but I'd have to expose all the fields to the rules to do this so it feels wrong. Having each rule on the Employee class though doesn't feel quite right either. How would this be implemented?
The second concern is that the actual Employees are Entity Framework entities backed to the DB so I don't feel happy adding logic to these "Entities" - especially when I need to mock the objects for unit testing each rule. How could I mock them if they have the rules I'm testing on the same object?
I have been thinking of using AutoMapper to convert to a simpler domain object before applying rules but then need to manage the updates to the fields myself. Any advice on this too?
One approach is to make the rules inner classes of Employee. The benefit of this approach is that the fields can remain private. Also, the invocation of the rules can be enforced by the Employee class itself, ensuring that they are always invoked when needed:
class Employee
{
string id;
string name;
float salary;
float pensionPot;
bool pension;
bool eligibleForPension;
public void ChangeSalary(float salary)
{
this.salary = salary;
ApplyRules();
}
public void MakeEligibleForPension()
{
this.eligibleForPension = true;
ApplyRules(); // may or may not be needed
}
void ApplyRules()
{
rules.ForEach(rule => rule.Apply(this));
}
readonly static List<IEmployeeRule> rules;
static Employee()
{
rules = new List<IEmployeeRule>
{
new SalaryBasedPensionEligibilityRule()
};
}
interface IEmployeeRule
{
void Apply(Employee employee);
}
class SalaryBasedPensionEligibilityRule : IEmployeeRule
{
public void Apply(Employee employee)
{
if (employee.salary > 100000 && !employee.eligibleForPension)
{
employee.MakeEligibleForPension();
}
}
}
}
One problem here is that the Employee class has to contain all rule implementations. This isn't a major problem since the rules embody business logic associated with employee pensions and so they do belong together.
Business rules are usually an interesting topic. There may certainly be a difference between an aggregate / entity invariant and a business rule. Business rules may need external data and I wouldn't agree with a rule changing an aggregate / entity.
You should think specification pattern for rules. The rule should basically just return whether it was broken or not with possibly a description of sorts.
In your example SalaryBasedPensionEligibilityRule, as used by eulerfx, may need some PensionThreshold. This rule really does look more like a task since the rule really isn't checking any validity of the entity.
So I would suggest that rules are a decision mechanism and tasks are for changing the state.
That being said you probably want to ask the entity for advice here since you may not want to expose the state:
public class Employee
{
float salary;
bool eligibleForPension;
public bool QualifiesForPension(float pensionThreshold)
{
return salary > pensionThreshold && !eligibleForPension;
}
public void MakeEligibleForPension()
{
eligibleForPension = true;
}
}
This sticks with the command/query separation idea.
If you are building directly from your ORM objects and do not want to, or cannot, include all the behaviour then that is OK --- but it certainly would help :)

Wicket - Wrapped collection Model "transformation"

I have a domain object which has a collection of primitive values, which represent the primary keys of another domain object ("Person").
I have a Wicket component that takes IModel<List<Person>>, and allows you to view, remove, and add Persons to the list.
I would like to write a wrapper which implements IModel<List<Person>>, but which is backed by a PropertyModel<List<Long>> from the original domain object.
View-only is easy (Scala syntax for brevity):
class PersonModel(wrappedModel: IModel[List[Long]]) extends LoadableDetachableModel[List[Person]] {
#SpringBean dao: PersonDao =_
def load: List[Person] = {
// Returns a collection of Persons for each id
wrappedModel.getObject().map { id: Long =>
dao.getPerson(id)
}
}
}
But how might I write this to allow for adding and removing from the original List of Longs?
Or is a Model not the best place to do this translation?
Thanks!
You can do something like this:
class PersonModel extends Model<List<Person>> {
private transient List<Person> cache;
private IModel<List<String>> idModel;
public PersonModel( IModel<List<String>> idModel ) {
this.idModel = idModel;
}
public List<Person> getObject() {
if ( cache == null ) {
cache = convertIdsToPersons( idModel.getObject() );
return cache;
}
public void setObject( List<Person> ob ) {
cache = null;
idModel.setObject( convertPersonsToIds( ob ) );
}
}
This isn't very good code but it shows the general idea. One thing you need to consider is how this whole thing will be serialised between requests, you might be better off extending LoadableDetachableModel instead.
Another thing is the cache: it's there to avoid having to convert the list every time getObject() is called within a request. You may or may not need it in practice (depends on a lot of factors, including the speed of the conversion), but if you use it, it means that if something else is modifying the underlying collection, the changes may not be picked up by this model.
I'm not quite sure I understand your question and I don't understand the syntax of Scala.
But, to remove an entity from a list, you can provide a link that simply removes it using your dao. You must be using a repeater to populate your Person list so each repeater entry will have its own Model which can be passed to the deletion link.
Take a look at this Wicket example that uses a link with a repeater to select a contact. You just need to adapt it to delete your Person instead of selecting it.
As for modifying the original list of Longs, you can use the ListView.removeLink() method to get a link component that removes an entry from the backing list.