I'm having some problems with my webservice -_-
I try to receive my movie list form the webservice, but there always this nasty error.
here is my model:
package de.hawhof.dm.kino.model;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.OneToMany;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#XmlRootElement(name="movie")
public class Movie implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
int movieid;
String name;
String releaseDate;
#Lob
String critic;
String runtime;
#Lob
String synopsis;
String posterPath;
String thumbnail;
// user movie comment rating
#OneToMany(cascade = CascadeType.ALL, mappedBy = "movie")
List<User_Movie_CR> userMovieCR;
// cinema movie
#OneToMany(cascade = CascadeType.ALL, mappedBy = "movie")
List<Cinema_Movie> cinemaMovie;
// user film cinema table
#OneToMany(mappedBy = "movie")
Set<Cinema_Movie_User> cinema_movie_user;
public Movie() {
}
public Movie(String name, String releaseDate, String critic,
String runtime, String synopsis, String posterPath, String thumbnail) {
this.name = name;
this.releaseDate = releaseDate;
this.critic = critic;
this.runtime = runtime;
this.synopsis = synopsis;
this.posterPath = posterPath;
this.thumbnail = thumbnail;
}
// toString
public String toString() {
return "Movie [name=" + name + ", releaseDate=" + releaseDate
+ ", critic=" + critic + ", runtime=" + runtime + ", synopsis="
+ synopsis + ", posterPath=" + posterPath + "]";
}
// setter and getter
}
There is also a dao and a facade, but they are working fine!
here is my service:
package de.hawhof.dm.kino.ws;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;
import de.hawhof.dm.kino.facade.MovieFacade;
import de.hawhof.dm.kino.model.*;
#Path("/movies")
public class MoviesResource {
#Context
UriInfo uriInfo;
#Context
Request request;
MovieFacade movieFacade = new MovieFacade();
#GET
#Path("xml")
#Produces(MediaType.TEXT_XML)
public List<Movie> getMoviesBrowser() {
List<Movie> movies = new ArrayList<Movie>();
movies.addAll(movieFacade.listAll());
return movies;
}
#GET
#Path("XMLForApp")
#Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public List<Movie> getMovies() {
List<Movie> movies = new ArrayList<Movie>();
movies.addAll(movieFacade.listAll());
return movies;
}
#GET
#Path("onemovie")
public Movie getMovie() {
return new Movie("TEST!!!", "", "", "", "", "", "");
}
#GET
#Path("count")
#Produces(MediaType.TEXT_PLAIN)
public String getCount() {
int count = movieFacade.listAll().size();
return String.valueOf(count);
}
#Path("{movie}")
public MovieResource getMovie(#PathParam("movie") int movieid) {
return new MovieResource(uriInfo, request, movieid);
}
}
the methode "onemovie" and "count" works fine and i will get the xml displayed in my browser,but when i call "XMLForApp" then the server throw me exception.
my client is here:
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.MediaType;
public class MovieWSClient {
Client client;
String movieList;
public MovieWSClient() {
client = ClientBuilder.newClient().register(getClass());
movieList = client.target("http://localhost:8080/kino").path("/rest/movies/XMLForApp").request(MediaType.APPLICATION_JSON).get(String.class);
}
public String getMovieList() {
return movieList;
}
}
the exception is:
SEVERE: Servlet.service() for servlet [Hello Servlet] in context with path [/kino] threw exception [An exception occurred processing JSP page /pages/public/hello.jsp at line 20
Stacktrace:] with root cause
javax.ws.rs.InternalServerErrorException: HTTP 500 Internal Server Error
at org.glassfish.jersey.client.JerseyInvocation.convertToException(JerseyInvocation.java:904)
at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:749)
at org.glassfish.jersey.client.JerseyInvocation.access$500(JerseyInvocation.java:88)
at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:650)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:421)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:646)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:375)
at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:275)
at de.hawhof.dm.kino.ws.MovieWSClient.<init>(MovieWSClient.java:16)
at org.apache.jsp.pages.public_.hello_jsp._jspService(hello_jsp.java:77)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:684)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:471)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:402)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:329)
at de.hawhof.dm.kino.servlet.HelloServlet.doGet(HelloServlet.java:21)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)
I had the same issue but with GAE( google app engine). It's seems related to Jersey MessageBodyWriter not able to serialize the JSON.
I solved it by adding genson.jar to my classpath. Genson is a JSON serializer/deserializer library that you can download on genson project page.
You can also use MOXy as your JSON provider (since it's the preferred way of supporting JSON binding with Jersey).
Don't forget to copy the jar into your WEB-INF/lib folder.
Try adding #RequestScoped to the REST service.
Related
I use the technologies jpa, hibernate, spring boot - data, api REST, MySql
Please help me out regarding this ERROR..!
Hibernate: select creditcard0_.credit_id as credit_i1_2_0_, creditcard0_.cardno as cardno2_2_0_, creditcard0_.creditname as creditna3_2_0_, creditcard0_.cvv as cvv4_2_0_, creditcard0_.uid as uid5_2_0_ from credit_card creditcard0_ where creditcard0_.credit_id=? Hibernate: insert into credit_card (cardno, creditname, cvv, uid, credit_id) values (?, ?, ?, ?, ?) 2022-12-22 11:39:10.208 WARN 2368 --- [nio-8080-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1048, SQLState: 23000 2022-12-22 11:39:10.208 ERROR 2368 --- [nio-8080-exec-4] o.h.engine.jdbc.spi.SqlExceptionHelper : Column 'uid' cannot be null 2022-12-22 11:39:10.209 INFO 2368 --- [nio-8080-exec-4] o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements 2022-12-22 11:39:10.223 ERROR 2368 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
java.sql.SQLIntegrityConstraintViolationException: Column 'uid' cannot be null at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117) ~[mysql-connector-j-8.0.31.jar:8.0.31] at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-j-8.0.31.jar:8.0.31] at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:916) ~[mysql-connector-j-8.0.31.jar:8.0.31] at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1061) ~[mysql-connector-j-8.0.31.jar:8.0.31]
Here is my code:
**User.java**
import java.io.Serializable; import java.util.Set;
import javax.persistence.Access; import javax.persistence.AccessType; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.transaction.Transactional;
import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Type;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
#Transactional #Entity #Table(name="users") public class User {
#Id
#GeneratedValue(strategy= GenerationType.AUTO,generator="native")
#GenericGenerator(name = "native",strategy = "native")
private int id;
#Column(name="name")
private String name;
#Column(name="email")
private String email;
#Column(name="phoneno")
private int phone_no;
#Column(name="address")
private String address;
private String pwd;
#OneToMany(mappedBy = "user",fetch=FetchType.LAZY,cascade = CascadeType.ALL)
private Set<CreditCard> creditcard;
public User() {
}
public User(String name, String email, int phone_no, String address, String pwd) {
super();
this.name = name;
this.email = email;
this.phone_no = phone_no;
this.address = address;
this.pwd=pwd;
}
public Set<CreditCard> getCreditcard() {
return creditcard;
}
public void setCreditcard(Set<CreditCard> creditcard) {
this.creditcard = creditcard;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail_id(String email) {
this.email = email;
}
public int getPhone_no() {
return phone_no;
}
public void setPhone_no(int phone_no) {
this.phone_no = phone_no;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
#Override
public String toString() {
return "User [uid=" + id + ", name=" + name + ", email=" + email + ", phone_no=" + phone_no
+ ", address=" + address + ", pwd=" + pwd + "]";
}
}
**CreditCard.java**
import java.io.Serializable;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.transaction.Transactional;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Transactional
#Entity
#Table(name="credit_card")
public class CreditCard implements Serializable {
#Id
private int credit_id;
private String cardno;
private String cvv;
private String creditname;
#NotFound(action = NotFoundAction.IGNORE)
#ManyToOne(fetch=FetchType.LAZY,optional = true)
#JoinColumn(name="uid",nullable = true)
private User user;
public CreditCard() {
super();
// TODO Auto-generated constructor stub
}
public CreditCard( String cardno, String cvv, String creditname,User user) {
super();
//this.credit_id = credit_id;
this.cardno = cardno;
this.cvv = cvv;
this.creditname = creditname;
this.user=user;
}
public int getCredit_id() {
return credit_id;
}
public void setCredit_id(int credit_id) {
this.credit_id = credit_id;
}
public String getCardno() {
return cardno;
}
public void setCardno(String cardno) {
this.cardno = cardno;
}
public String getCvv() {
return cvv;
}
public void setCvv(String cvv) {
this.cvv = cvv;
}
public String getCreditname() {
return creditname;
}
public void setCreditname(String creditname) {
this.creditname = creditname;
}
#JsonIgnore
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
#Override
public String toString() {
return "CreditCard [credit_id=" + credit_id + ", cardno=" + cardno + ", cvv=" + cvv + ", creditname="
+ creditname + "]";
}
}
**UserController.java**
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.Grocery.Grocery.model.User;
import com.Grocery.Grocery.repository.GroceryRepository;
#RestController
#RequestMapping("/users")
public class UserController {
#Autowired
private GroceryRepository groceryRepository;
#GetMapping
public List<User> getAllUsers()
{
return groceryRepository.findAll();
}
#GetMapping("/{id}")
public ResponseEntity getbyid(#PathVariable("id") int id) {
return new ResponseEntity(groceryRepository.findById(id), HttpStatus.OK);
}
}
**CreditCardController.java**
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.Grocery.Grocery.model.CreditCard;
import com.Grocery.Grocery.repository.CreditCardRepository;
#RestController
#RequestMapping("/creditcard")
public class CreditCardController {
#Autowired
private CreditCardRepository creditcardRepository;
#GetMapping
public List<CreditCard> getAllCreditCard(){
return creditcardRepository.findAll();
}
#PostMapping("/add")
#ResponseBody
public CreditCard createEmployee(#RequestBody CreditCard credit) {
return creditcardRepository.save(credit);
}
}
**GroceryRepository.java(UserRepository.java)**
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.stereotype.Repository;
import com.Grocery.Grocery.model.User;
#Repository
public interface GroceryRepository extends JpaRepository<User, Integer> {
List<User> findByEmail(String email);
}
**CreditCardRepository.java**
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.Grocery.Grocery.model.CreditCard;
#Repository
public interface CreditCardRepository extends JpaRepository<CreditCard, Integer>{
}
aaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaf awe fffffffffffff ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeee eeeeeeeeeeeeeeeeeeeeee eeeggg gggg gggggggggggggggggg kkkkkkkkkkkkkkkkkkk
i could'n stock byte in mysql database table using "jpa" hibernate under spring "mvc"
am getting file as multipart :file and some text from form
tables are created dynamically with hibernate
when trying to save file with form data,the data is stocked properly ,but about the file just 4 bytes blob stocked
the entity is like
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "store")
public class Store {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="storeid", updatable = false, nullable = false)
#org.springframework.data.annotation.Id
private Long storeid;
#Column(name = "stor_Name")
private String storName;
...
#Column(name = "stor_Logo", columnDefinition="BLOB")
#Lob
private byte[] storLogo;
#Column(name = "stor_Email")
private String storEmail;
#Column(name = "stor_Phone")
private String storPhone;
#OneToMany(mappedBy = "store")
private Set<Product> storProducts;
public Store(Long storeid,
String storName,
String storDesc,
byte[] storLogo,
Double storPrice,
String storeEmail,
String storePhone,
Set<Product> storProducts
) {
this.storeid = storeid;
this.storName = storName;
this.storDesc = storDesc;
this.storLogo = storLogo;
this.storEmail = storeEmail;
this.storPhone = storePhone;
this.storProducts = storProducts;
}
... setters and getters
repository is coded as well
import com.openstore.models.Store;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface StoreRepository extends JpaRepository<Store, Long> {
Store findByStorName(final String storName);
}
all is stocking properly except "storLogo" it stocks just 4 bytes of blob
i tray to change in application.proprieties to verify if the problem is "http" problem by modifying accepted file size , so it does not accept over sizing files
so i debug repository controller :
#RequestMapping(value = "save", method = RequestMethod.POST, consumes =
"multipart/form-data")
public String save(#RequestParam String storName,
#RequestParam String storDesc,
#RequestParam Double storPrice,
#RequestPart MultipartFile storLogo,
#RequestParam String storEmail,
#RequestParam String storPhone
) {
Store store = new Store();
store.setStorName(storName);
store.setStorDesc(storDesc);
try {
store.setStorLogo(storLogo.getBytes());
} catch (IOException ex) {
Logger.getLogger(StoreController.class.getName()).log(Level.SEVERE, null, ex);
}
store.setStoreEmail(storEmail);
store.setStorePhone(storPhone);
storeService.save(store);
return "redirect:/show/" + store.getstoreid();
}
and am getting the file just well in the store object ,in the service
so i guess is miss configuring problem ,maybe in jparepository or hibernate
any idea
I am trying to get my Spring MySQL backend to return a mutli table VIEW (not a single table) thru AXIOS to my REACT front end.
I am testing my Backend with POSTMAN (http://localhost:8080/api/v1/cpysiteassetview)
I get an error messages from SPRING and a long error message from POSTMAN (below).
I am close, but going wrong somewhere and I hope someone more familiar with this can shed some light and explain where I am going wrong.
Here is the VIEW\MODEL\REPOSITORY\CONTROLLER.
...
CREATE
ALGORITHM = UNDEFINED
DEFINER = `root`#`localhost`
SQL SECURITY DEFINER
VIEW `cpysiteasset` AS
SELECT
`cpymaster`.`cpymasterid` AS `cpymasterid`,
`cpymaster`.`cpymastercode` AS `cpymastercode`,
`cpymaster`.`cpymastername` AS `cpymastername`,
`sitemaster`.`sitemasterid` AS `sitemasterid`,
`sitemaster`.`sitemastercode` AS `sitemastercode`,
`sitemaster`.`sitemastername` AS `sitemastername`,
`assets`.`assetsid` AS `assetsid`,
`assets`.`assetsidentifier` AS `assetsidentifier`,
`assets`.`assetsname` AS `assetsname`
FROM
((`cpymaster`
JOIN `sitemaster` ON = `cpymaster`.`cpymasterid`)))
JOIN `assets` ON ((`assets`.`sitemaster_sitemasterid` = `sitemaster`.`sitemasterid`)))
ORDER BY `sitemaster`.`sitemastercode` , `assets`.`assetsidentifier`
//MODEL
package net.javaguides.springboot.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Immutable;
#Entity
#Immutable
#Table(name = "`cpysiteassetview`")
public class CpySiteAssetView {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private int cpymasterid;
private String cpymastercode;
private String cpymastername;
private int sitemasterid;
private String sitemastercode;
private String sitemastername;
private int assetsid;
private String assetsidentifier;
private String assetsname;
#Column(name = "cpymasterid")
public int getCpymasterid() {
return cpymasterid;
}
#Column(name = "cpymastercode")
public String getCpymastercode() {
return cpymastercode;
}
#Column(name = "cpymastername")
public String getCpymastername() {
return cpymastername;
}
#Column(name = "sitemasterid")
public int getSitemasterid() {
return sitemasterid;
}
#Column(name = "sitemastercode")
public String getSitemastercode() {
return sitemastercode;
}
#Column(name = "sitemastername")
public String getSitemastername() {
return sitemastername;
}
#Column(name = "assetsid")
public int getAssetsid() {
return assetsid;
}
#Column(name = "assetsidentifier")
public String getAssetsidentifier() {
return assetsidentifier;
}
#Column(name = "assetsname")
public String getAssetsname() {
return assetsname;
}
}
//Repository
package net.javaguides.springboot.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import net.javaguides.springboot.model.CpySiteAssetView;
#Repository
public interface CpySiteAssetViewRepository1 extends JpaRepository<CpySiteAssetView, Long>{
public List<CpySiteAssetView> findAll();
}
//Controller
package net.javaguides.springboot.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import net.javaguides.springboot.model.CpySiteAssetView;
import net.javaguides.springboot.repository.CpySiteAssetViewRepository1;
#CrossOrigin(origins = "http://localhost:3000")
#RestController
#RequestMapping("/api/v1/")
public class CpySiteAssetViewController {
#Autowired
private CpySiteAssetViewRepository1 cpySiteAssetViewRepository1;
//get all
#GetMapping("/cpysiteassetview")
public List<CpySiteAssetView> getAllCpySiteAssetView(){
return cpySiteAssetViewRepository1.findAll();
}
}
...
Error Message from Spring:
java.sql.SQLSyntaxErrorException: Unknown column 'cpysiteass0_.id' in 'field list'
Error Message from Postman (first part):
"error": "Internal Server Error",
"trace": "org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet\r\n\tat org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:259)\r\n\tat org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:233)\r\n\tat org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:551)\r\n\tat org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)\r\n\tat org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)\r\n\tat org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(Per
OK..commented out //private long id;
and now it works !!!!!
I'm trying to make a simple spring boot web service that returns json, but i get this error " java.lang.IllegalArgumentException: No converter found for return value of type: testSomething " even tho i have the jackson json dependencies in my gradle.build through the spring-boot-starter-web
rest controller.
package controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.*;
import com.anders.cphbusiness.numbersModel.testSomething;
#RestController
#RequestMapping("/test")
public class restController {
public restController() {
}
#RequestMapping(method=RequestMethod.GET)
public #ResponseBody testSomething test() {
return new testSomething("asd", 5);
}
}
the model.
package numbersModel;
public class testSomething {
private String msg;
private int aNumber;
public testSomething(String msg, int aNumber) {
this.msg = msg;
this.aNumber = aNumber;
}
#Override
public String toString() {
return msg;
}
}
added
compile('org.springframework.boot:spring-boot-starter-web')
for jackson json support in my gradle.build file.
Try adding also:
compile("com.fasterxml.jackson.core:jackson-databind")
NOTE: Also it is a good practise to start your class name with upper case letter.
public class testSomething
to
public class TestSomething
I am using Spring 4 and Hibernate 4. I am using java jpa to use hibernate. I want to load few data lazily. And I have also configured Jackson mapper to convert my java object to json and vice versa. But it's throwing exception while converting the java to json. I have created custom object mapper but still it's not working.
Please see the following classes and see what I am missing here
I am using annotations. Hibernate configuration file:
MvcConfiguration.java
package com.ampdev.platform.module.common.config;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import com.ampdev.platform.framework.dataaccess.config.HibernateAwareObjectMapper;
import com.ampdev.platform.framework.rest.security.AuthenticationService;
import com.ampdev.platform.framework.rest.security.AuthenticationServiceDefault;
import com.ampdev.platform.module.user.util.EncryptionUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
#Configuration
#ComponentScan(basePackages = "com.ampdev")
#EnableWebMvc
#EnableTransactionManagement
public class MvcConfiguration extends WebMvcConfigurerAdapter
{
#Bean
public ViewResolver getViewResolver()
{
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Autowired
#Bean(name = "authenticationService")
public AuthenticationService getAuthencticaionService()
{
return new AuthenticationServiceDefault();
}
#Autowired
#Bean(name = "passwordEncoder")
public PasswordEncoder getPasswordEncoder()
{
return new BCryptPasswordEncoder();
}
#Autowired
#Bean(name = "encrypyionUtil")
public EncryptionUtil getEncryptionUtil(PasswordEncoder passwordEncoder)
{
return new EncryptionUtil(passwordEncoder);
}
#Autowired
#Bean(name = "objectMapper")
public ObjectMapper getObjectMapper()
{
return new HibernateAwareObjectMapper();
}
#Autowired
#Bean(name = "jsonMessageConverter")
public MappingJackson2HttpMessageConverter getMessageConvertor()
{
return new MappingJackson2HttpMessageConverter();
}
#Autowired
private ObjectMapper objectMapper;
#Autowired
private MappingJackson2HttpMessageConverter jsonMessageConverter;
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters)
{
jsonMessageConverter.setObjectMapper(objectMapper);
converters.add(jsonMessageConverter);
}
}
I have created a custom object mapper to include Hibernate4Module
HibernateAwareObjectMapper.java
package com.ampdev.platform.framework.dataaccess.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module;
public class HibernateAwareObjectMapper extends ObjectMapper
{
/**
*
*/
private static final long serialVersionUID = -4013528320937607847L;
public HibernateAwareObjectMapper()
{
Hibernate4Module hibernateModule = new Hibernate4Module();
registerModule(hibernateModule);
}
}
Here is my Data object in which I am using the lazy loading:
UserMovieReviewData .java
package com.ampdev.platform.module.movie.review.user.dataobject;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import com.ampdev.platform.module.common.dataobject.PersistedDataObject;
import com.ampdev.platform.module.movie.dataobject.MovieData;
import com.ampdev.platform.module.movie.review.constants.ReviewConstants;
import com.ampdev.platform.module.user.dataobject.UserData;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
#Entity
#Table(name = "movie_review_user")
#JsonInclude(Include.NON_NULL)
public class UserMovieReviewData extends PersistedDataObject
{
/**
*
*/
private static final long serialVersionUID = -5644749600929596177L;
#Id
#GeneratedValue
#Column(name = "review_id")
private long id;
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "movie_id")
private MovieData movieData;
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "user_id")
private UserData userData;
#Column(name = "rating")
private int rating;
#Column(name = "title")
private String title;
#Column(name = "review")
private String review;
#Column(name = "create_date")
#Temporal(TemporalType.TIMESTAMP)
private Date createDate;
#Column(name = "update_date")
#Temporal(TemporalType.TIMESTAMP)
private Date updateDate;
#Override
public long getId()
{
return id;
}
public void setId(long id)
{
this.id = id;
}
public MovieData getMovieData()
{
return movieData;
}
public void setMovieData(MovieData movieData)
{
this.movieData = movieData;
}
public UserData getUserData()
{
return userData;
}
public void setUserData(UserData userData)
{
this.userData = userData;
}
public int getRating()
{
return rating;
}
public void setRating(int rating)
{
this.rating = rating;
}
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title = title;
}
public String getReview()
{
return review;
}
public void setReview(String review)
{
this.review = review;
}
public Date getCreateDate()
{
return createDate;
}
public void setCreateDate(Date createDate)
{
this.createDate = createDate;
}
public Date getUpdateDate()
{
return updateDate;
}
public void setUpdateDate(Date updateDate)
{
this.updateDate = updateDate;
}
}
Here is my web service resource which I am using as rest resource:
ReviewResource.java
package com.ampdev.platform.module.movie.review.resource;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.ampdev.platform.framework.rest.BaseExecutor;
import com.ampdev.platform.framework.rest.RestBaseResource;
import com.ampdev.platform.module.common.constants.URIConstants;
import com.ampdev.platform.module.movie.review.constants.ReviewConstants;
import com.ampdev.platform.module.movie.review.user.dataobject.UserMovieReviewData;
#Controller
#RequestMapping(value = "/ws/movie/review")
#Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class ReviewResource extends RestBaseResource
{
#Autowired
private BaseExecutor<UserMovieReviewData, UserMovieReviewData> createMovieReviewExecutor;
#Autowired
private BaseExecutor<String, List<UserMovieReviewData>> getMovieReviewExecutor;
#RequestMapping(value = ReviewConstants.ADD, method = RequestMethod.POST)
public ResponseEntity<UserMovieReviewData> createMovieReview(
#RequestParam(value = ReviewConstants.TYPE, required = true) String type,
RequestEntity<UserMovieReviewData> requestEntity)
{
createMovieReviewExecutor.setAttribute(ReviewConstants.TYPE, type);
return performTask(requestEntity, createMovieReviewExecutor);
}
#RequestMapping(value = URIConstants.GET_IDS, method = RequestMethod.GET)
public ResponseEntity<List<UserMovieReviewData>> getReview(
#RequestParam(value = ReviewConstants.TYPE, required = true) String type, #PathVariable(value = "ids") String reviewIds)
{
getMovieReviewExecutor.setAttribute(ReviewConstants.TYPE, type);
getMovieReviewExecutor.setAttribute(ReviewConstants.REVIEW_IDS, reviewIds);
return performTask(null, getMovieReviewExecutor);
}
}
I am using spring 4 + hibernate 4.
I am getting the following error when I am trying to get data from Rest web service call:
I am getting the following error when I am trying to fetch the data from Rest web service:
org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:238)
org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:208)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:161)
org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:144)
org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:71)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:128)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:186)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
root cause
com.fasterxml.jackson.databind.JsonMappingException: could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->com.ampdev.platform.module.movie.review.user.dataobject.UserMovieReviewData["movieData"]->com.ampdev.platform.module.movie.dataobject.MovieData_$$_jvst49f_5["id"])
com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:232)
com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:197)
com.fasterxml.jackson.databind.ser.std.StdSerializer.wrapAndThrow(StdSerializer.java:187)
com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:652)
com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)
com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:541)
com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:644)
com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)
com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:100)
com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:21)
com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:183)
com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:114)
com.fasterxml.jackson.databind.ObjectMapper.writeValue(ObjectMapper.java:1837)
org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:231)
org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:208)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:161)
org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:144)
org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:71)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:128)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:186)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
root cause
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:165)
org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:286)
org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
com.ampdev.platform.module.movie.dataobject.MovieData_$$_jvst49f_5.getId(MovieData_$$_jvst49f_5.java)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
com.fasterxml.jackson.databind.ser.BeanPropertyWriter.get(BeanPropertyWriter.java:726)
com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:506)
com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:644)
com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)
com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:541)
com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:644)
com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)
com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:100)
com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:21)
com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:183)
com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:114)
com.fasterxml.jackson.databind.ObjectMapper.writeValue(ObjectMapper.java:1837)
org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:231)
org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:208)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:161)
org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:144)
org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:71)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:128)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:186)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
You're trying to access a lazy collection outside of the hibernate session. There are a few ways to solve this, the most clear is to access the size() of each collection you're going to be serializing in your service class, which causes the collection to be loaded and therefore available outside the session.
Another alternative is to annotate the collection with FetchType.EAGER, but this will affect all uses of your model, which might not be what you want. Finally, you can use the OpenSessionInView pattern, which maintains an open hibernate session for the duration of the request (and therefore allows you to load lazy collections outside where the session boundary would otherwise be). This last alternative is generally considered an anti-pattern.