Hibernate association mappings - json

I have two classes: Event and User. Every 'event' is created by only one 'user', but a 'user' can create many 'events'. I created relationships like this:
#Entity
#Table(name="events")
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Event {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#NotBlank
private String name;
#NotBlank
#Type(type="text")
private String description;
private String event_type;
#NotNull
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
private LocalDateTime expected_start;
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
private LocalDateTime expected_end;
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
private LocalDateTime actual_start;
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
private LocalDateTime actual_end;
#NotBlank
private String environment;
private int executed_by;
#Temporal(TemporalType.TIMESTAMP)
#CreationTimestamp
private Date created_at;
#Temporal(TemporalType.TIMESTAMP)
#UpdateTimestamp
private Date updated_at;
#ManyToOne
#JoinColumn(name="created_by")
private User creator;
}
#Entity
#Table(name="users")
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "username")
#FieldMatch(first = "password", second = "repassword",message = "The password fields must match")
public class User{
#Id
#NotBlank
#Size(min=5,max=15)
#Column(name="username", unique=true)
private String username;
#NotBlank
private String first_name;
#NotBlank
private String last_name;
#NotBlank
private String password;
#NotBlank
#Transient
private String repassword;
#NotBlank
private String email;
#NotBlank
private String phone;
#Temporal(TemporalType.TIMESTAMP)
#CreationTimestamp
private Date created_at;
#Temporal(TemporalType.TIMESTAMP)
#UpdateTimestamp
private Date updated_at;
#OneToMany(mappedBy="creator")
private Collection<Event> events=new ArrayList<Event>();
}
DAO:
public List<Event> getEvents() {
Criteria criteria=getCurrentSession().createCriteria(Event.class);
return (List<Event>) criteria.list();
}
I am using jackson for converting to JSON. when make an ajax call for a particular event, it pull the user information along with it. that's OK as it is need for me. But it also pull's other events created by user because of #oneToMany in user class. How to overcome this

