What I have in my hands are 4 deeply related entities.
The first one is Sickness defined as follows:
public class Sickness {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false)
#JsonView(Views.Superficial.class)
private Long id;
/*
* ...
*/
#OneToMany(fetch = FetchType.LAZY)
private List<Diagnostic> Diagnostic; // <---- The first problem :)
/*
*...
*/
Now the diagnostic for the sickness is defined as followed
#Entity
/*
* ...
*/
#Table(name = "Diagnostic")
public class Diagnostic{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#JsonView(Views.Superficial.class)
private Long id;
/*
*...
*/
#JsonIgnore
private String label;
#ManyToMany(fetch = FetchType.EAGER)
#JsonView(Views.Detailed.class)
private List<Question> questions; // <-- Second Problem !
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
private Sickness sickness;
The question Entity is defined like this :
#Entity
#NoArgsConstructor
#AllArgsConstructor
#Getter
#Builder
#Setter
#Table(name = "question")
public class Question {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", nullable = false)
#JsonView(Views.Superficial.class)
private Long id;
#Enumerated
#JsonView(Views.Superficial.class)
private TypeQuestion type;
#JsonView(Views.Superficial.class)
private String question_label;
#ManyToMany
#JsonView(Views.Superficial.class)
private List<Choice> choiceList; // <-- Third problem XD
And finally the Choice entity is defined as such :
#Entity
#AllArgsConstructor
#NoArgsConstructor
#Getter
#Setter
#Builder
#Table(name = "choice")
public class Choice {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#JsonView(Views.Superficial.class)
private Long id;
#JsonView(Views.Superficial.class)
private String label;
#OneToOne
#JsonView(Views.Detailed.class)
private Diagnostique diagnostique; // <-- :) ; did this because you could have multiple
// diacnostics for a sickness symtome
#OneToOne
#JsonView(Views.Superficial.class)
private Traitement traitement;
#JsonView(Views.Superficial.class)
private String noTreatementNoDiagnosticChoice;
}
The problem is probably the Choice entity since it calls the diagnostic entity recursively in one or two records.
I have manually injected data records, now it works for the case where I have a single nested diagnostic entity in the Choice object (Diagnostic -> Question -> Choice -> Diagnostic -> Question -> Choice -> Treatment)
But for the double nested case it throws that error (Diagnostic -> Question -> Choice -> Diagnostic -> Question -> Choice Diagnostic -> Question -> Choice -> Treatment ).
I really don't know what to do at this point, the data modeling of the case is not that great and I'm really too invested in this version of modeling to change it.
Can anyone help?
Here's some stack traces:
When I query the Sickness
org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: 4; nested exception is com.fasterxml.jackson.databind.JsonMappingException: 4\r\n\tat org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:465)\r\n\tat org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:104)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:290)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:219)\r\n\tat
When I query the diagnostic
org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: 4; nested exception is com.fasterxml.jackson.databind.JsonMappingException: 4 (through reference chain: com.nst.onercp.domain.Diagnostic$HibernateProxy$SlDHxnlx[\"questions\"])\r\n\tat org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:465)\r\n\tat org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:104)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:290)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:219)\r\n\tat org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:78)
Sorry for the long post :)
You should use DTOs pattern
https://en.wikipedia.org/wiki/Data_transfer_object
Try learning about Mapstruct it might help with this use case
https://mapstruct.org/
Solved with #JsonIgnoreProperties(value="diagnostique") and a dedicated api endpoint to get the diagnostic of a choice if present.
Related
I have this entity:
public class StatementLinesEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long statementLinesId;
#CreationTimestamp
#Temporal(TemporalType.DATE)
private Date dateOperation;
private String operationNature;
private BigDecimal amount;
private String debitAmount;
And this entity has Inheritance of type SINGLE_TABLE:
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class OperationCreditEntity {
#Id
#Column(nullable = false, updatable = false)
#GeneratedValue(strategy = GenerationType.AUTO)
private Long operationCreditId;
#CreatedDate
private Date operationDate;
#OneToOne
private StatementLinesEntity statementLine;
And these 3 enteties inherite of it :
#Entity
#DiscriminatorValue("Espece")
public class OperationEspecesEntity extends OperationCreditEntity {
private String cin;
private String nomEmetteur;
private String prenomEmetteur;
=============================
#DiscriminatorValue("Virement")
public class OperationVirementEntity extends OperationCreditEntity {
private String rib;
===========================
#Entity
#DiscriminatorValue("Cheque")
public class OperationChequeEntity extends OperationCreditEntity{
private int numeroCheque;
Let's suppose I have a List<StatementLinesEntity> consist of 2 lines, on line has debitAmount = C and operationNature = Virement and second line has debitAmount = C and operationNature = Espece. My goal is to persist each line in a specific DTYPE. example
first line should be persisted in OperationCreditEntity table DTYPE = Virement and the second should be persisted in OperationCreditEntity table DTYPE = Espece
The model to me should be more like:
#Entity
public class StatementLinesEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long statementLinesId;
#CreationTimestamp
#Temporal(TemporalType.DATE)
private Date dateOperation;
#OneToOne(mappedBy = "statementLine")
private OperationCreditEntity operation;
private BigDecimal amount;
private String debitAmount;
}
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
abstract public class OperationCreditEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long operationCreditId;
#CreatedDate
private Date operationDate;
#OneToOne
private StatementLinesEntity statementLine;
}
Any method then that takes in StatementLinesEntity instances can then take in one that references an OperationCreditEntity instance (which can be any one of its subclasses). There is no need to manage, parse or handle String operationNature strings directly, as the operation type will determine the operation nature.
This might change other signatures, serialization (such as JSON though), so if you can't use this and are 'stuck' with your existing StatementLinesEntity data representation YOU need to handle how to create your OperationCreditEntity instances from that data. There is no tool to automatically do it for you. It is as simple as a utility of the form:
OperationCreditEntity createOperationInstance(StatementLinesEntity statementLine) {
String operationNature = statementLine.getOperationNature();
OperationCreditEntity returnVal = null;
if "Espece".equals(operationNature) {
returnVal = new OperationEspecesEntity();
} else if "Virement".equals(operationNature) {
returnVal = new OperationVirementEntity();
} else if "Cheque".equals(operationNature) {
returnVal = new OperationChequeEntity();
} else {
throw new IllegalStateException();
}
returnVal.setStatementLine(statementLine);
return returnVal;
}
Just call save using your OperationCreditEntity repository when ever you call this method to get it put into the same transactional context you are making changes to. Also note, those OperationCreditEntity subclasses have data you will need to find a way to fill in on your own; I personally think this data will likely be tied to data available when defining/creating a StatementLinesEntity, so should be generated/created then, not after the fact, but that is up to you.
Added just to be complete:
Yes, you can access the column used to store discriminator values directly in a base entity class. Nothing stops or prevents you from mapping the column as you would any other database column. For Hibernate, it uses "DTYPE", so
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class OperationCreditEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long operationCreditId;
#CreatedDate
private Date operationDate;
#Column(name="DTYPE",insertable=false, updatable=false)
private String typeValue;
}
Notice I marked this as insertable/updatable=false though. It is provider specific if it complains about controlling this value in this way; many try to do so with the hope of changing it. Changing an entity 'type' is not supported. A Caterpillar does not become a Butterfly just by changing a string value. Any caches that hold OperationCreditEntity or some specific subclass type aren't magically going to have the object type changed; JPA requires you to delete the entity and create a new instance (of the proper class) for that data, preferably after flushing the delete operation.
Also note, you can query and use Entity Type Expressions (TYPE) without having a column or other mapping for it.
"Select line from OperationCreditEntity operation join operation.statementLine line where TYPE(operation) IN (OperationEspecesEntity, OperationChequeEntity) and line.somethingElse = :someValue"
I have 2 entities: Version and Change log.
A Version has N change Logs and a Change Log has one Version.
My Version entity looks like:
#Table(name="change_log_version")
#Entity
public class ChangeLogVersionEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name="version")
private String version;
#Column(name="date")
private LocalDateTime date;
#OneToMany(mappedBy = "version", cascade=CascadeType.ALL, fetch =
FetchType.EAGER)
public List<ChangeLogEntity> changeLogEntities;
public void addChangeLog(ChangeLogEntity changeLogEntity) {
this.changeLogEntities.add(changeLogEntity);
changeLogEntity.setVersion(this);
}
...
}
My Change Log entity looks like:
#Table(name="change_log")
#Entity
public class ChangeLogEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name="description")
private String description;
#Column(name="added")
private boolean isAdded;
#Column(name="modified")
private boolean isModified;
#Column(name="deleted")
private boolean isDeleted;
#Column(name="public")
private boolean isPublic;
#Column(name="date")
private LocalDateTime date;
#ManyToOne(cascade=CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "version_id")
private ChangeLogVersionEntity version;
...
}
I am kinda new to hibernate and i am stuck in a null pointer by adding a change log to the version. What do i have to change to archive the relation?
Many thanks in advance so far :)
That's because the changeLogEntites List is not initialized.
You should initialize it in the declaration
#OneToMany(mappedBy = "version", cascade=CascadeType.ALL, fetch = FetchType.EAGER)
public List<ChangeLogEntity> changeLogEntities = new ArrayList<>();
OneToMany relationship causing infinite loop using Spring Data JPA with hibernate as provider
The problem here is not the type of exception but the infinite loop that causes this exception
I tried #JsonIgnoreProperties which gives me another error => 'Could not write JSON: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer'
The post referencing the solution does not have a solution that adresses my problem.
One says use #JsonManagedReference and #JsonBackReference that does stop the recursion but excludes the object (UserGroup in 'myUser' entity) from the result which I need when I want an object of 'myUser' entity.
The other one says about overriding ToString method which I don't do.
Another one explains why there is an infinite loop and suggest as solution to not do that way. I quote "Try to create DTO or Value Object (simple POJO) without cycles from returned model and then return it."
And this one Difference between #JsonIgnore and #JsonBackReference, #JsonManagedReference explains the difference but doing so I will have the same problem as the first one
'myUser' entity
#Entity
public class MyUser {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
private String email;
private Integer age;
//#JsonIgnoreProperties({"myUsers"})
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "userGroupId")
private UserGroup userGroup;
'UserGroup' entity
#Entity
public class UserGroup {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Integer groupOrder;
#OneToMany
(
mappedBy = "userGroup",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<MyUser> myUsers;
change the getUserGroup() method in your MyUser class as follows.
#Entity
public class MyUser
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
private String email;
private Integer age;
//#JsonIgnoreProperties({"myUsers"})
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "userGroupId")
private UserGroup userGroup;
public UserGroup getUserGroup()
{
userGroup.setMyUsers(null);
return userGroup;
}
}
you need to add #JsonIgnore annotation at #OneToMany
like this
#JsonIgnore
#OneToMany
(
mappedBy = "userGroup",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<MyUser> myUsers;
I think I'm getting the point of your problem. You want to fetch MyUser including the userGroup data without the circular reference.
Based from the solutions you enumerated, I suggest you should still use the #JsonBackReference and #JsonManagedReference to prevent recursion on your entities and for the solution on your problem, you can try to use a mapper (MapStruck) and map the userGroup details to a DTO during the retrieval of data from the service.
DTOs:
public class MyUserDto {
private Long id;
private String firstName;
private String lastName;
private String email;
private Integer age;
private UserGroupDto userGroupDto;
}
public class UserGroupDto {
private Long id;
private Integer groupOrder;
}
Mapper (MapStruck):
#Mapper(componentModel = "spring")
public interface MyUserMapper {
MyUserMapper INSTANCE = Mappers.getMapper(MyUserMapper.class);
UserGroupDto userGroupToDto(UserGroup userGroup);
#Mapping(source = "myUser.userGroup", target = "userGroupDto")
MyUserDto myUserToDto(MyUser myUser);
}
After retrieving the data from your repository, you may then call the myUserToDto method to map the entity to a DTO.
This is just one way of solving your problem.
I have One-To-Many relationship, here is my code
#Entity
#Table(name = "catalog")
public class Catalog {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "catalog_id")
private int catalog_id;
#NotEmpty
#Size(min = 3, max = 255)
#Column(name = "name", nullable = false)
private String name;
#OneToMany(mappedBy="mycatalogorder")
private List<Order> orders;
#OneToMany(mappedBy="mycatalog")
private List<CatalogItem> items;
// setters and getters
}
#Entity
#Table(name = "catalogitem")
public class CatalogItem {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "catalogitem_id")
private int catalogitem_id;
#NotEmpty
#Size(min = 3, max = 255)
#Column(name = "name", nullable = false)
private String name;
#NotEmpty
#Column(name = "price", nullable = false)
private Double price;
#OneToOne(mappedBy="ordercatalogitem", cascade=CascadeType.ALL)
private OrderItem morderitem;
#ManyToOne
#JoinColumn(name="catalog_id", nullable=false)
private Catalog mycatalog;
// setters and getters
}
#Entity
#Table(name = "orders")
public class Order {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "order_id")
private int order_id;
#NotEmpty
#Size(min = 3, max = 255)
#Column(name = "name", nullable = false)
private String name;
#NotEmpty
#Size(min = 3, max = 1024)
#Column(name = "note", nullable = false)
private String note;
#Temporal(TemporalType.TIMESTAMP)
#DateTimeFormat(pattern = "ddmmYYYY HH:mm:ss")
#Column(name = "created", nullable = false)
private Date created;
#OneToMany(mappedBy="myorder")
private Set<OrderItem> orderItems;
#ManyToOne
#JoinColumn(name="catalog_id", nullable=false)
private Catalog mycatalogorder;
#PrePersist
protected void onCreate() {
created = new Date();
}
// setters and getters
}
#Entity
#Table(name = "orderitem")
public class OrderItem {
#Id
#Column(name="catalogitem_id", unique=true, nullable=false)
#GeneratedValue(generator="gen")
#GenericGenerator(name="gen", strategy="foreign", parameters=#Parameter(name="property", value="catalogitem"))
private int catalogitem_id;
#Column(name = "quantity")
private int quantity;
#OneToOne
#PrimaryKeyJoinColumn
private CatalogItem ordercatalogitem;
#ManyToOne
#JoinColumn(name="order_id", nullable=false)
private Order myorder;
// setters and getters
}
And I am getting the exception:
org.springframework.http.converter.HttpMessageNotWritableException:
Could not write content: failed to lazily initialize a collection of
role: com.example.helios.model.Catalog.items, could not initialize
proxy - no Session; nested exception is
com.fasterxml.jackson.databind.JsonMappingException: failed to lazily
initialize a collection of role:
com.example.helios.model.Catalog.items, could not initialize proxy -
no Session
org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:271)
org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:100)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:222)
org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:183)
org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:80)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:126)
My versions is:
SpringFramework 4.2.4.RELEASE
Hibernate 4.3.11.Final
Jackson 2.7.4
Jacksontype 2.7.1
This is the normal Hibernate behaviour
In one to many relations, hibernate loads the father entity (Catalog in your case) but it will load the children entities List (List items and List orders in your case) in a LAZY mode
This means you can't access to these objects because they are just proxies and not real objects
This is usefull in order to avoid to load the full DB when you execute a query
You have 2 solution:
Load children entities in EAGER mode (I strongly suggest to you to not do it because you can load the full DB.... but it is something related to your scenario
You don't serialize in your JSON the children entities by using the com.fasterxml.jackson.annotation.JsonIgnore property
Angelo
A third option which can be useful if you don't want to use EAGER mode and load up everything is to use Hibernate::initialize and only load what you need.
Session session = sessionFactory.openSession();
Catalog catalog = (Catalog) session.load(Catalog.class, catalogId);
Hibernate.initialize(shelf);
More information
I had the same problem but a fixed by:
#OneToMany
#JoinColumn(name = "assigned_ingredient", referencedColumnName = "ingredient_id")
#Fetch(FetchMode.JOIN) // Changing the fetch profile you can solve the problem
#Where(clause = "active_ind = 'Y'")
#OrderBy(clause = "meal_id ASC")
private List<Well> ingredients;
you can have more information here: https://vladmihalcea.com/the-best-way-to-handle-the-lazyinitializationexception/
It's caused by an infinite loop when parsing datas to JSON.
You can solve this by using #JsonManagedReference and #JsonBackReference annotations.
Definitions from API :
JsonManagedReference (https://fasterxml.github.io/jackson-annotations/javadoc/2.5/com/fasterxml/jackson/annotation/JsonManagedReference.html) :
Annotation used to indicate that annotated property is part of two-way
linkage between fields; and that its role is "parent" (or "forward")
link. Value type (class) of property must have a single compatible
property annotated with JsonBackReference. Linkage is handled such
that the property annotated with this annotation is handled normally
(serialized normally, no special handling for deserialization); it is
the matching back reference that requires special handling
JsonBackReference: (https://fasterxml.github.io/jackson-annotations/javadoc/2.5/com/fasterxml/jackson/annotation/JsonBackReference.html):
Annotation used to indicate that associated property is part of
two-way linkage between fields; and that its role is "child" (or
"back") link. Value type of the property must be a bean: it can not be
a Collection, Map, Array or enumeration. Linkage is handled such that
the property annotated with this annotation is not serialized; and
during deserialization, its value is set to instance that has the
"managed" (forward) link.
Example:
Owner.java:
#JsonManagedReference
#OneToMany(mappedBy = "owner", fetch = FetchType.EAGER)
Set<Car> cars;
Car.java:
#JsonBackReference
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "owner_id")
private Owner owner;
Another solution is to use #JsonIgnore which will just set null to the field.
Here is my solution for this task with Hibernate. I marked hibernate releation with #JsonIgnore and use custom field for jackson, in which I check if the field is loaded. If you need serialize collection to json then you should manualy call collection getter during hibernate transaciton.
#JsonIgnore
#OneToMany(mappedBy = "myorder")
private List<OrderItem> orderItems = new ArrayList<>();
#JsonProperty(value = "order_items", access = JsonProperty.Access.READ_ONLY)
private List<OrderItem> getOrderItemsList() {
if(Hibernate.isInitialized(this.relatedDictionary)){
return this.relatedDictionary;
} else{
return new ArrayList<>();
}
}
#JsonProperty(value = "order_items", access = JsonProperty.Access.WRITE_ONLY)
private void setOrderItemsList(List<OrderItem> orderItems) {
this.orderItems = orderItems;
}
I know this is an old post but this might still help someone facing a similar issue. To solve the problem, iterate through the list of items and set the lazy-loadable collection to null. Then set your mapper to include NON-NULL
for (Catalog c : allCatalogs) {
c.setItems(null);
}
objectMapper.setSerializationInclusion(Include.NON_NULL)
Using FetchType.LAZY , if still getting the error "Could not write content: failed to lazily initialize a collection of role" , that may be probably caused by somewhere in the logic (perhaps in a controller) , Catalog is being tried to be deserialized that contains list of catalog items which is a proxy but the transaction has already ended to get that.
So create a new model ('CatalogResource' similar to catalog but without the list of items).
Then create a catalogResource object out of the Catalog (which is returned from the query)
public class CatalogResource {
private int catalog_id;
private String name;
private List<Order> orders;
}
I think the best solution to your problem (which also is the simplest) is to set your FetchType to LAZY and simply annotate the oneToMany collection fields using #transient.
Setting FetchType to EAGER isn't a good idea most times.
Best of luck.
"You don't serialize in your JSON the children entities by using the com.fasterxml.jackson.annotation.JsonIgnore property"
Add #JsonIgnore for hibernate lazy loading properties eg. #ManyToOne. That should work
#Entity
public class Group{
#Id
#GeneratedValue
private Long id;
#ManyToOne
private Group parent;
#LazyCollection(value=LazyCollectionOption.FALSE)
#OneToMany(mappedBy = "parent")
#Cascade(value = {CascadeType.ALL})
private Set<Group> children = new HashSet<Group>();
}
How do I JSON that structure? Json goes to infinite recursion .. Im using Jackson.
I need to have parent ID in my json output also .
set a #JsonBackReference on the #ManyToOne property and a #JsonManagedReference on the #OneToMany property
#Entity
public class Group{
#Id
#GeneratedValue
private Long id;
#JsonBackReference
#ManyToOne
private Group parent;
#JsonManagedReference
#LazyCollection(value=LazyCollectionOption.FALSE)
#OneToMany(mappedBy = "parent")
#Cascade(value = {CascadeType.ALL})
private Set<Group> children = new HashSet<Group>();
}
If the Competency entity points to a Group, then you might indeed go into infinite recursion. You can put a #JsonIgnore annotation on the parent and children instance variables to ignore them from being included in the JSON, or you can use a combination of #JsonBackReference/#JsonManagedReference, as the other poster suggested.
Other thing you can do is create a pojo which contains all the properties you are interested in in your service layer, cutting the hibernate connections out of the picture. Something like that:
public class GroupDto {
private Long id;
private CompetencyDto parent;
private List<CompetencyDto> children;
}
public class CompetencyDto {
private Long id;
}
This, while seeming like overwork, would give you the power your presentation model to not be dependent on your domain model. This would give you much more flexibility when constructing your views:
http://codebetter.com/jpboodhoo/2007/09/27/screen-bound-dto-s/
http://martinfowler.com/eaaDev/PresentationModel.html