DOM4J createQuery not eagerly fetching - dom4j

I have an entity which contains a OneToMany relationship, with eager fetching, with a second entity. This second entity has two OneToOne relationships, with eager fetching also, to a third and fourth class. The OneToOne relationships are unidirectional.
I am calling createQuery() from a DOM4J session sending in "from entity" as the HQL. In the return I get the second entity but it contains only the IDs of the third and fourth entities instead of the complete contents. To me it looks like those third and fourth entities are not being eagerly fetched. I can't reproduce the code exactly but here is the most relevant parts.
#Entity
public class Event extends EventParent {
#OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
#JoinColumn(name="eventId")
#org.hibernate.annotations.Cascade(value=org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
private Set<Pair> pairs=new HashSet<MarPair>();
}
#Entity
public class Pair extends PairParent {
#OneToOne(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
#org.hibernate.annotations.Cascade(value=org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
private Info info;
#OneToOne(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
#org.hibernate.annotations.Cascade(value=org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
private Results results;
}
#Entity
public class Info {
private String name;
private Date time;
}
#Entity
public class Results {
private String name;
private Date time;
}
Finally here is the code I am using for the query:
public void retrieve() {
String hqlQry = "from Event";
Session session = dom4JSessionFactory.getCurrentSession();
Session dom4jSession = session.getSession(EntityMode.DOM4J);
List results = dom4jSession.createQUery(hqlQuery).list();
}
As I mentioned, from this query I am getting back an integer for the value of info and results which is the key to the info and results table instead of the actual data being retrieved from the info and results table.
Relevant Information:
Spring 2.5.4
Hibernate 3.2.6
Hibernate Annotations 3.3.1.GA
dom4JSessionFactory is of type org.springframework.orm.hibernate3.LocalSessionFactoryBean
The entity "Event" is actually the 7th class down in a class hierarchy (don't know if this matters or not)
I did leave out a lot of information hoping that it was not necessary. If there is something else you would need to venture a guess as to why it isn't working, please let me know.

Turns out this is a bug with the Hibernate version we are using. What I had to do was to change embed-xml to true after Hibernate generated the HBM files. This was done using the "replace" ant function.

Related

LazyInitializationException when returning JSON in REST Webservice in Quarkus

I'm trying to build a simple application with Quarkus. Currently, I have two entity classes, which are related one-to-many:
#Entity
public class Person extends PanacheEntity {
public String name;
public LocalDate birthdate;
#OneToMany(mappedBy = "person")
public List<Address> addresses;
public static Person findByNameFirst(String name) {
return find("name", name).firstResult();
}
}
#Entity
public class Address extends PanacheEntity {
public String street;
...etc...
#ManyToOne
public Person person;
}
These are used by a simple REST webservice, which should store a Person to the database, select it again an return it:
#GET
#Path("storePerson")
#Produces(MediaType.APPLICATION_JSON)
#Transactional
public Person storePerson(
#QueryParam("name")String name,
#QueryParam("birthdate")String birthdate)
{
LocalDate birth = LocalDate.parse(birthdate, DateTimeFormatter.BASIC_ISO_DATE);
Person person = new Person(name, birth);
person.persistAndFlush();
Person p2 = Person.findByNameFirst(name);
return p2;
}
When calling the webservice the first time, the result is a JSON object with the stored data, which is as expected. When called again, an internal server error is thrown:
org.hibernate.LazyInitializationException: Unable to perform requested lazy initialization [Person.addresses] - no session and settings disallow loading outside the Session
As I understand, the error is thrown because the transaction only lasts until the storePerson method ends, but the conversion to JSON is happening outside of the method.
How can I prevent this error? I have read about the hibernate parameter "enable_lazy_load_no_trans" but it seems it is not supported in Quakus' application.properties.
The idea is to use a mapper framework such as MapStruct.
We don't recommend to directly expose your entities for 2 reasons:
the issue you have,
API management in the long run: you might have to change your model and not your API or the opposite.
There is an example here: https://github.com/mapstruct/mapstruct-examples/tree/master/mapstruct-quarkus .
The Quarkus version used is a bit old but AFAICS it should still work with latest Quarkus.
You can make the error go away by using Hibernate.initialize(person.addresses), then the collection gets initialized before the transaction ends.

Cascading not working in oneToMany, with eclipseLink

I am working with EclipseLink and JPA 2.0.
Those are my 2 entities:
Feeder entity:
#Entity
#Table(name = "t_feeder")
public class Feeder implements Serializable {
private static final long serialVersionUID = 1L;
//Staff
#OneToMany(cascade = CascadeType.ALL, mappedBy = "idAttachedFeederFk")
private Collection<Port> portCollection;
//staff
}
Port entity:
#Entity
#Table(name = "t_port")
public class Port implements Serializable {
//staff
#JoinColumn(name = "id_attached_feeder_fk", referencedColumnName = "id")
#ManyToOne
private Feeder idAttachedFeederFk;
//staff
}
And this is my code:
Feeder f = new Feeder();
//staff
Port p = new Port();
p.setFeeder(f);
save(feeder); //This is the function that calls finally persist.
The probleme is that, only feeder is persisted and not the port. Am I missing something? And specially, in which side should I mention the cascading exactly. Given that in my database, the port table is referencing the feeder one with a foreign key.
EDIT
This simple piece of code worked fine with me:
public static void main(String[] args) {
Address a1 = new Address();
a1.setAddress("madinah 0");
Employee e1 = new Employee();
e1.setName("houssem 0");
e1.setAddressFk(a1);
saveEmplyee(e1);
}
I am not sure why you would expect it to work: you are attempting to save a new instance of Feeder which has no connection whatsoever to the newly created Port.
By adding the Cascade to the #OneToMany and calling save(feeder) Eclipse link would if there were an association:
Insert the record for the Feeder.
Iterate the Port collection and insert the relevant records.
As I have noted however, this new Feeder instance has no Ports associated with it.
With regard to your simple example I assume when you say it works that both the new Address and Employee have been written to the database. This is expected because you have told the Employee about the Address (e1.setAddressFk(a1);) and saved the Employee. Given the presence of the relevant Cascade option then both entities should be written to the database as expected.
Given this it should then be obvious that calling save(port) would work if the necessary cascade option was added to the #ManyToOne side of the relationship.
However if you want to call save(feeder) then you need to fix the data model. Essentially you should always ensure that any in-memory data model is correct at any given point in time, viz. if the first condition below is true then it follows that the second condition must be true.
Port p = new Port();
Feeder feeder = new Feeder();
p.setFeeder(f();
if(p.getFeeder().equals(f){
//true
}
if(f.isAssociatedWithPort(p)){
//bad --> returns false
}
This is obviously best practice anyway but ensuring the correctnes of your in-memory model should mean you do not experience the type of issue you are seeing in a JPA environment.
To ensure the correctness of the in-memory data model you should encapsulate the set/add operations.

Spring Data Rest Ambiguous Association Exception

The newly added LinkCollectingAssociationHandler is throwing a MappingException due to an ambiguous association in my domain class.
The links array looks like this:
[<http://localhost:8080/rooms/2/roomGroups>;rel="roomGroups", <http://localhost:8080/rooms/2/userGroup>;rel="userGroup", <http://localhost:8080/rooms/2/room>;rel="room", <http://localhost:8080/rooms/2/originatingConferences>;rel="originatingConferences", <http://localhost:8080/rooms/2/user>;rel="user"]
And it is trying to add another 'room' relation when it throws the exception.
The issue is that it seems to be adding links to relations which I have explicitly marked with #RestResource(exported = false)
Here is an example of a relation which I believe is causing this issue:
#JsonIgnore
#RestResource(exported = false)
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.room", cascade = {CascadeType.REMOVE})
private Set<RoomsByUserAccessView> usersThatCanDisplay = new HashSet<>();
The type RoomsByUserAccessView has an embedded id made up of a Room and a User.
I have also annotated the embedded id property with:
#JsonIgnore
#RestResource(exported = false)
private RoomsByUserAccessViewId pk = new RoomsByUserAccessViewId();
and its properties like this:
#JsonIgnore
#RestResource(exported = false)
private Room room;
#JsonIgnore
#RestResource(exported = false)
private User userWithAccess;
public RoomsByUserAccessViewId() {
//
}
How can I get it to ignore these relations properly when serializing to JSON?
My code was working prior to DATAREST-262 (https://github.com/spring-projects/spring-data-rest/commit/1d53e84cae3d09b09c4b5a9a4caf438701527550)
The full error message returned when I try to visit the rooms/ endpoint is as follows:
{
timestamp: "2014-03-17T13:38:05.481-0500"
error: "Internal Server Error"
status: 500
exception: "org.springframework.http.converter.HttpMessageNotWritableException"
message: "Could not write JSON: Detected multiple association links with same relation type! Disambiguate association #com.fasterxml.jackson.annotation.JsonIgnore(value=true) #javax.persistence.ManyToOne(fetch=EAGER, cascade=[], optional=true, targetEntity=void) #org.springframework.data.rest.core.annotation.RestResource(description=#org.springframework.data.rest.core.annotation.Description(value=), path=, exported=false, rel=) private com.renovo.schedulerapi.domain.Room com.renovo.schedulerapi.domain.RoomsByUserAccessViewId.room using #RestResource! (through reference chain: org.springframework.hateoas.PagedResources["content"]->java.util.UnmodifiableCollection[0]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Detected multiple association links with same relation type! Disambiguate association #com.fasterxml.jackson.annotation.JsonIgnore(value=true) #javax.persistence.ManyToOne(fetch=EAGER, cascade=[], optional=true, targetEntity=void) #org.springframework.data.rest.core.annotation.RestResource(description=#org.springframework.data.rest.core.annotation.Description(value=), path=, exported=false, rel=) private com.renovo.schedulerapi.domain.Room com.renovo.schedulerapi.domain.RoomsByUserAccessViewId.room using #RestResource! (through reference chain: org.springframework.hateoas.PagedResources["content"]->java.util.UnmodifiableCollection[0])"
}
I had a very similar problem . When adding a bidirectional relationship between two entities
I got an exception ""Could not write JSON: Detected multiple association links with same
relation type!" , While trying some solutions that i found here
(#JsonIgnore, #JsonIdentity, #RestResource, I also tried to do what Oliver offered
)
(The relation was properly defined with #JsonManagedReference and #JsonBackReference)
Nothing helped.
At the end i managed to understand that spring data rest is trying to
figure out if the related entity is linkable ( while trying to build the json of the
requested entity )
(LinkCollectingAssociationHandler : doWithAssociation -> isLinkableAssociation)
, For doing that he is looking for a repository that deals with the
related entity. After adding a repository for the related entity.. works like a charm..
(I suppose that after adding a repo a mapping RepositoryAwareResourceInformation is being
created for this entity (that is what I saw at debug).
I had this issue, and solved it as Ron suggests, but I thought I would expound a little. I didn't fully understand the first couple times I read Ron's answer...
#NodeEntity
public class Player extends Entity
#NodeEntity
public class PlayerTrade extends Entity
#NodeEntity
public class Trade extends Entity
I had repositories for Player and Trade, but none for PlayerTrade:
#RepositoryRestResource
public interface PlayerRepository extends GraphRepository<Player> {
#RepositoryRestResource
public interface TradeRepository extends GraphRepository<Trade> {
As soon as I added the last repo it worked.
#RepositoryRestResource
public interface PlayerTradeRepository extends GraphRepository<PlayerTrade>
I tried using #RestResource with rel or excluded, but couldn't get it dialed in. Does this mean that every entity in our JSON graph must have a repository?

"org.hibernate.ObjectNotFoundException: No row with the given identifier exists" but it does exists

I'm using hibernate for my web service.
I'm able to list all the records, but unable to get just one.
The table contains:
ID (VARCHAR) VALUE(BIT)
celiac 1
rate 1
suggestions 0
The error shown is:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.pfc.restaurante.models.Device#id="xxxxxx"]
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
And the main code:
#JsonAutoDetect
#Entity
#Table(name = "SETTINGS")
public class Settings implements Serializable{
#Id
#Column(name="ID")
private String id;
#Column(name="VALUE", nullable=false)
private boolean value;
(...)
}
//////////////////7
#Controller
#RequestMapping("/settingsService")
public class SettingsServiceController {
#Autowired
SettingsService settingsService;
#RequestMapping(value = "/{id}", method = RequestMethod.GET)
public #ResponseBody Settings find(#PathVariable("id") String id){
return settingsService.find(id);
}
(...)
}
I've read around that it could be because DB incongruence with my entity (some nullable = true when it shouldn't), but I've checked it already and there is no such a thing.
Could someone lend me a hand?
Thanks in advance!
Your error refers to an entity named 'Device' but your code shows an entity 'Settings'. Are they the same?
I've seen this error only in 2 situations:
The main entity does not exist in the DB and Session.load() is used. Use Session.get() and check for null instead.
Broken relationships. Consider this: EntityA owns a relation to EntityB. EntityB is deleted while the FK in EntityA is left untouched. So, whenever HB tries to load the link A-B the error happens. This can happen when running a normal search or even when saving/refreshing EntityA (HB needs to refresh the link as well).

Persisting a Many-to-Many entity by adding to a List of entities

I am getting a list of entities and attempting to add more values to it and have them persist to the data base... I am running into some issues doing this... Here is what I have so far...
Provider prov = emf.find(Provider.class, new Long(ID));
This entity has a many to many relationship that I am trying to add to
List<Organization> orgList = new ArrayList<Organization>();
...
orgList = prov.getOrganizationList();
So I now have the list of entities associated with that entity.
I search for some entities to add and I place them in the orgList...
List<Organization> updatedListofOrgss = emf.createNamedQuery("getOrganizationByOrganizationIds").setParameter("organizationIds", AddThese).getResultList();
List<Organization> deleteListOfOrgs = emf.createNamedQuery("getOrganizationByOrganizationIds").setParameter("organizationIds", DeleteThese).getResultList();
orgList.addAll(updatedListofOrgss);
orgList.removeAll(deleteListOfOrgs);
As you can see I also have a list of delete nodes to remove.
I heard somewhere that you don't need to call persist on such an opperation and that JPA will persist automatically. Well, it doesn't seem to work that way. Can you persist this way, or will I have to go throught the link table entity, and add these values that way?
public class Provider implements Serializable {
#Id
#Column(name="RESOURCE_ID")
private long resourceId;
...
#ManyToMany(fetch=FetchType.EAGER)
#JoinTable(name="DIST_LIST_PERMISSION",
joinColumns=#JoinColumn(name="RESOURCE_ID"),
inverseJoinColumns=#JoinColumn(name="ORGANIZATION_ID"))
private List<Organization> organizationList;
...//getters and setters.
}
The link table that links together organizations and providers...
public class DistListPermission implements Serializable {
#Id
#Column(name="DIST_LIST_PERMISSION_ID")
private long distListPermissionId;
#Column(name="ORGANIZATION_ID")
private BigDecimal organizationId;
#Column(name="RESOURCE_ID")
private Long resourceId;
}
The problem is that you are missing a cascade specification on your #ManyToMany annotation. The default cascade type for #ManyToMany is no cascade types, so any changes to the collection are not persisted. You will also need to add an #ElementDependent annotation to ensure that any objects removed from the collection will be deleted from the database. So, you can change your Provider implementation as follows:
#ManyToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL)
#ElementDependent
#JoinTable(name="DIST_LIST_PERMISSION",
joinColumns=#JoinColumn(name="RESOURCE_ID"),
inverseJoinColumns=#JoinColumn(name="ORGANIZATION_ID"))
private List<Organization> organizationList;
Since your Provider class is managed, you should not need to merge the entity; the changes should take effect automatically when the transaction is committed.