I guess that Jackson, while serializing, checks the events collection size and, since you are using openSessionInViewFilter, the collection gets fetched, so it puts it in the response. You can just #JsonIgnore the events field.
Design note:
I think that "Open session in view" is an anti-pattern. Any transaction management should be done a level below the view layer. In order to decouple view layer from the layers below you should be returning DTOs to the view layer instead of JPA entities. Unless you're doing some toy project, that's the investment you won't regret.
How I do it:
I use select new mechanism from JPA to write dedicated query
to make queries typesafe I use QueryDSL (but that's optional, you can try out an ordinary JPQL first)
queries return DTO objects that don't even need Jackson annotations as they represent what I want to get in the view.
This approach has additional advantage of being much faster than normal entity loading by JPA. Some prefer loading entities and then repackage them which saves effort required to write the query (which is minimal once you get it how it works) but then there is no performance benefit.

Related

spring data jpa native query

I am working on a mini banking app. I want to query the database in which all the transactions made so far are stored with three query parameters which are, user account,startDate and endDate. the database has a column for transactionDate which is of type Date. I want a situation in which if the user provide something like 2022-10-21 as start date and 2022-08-02 as the end date, and then provide his account number. The query should return a list of all the transactions made by that particular user using the user's account number by querying the transactionDate column to get the date for each transactions. That's a transaction between 2022-10-21 to 2022-08-02 for that user.
This is what I have tried so far but still getting this error
Caused by: org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.util.List com.elijah.onlinebankingapp.repository.transaction.TransactionTypeRepository.findByBankAccountAndTransactionDate(com.elijah.onlinebankingapp.model.account.BankAccount,java.util.Date,java.util.Date)! Reason: Validation failed for query for method public abstract java.util.List com.elijah.onlinebankingapp.repository.transaction.TransactionTypeRepository.findByBankAccountAndTransactionDate(com.elijah.onlinebankingapp.model.account.BankAccount,java.util.Date,java.util.Date)!; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List com.elijah.onlinebankingapp.repository.transaction.TransactionTypeRepository.findByBankAccountAndTransactionDate(com.elijah.onlinebankingapp.model.account.BankAccount,java.util.Date,java.util.Date)!
This is my TransactionType model class
#Entity
#NoArgsConstructor
#Data
public class TransactionType {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Date transactionDate;
private double amount;
private double currentBalance;
private String transactionType;
private String description;
private String depositorOrWithDrawalName;
#ManyToOne
#JoinColumn(name = "account_id")
private BankAccount bankAccount;
}
The BankAccount class
#Entity
#Data
#NoArgsConstructor
#Slf4j
public class BankAccount {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String accountType;
private String accountStatus;
private String accountNumber;
private double currentBalance;
private LocalDate createdDate;
#OneToOne
#JoinColumn(name = "customer_id")
private Customer customer;
}
my BankAccountStatement class
#Data
#NoArgsConstructor
public class BankAccountStatement {
private double id;
private String transactionDate;
private String transactionType;
private String description;
private double amount;
private double currentBalance;
private String depositorOrWithDrawalName;
}
BankAccountStatementDto
#Data
#NoArgsConstructor
public class BankAccountStatementDto {
private Date startDate;
private Date endDate;
}
my repository in which I did the query
#Repository
public interface TransactionTypeRepository extends JpaRepository<TransactionType,Long> {
#Query("select t from TransactionType t where t.bankAccount =:bankAccount, t.transactionDate <=:startDate AND t.transactionDate >=:endDate")
List<TransactionType> findByBankAccountAndTransactionDate(BankAccount bankAccount, #Param("startDate") Date startDate,#Param("endDate") Date endDate);
}
my service class
#Service
public class TransactionTypeService {
#Autowired
private TransactionTypeRepository transactionTypeRepository;
#Autowired
private BankAccountService bankAccountService;
public List<BankAccountStatement> getUserAccountStatement(BankAccountStatementDto bankAccountStatementDto, String accountNumber) throws DataNotFoundException {
BankAccount bankAccount = bankAccountService.getAccountByAccountNumber(accountNumber);
List<TransactionType> transactionTypeList = transactionTypeRepository.findByBankAccountAndTransactionDate(bankAccount,bankAccountStatementDto.getStartDate(),bankAccountStatementDto.getEndDate());
//the TransactionType has so many data and I don't need all the data in it
//I only want to retrieve the important information and store on this BankAccountStatement
List<BankAccountStatement> bankAccountStatementList = new ArrayList<>();
BankAccountStatement bankAccountStatement = new BankAccountStatement();
for (TransactionType transactionType: transactionTypeList){
bankAccountStatement.setId(transactionType.getId());
bankAccountStatement.setTransactionType(transactionType.getTransactionType());
bankAccountStatement.setTransactionDate(transactionType.getTransactionDate().toString());
bankAccountStatement.setDescription(transactionType.getDescription());
bankAccountStatement.setDepositorOrWithDrawalName(transactionType.getDepositorOrWithDrawalName());
bankAccountStatement.setCurrentBalance(transactionType.getCurrentBalance());
bankAccountStatement.setAmount(transactionType.getAmount());
bankAccountStatementList.add(bankAccountStatement);
}
return bankAccountStatementList;
}
}
my controller
#RestController
public class TransactionController {
#Autowired
private TransactionTypeService transactionTypeService;
#GetMapping("/account/statement/from/enteredDate")
public ResponseEntity<List<BankAccountStatement>> getCustomerAccountStatement(#RequestBody BankAccountStatementDto bankAccountStatementDto,#RequestParam("accountNumber")String accountNumber) throws DataNotFoundException {
return new ResponseEntity<>(transactionTypeService.getUserAccountStatement(bankAccountStatementDto,accountNumber),HttpStatus.OK);
}
}
The problem is with your transactionDate field. You have to let the hibernate know whether it holds only date, only time, or both. Assuming you are using java.util.Date, it contains both date and time upto milliseconds. #Temporal annotation in sprint boot will let know the hibernate about what data it holds.
In your case, you should add #Temporal(TemporalType.TIMESTAMP) for transactionDate field (assuming you are using java.util.Date).
You have other temporal types as well,
TemporalType.DATE - only date, TemporalType.TIME - only time
I have solved the issue, the problem was from my query, I was using a comma after the bankAccount instead of AND.
This is the final solution in case anyone has such a problem
#Query("select t from TransactionType t where t.bankAccount = :bankAccount AND t.transactionDate <= :startDate AND t.transactionDate >= :endDate")
List<TransactionType> findByBankAccountAndTransactionDate(BankAccount bankAccount, #Param("startDate") Date startDate,#Param("endDate") Date endDate);

Spring boot: How to Save data to specific DTYPE

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"

Spring Data JPA #OneToMany infinite loop exception

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.

JPA generate fails with JSON

I cound't find any solution to manage that fail, so I decided to create a new question. I have a simple class
#Entity
public class Reservation {
// private Integer RESERVATION_ID;
// private Integer id;
private long code;
private Date date;
private Client reservationClient;
private WashType reservationWashType;
private Vehicle reservationVehicle;
private Wash reservationWash;
private Worker reservationWorkerPesel;
private Review reservationReview;
private ReservationReminder reservationReminder;
}
Where I run a query like that:
#Query("SELECT r FROM Reservation r JOIN FETCH r.reservationReminder where r.reservationWorkerPesel = :worker")
List<Reservation> findByReservationWorkerPesel(#Param("worker") Worker worker);
And at first I everything looks nice, but then I do some operations like that:
public List<ReservationReminder> findByReservationWorkerPesel(Worker worker) {
List<ReservationReminder> reservationReminderList = new ArrayList<>();
List<Reservation> byReservationWorkerPesel = reservationDao.findByReservationWorkerPesel(worker);
for (Reservation r : byReservationWorkerPesel) {
if (r.getReservationReminder() != null && r.getReservationReminder().getChecked() == false)
reservationReminderList.add(r.getReservationReminder());
}
return reservationReminderList;
}
And after that when I see how JSON looks like - it's strange, because:
[{"reservationReminderId":2,"reservation":{"code":263022,"date":1487851200000,"reservationClient":{"clientPesel":"91122619197","name":"Client 1","surname":"Client 1","email":"client#wp.pl","phone":"234567890","accountNumber":"34567897654345678987654356","clientUser":{"userId":3,"login":"client","passwordHash":"$2a$10$0jJMMzeh2CTRagk3hwRSlurx.mxLgR1aAUQOYBD9QFqbISeoTSVN.","userRole":{"roleId":3,"name":"CLIENT","users":[{"userId":8,"login":"clien5","passwordHash":"$2a$10$6WrmwpwOdhv6UXBo2mYq8ucKiQTwvIwTHw23myo6.oujflh8pqKR.","userRole":{"roleId":3,"name":"CLIENT","users":[{"userId":8,"login":"clien5","passwordHash":"$2a$10$6WrmwpwOdhv6UXBo2mYq8ucKiQTwvIwTHw23myo6.oujflh8pqKR.","userRole":{"roleId":3,"name":"CLIENT","users":[{"userId":8,"login":"clien5","passwordHash":"$2a$10$6WrmwpwOdhv6UXBo2mYq8ucKiQTwvIwTHw23myo6.oujflh8pqKR.","userRole":{"roleId":3,"name":"CLIENT","users":[{"userId":8,"login":"clien5","passwordHash":"$2a$10$6WrmwpwOdhv6UXBo2mYq8ucKiQTwvIwTHw23myo6.oujflh8pqKR.","userRole":{"roleId":3,"name":"CLIENT","users":
....
[{"userId":8,"login":"clien5","passwordHash":"$2a$10$6WrmwpwOdhv6UXBo2mYq8ucKiQTwvIwTHw23myo6.oujflh8pqKR.","userRole":{"roleId":3,"name":"CLIENT","users":[{"userId":8,"login":"clien5","passwordHash":"$2a$10$6WrmwpwOdhv6UXBo2mYq8ucKiQTwvIwTHw23myo6.oujflh8pqKR.","userRole":{"roleId":3,"name":"CLIENT","users":[{"userId":8,"login":"clien5","passwordHash":"$2a$10$6WrmwpwOdhv6UXBo2mYq8ucKiQTwvIwTHw23myo6.oujflh8pqKR.","userRole":{"roleId":3,"name":"CLIENT","users":[{"userId":8,"login":"clien5","passwordHash":{"timestamp":1489015140465,"status":200,"error":"OK","exception":"org.springframework.http.converter.HttpMessageNotWritableException","message":"Could not write content: Infinite recursion (StackOverflowError) (through reference chain: com.carwash.domains.User[\"userRole\"]->com.carwash.domains.Role[\"users\"]->org.hibernate.collection.internal.PersistentBag[0]->com.carwash.domains.User[\"userRole\"]->com.carwash.domains.Role[\"users\"]->org.hibernate.collection.internal.PersistentBag[0]->com.carwash.domains.User[\"userRole\"]->com.carwash.domains.Role[\"users\"]->org.hibernate.collection.internal.PersistentBag[0]->com.carwash.domains.User[\"userRole\"]->com.carwash.domains.Role[\"users\"]->org.hibernate.collection.internal.PersistentBag[0]->com.carwash.domains.User[\"userRole\"]->com.carwash.domains.Role[\"users\"]->org.hibernate.collection.internal.PersistentBag[0]->com.carwash.domains.User[\"userRole\"]->com.carwash.domains.Role[\"users\"]->org.hibernate.collection.internal.PersistentBag[0]->com.carwash.domains.User[\"userRole\"]->com.carwash.domains.Role[\"users\"]->org.hibernate.collection.internal.PersistentBag[0]->com.carwash.domains.User[\"userRole\"]->com.carwash.domains.Role[\"users\"]->org.hibernate.collection.internal.PersistentBag[0]->com.carwash.domains.User[\"userRole\"]->com.carwash.domains.Role[\"users\"]->org.hibernate.collection.internal.PersistentBag[0]->com.carwash.domains.User[\"userRole\"]->com.carwash.domains.Role[\"users\"]-
...
\"]->org.hibernate.collection.internal.PersistentBag[0]->com.carwash.domains.User[\"userRole\"]->com.carwash.domains.Role[\"users\"]->org.hibernate.collection.internal.PersistentBag[0]->com.carwash.domains.User[\"userRole\"]->com.carwash.domains.Role[\"users\"]->org.hibernate.collection.internal.PersistentBag[0]->com.carwash.domains.User[\"userRole\"]->com.carwash.domains.Role[\"users\"]->org.hibernate.collection.internal.PersistentBag[0]->com.carwash.domains.User[\"userRole\"]->com.carwash.domains.Role[\"users\"]->org.hibernate.collection.internal.PersistentBag[0]->com.carwash.domains.User[\"userRole\"]->com.carwash.domains.Role[\"users\"]->org.hibernate.collection.internal.PersistentBag[0]->com.carwash.domains.User[\"userRole\"])","path":"/api/reservationreminder"}
What am I doing wrong?
Perhaps it can say you something - I don't why after making a GET method (only get) I got some those bugs?
You have a Infinite recursion between your User and UserRole object. Whenever a user is serialized his related user roles are also serialized. Since user roles does also have a relation back to the user you have the recursion.
Solution to this could be to use #JsonManagedReference (added to the relation in User) and #JsonBackReference (realtion at UserRoles). See also here: Infinite Recursion with Jackson JSON and Hibernate JPA issue
#Entity
public class User
...
#JsonManagedReference
private Set<UserRole> userRoles;
#Entity
public class UserRole
...
#JsonBackReference
private User user;
#JsonManagedReference would mean that during serialization the relation part is taken into account. So the related user roles would be also serialized. Since there the related connection is marked with #JsonBackReference serialization stops to go further.
#KLHauser
So how to manage the case if I have a class
#Entity
public class ReservationReminder {
private int reservationReminderId;
private Reservation reservation;
private boolean isChecked;
private Date checkedDate;
and Reservation class
#Entity
public class Reservation {
// private Integer RESERVATION_ID;
// private Integer id;
private long code;
private Date date;
private Client reservationClient;
private WashType reservationWashType;
private Vehicle reservationVehicle;
private Wash reservationWash;
private Worker reservationWorkerPesel;
private Review reservationReview;
private ReservationReminder reservationReminder;
#Entity
public class Worker {
private String workerPesel;
private String name;
private String surname;
private Date startDateWorking;
private String accountNumber;
private List<Review> workerReview;
private Adress workerAdress;
private List<LaborHistory> workerLaborHistory;
private Wash workerWash;
//private List<WorkerWorkerTime> workerWorkTime;
// private Role WORKER_ROLE;
private User workerUser;
private List<Reservation> workerReservation;
And I'd like to load ReservationReminder class with Worker from Reservation class? If I use #JsonIgonre like that
#OneToOne(mappedBy = "reservationReminder", fetch = FetchType.LAZY)
#JsonIgnore
public Reservation getReservation() {
return reservation;
}
I only got a Json with checkedDate, isChecked and reservationReminderId from ReservationReminder

Could not write content: failed to lazily initialize a collection of role

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