Hibernate complex data retrieval? - java

I have nine related tables in my database.i have to retrieve records after filtering user request.
My Entities follows ,
Movie
#Entity
#Table(name = "movie")
public class Movie implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "movie_id")
private int movieId;
#Column(name = "category_id")
private Integer categoryId;
#Column(name = "movie_title")
private String movieTitle;
#Column(name = "movie_description", columnDefinition = "TEXT")
private String movieDescription;
#Column(name = "movie_summary", columnDefinition = "TEXT")
private String movieSummary;
private Integer status;
#Column(name = "language_id")
private Integer languageId;
#Column(name = "banner_image_url")
private String bannerImageUrl;
#Column(name = "imdb_rating")
private Integer imdbRating;
#Column(name = "rotten_tomatoes_rating")
private Integer rottenTomatoesRating;
#Column(name = "user_avg_rating")
private Float userAvgRating;
#Column(name = "main_genre_id")
private Integer mainGenreId;
#Column(name = "secondary_genre_id")
private Integer secondaryGenreId;
#Column(name = "created_by_user_id")
private Integer createdByUserId;
}
Category
#Entity
#Table(name = "category")
public class FetchSubCategory implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "category_id")
private Integer categoryId;
#Column(name = "category_name")
private String categoryName;
}
MovieActorMapping
#Entity
#Table(name = "movie_actor_mapping")
public class MovieActorMapping implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "mapping_id")
private int mappingId;
#Column(name = "movie_id")
private Integer movieId;
#Column(name = "actor_id")
private Integer actorId;
}
MovieActors
#Entity
#Table(name = "movie_actors")
public class MovieActors implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "actor_id")
private int actorId;
#Column(name = "actor_name")
private String actorName;
}
MovieGenre
#Entity
#Table(name = "movie_genre")
public class MovieGenre implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "genre_id")
private int genreId;
#Column(name = "genre_name")
private String genreName;
#Column(name = "created_by_user_id")
private Integer createdByUserId;
}
MovieLanguage
#Entity
#Table(name = "movie_language")
public class MovieLanguage implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "language_id")
private int languageId;
#Column(name = "language_name")
private String languageName;
#Column(name = "created_by_user_id")
private Integer createdByUserId;
#Column(name = "last_updated_user_id")
private Integer lastUpdatedUserId;
}
The user will request like below .all are optional fields ,
{
"subCategory":"New Release",
"language":"Malayalam",
"actor":"allu arjun",
"filmGenre":"'Family'"
}
According to the request i will return the movie list by checking conditions from corresponding table using subquery.
Method
public List<Movie> getFilterMovieList(FilterMovieRequest filterMovieRequest) throws SQLException, ClassNotFoundException, IOException {
List<Movie> movies = null;
try {
String subCategory = filterMovieRequest.getSubCategory();
String language = filterMovieRequest.getLanguage();
String actor = filterMovieRequest.getActor();
String filmGenre = filterMovieRequest.getFilmGenre();
String contained = "where";
String sql = "from Movie as M ";
if (actor.length() > 1) {
sql += contained + " movieId in(select movieId from MovieActorMapping where actorId in(select actorId from MovieActors where actorName='" + actor + "')) ";
contained = "and";
}
if (subCategory.length() > 1) {
sql += contained + " M.categoryId=(select categoryId from FetchSubCategory where categoryName='" + subCategory + "') ";
contained = "and";
}
if (language.length() > 1) {
sql += contained + " M.languageId=(select languageId from MovieLanguage where languageName='" + language + "') ";
contained = "and";
}
if (filmGenre.length() > 1) {
sql += contained + " (M.mainGenreId in(select genreId from MovieGenre where genreName in(" + filmGenre + ")) or M.secondaryGenreId in(select genreId from MovieGenre where genreName in(" + filmGenre + ")))";
contained = "and";
}
if (contained.equals("and")) {
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery(sql);
movies = query.list();
}
} catch (Exception e) {
e.printStackTrace();
}
return movies;
}
And it works fine.the problem is now i have to combine with the result in which theaters movies is playing and the show time also.
And my theater related tables follow,
theater_movie_mapping
theater_list
show_timings
you can see in column movie_id in theater_movie_mapping which related to my base table movie. using that we can fetch theater_id and show_id for fetch the theaters and show timing..note that i have a movie list early fetched after checking above conditions.How can i combine theaters from theater_list and show times from show_timings ? being an android developer it seems complex for me.Am totally stucked. Any help will be appreciated.Am using Spring restful webservice.
Now i have getting the result in following format,
[
{
"movieId": 8,
"categoryId": 14,
"movieTitle": "Kanyaka Talkies",
"movieDescription": "CRITICS 3 out of 5 (Good) 3 out of 5 (Good) The composite emotional weather that the film sports makes it maddening and nurturing at once, rendering it an almost enigmatic feel. And it is this ethereal complexity that 'Kanyaka Talkies' inherently has, that makes the film singular. ",
"movieSummary": "The concurrence of the three key characters in 'Kanyaka Talkies' isn't of the traditionalist kind; rather, by throwing the three of them together, the film does achieve the ostensibly improbable feat of placing the unlikeliest of players collectively on board, with their fates irrevocably intertwined with each other. ",
"status": 1,
"languageId": 1,
"bannerImageUrl": "0",
"imdbRating": 1,
"rottenTomatoesRating": 3,
"userAvgRating": 2,
"mainGenreId": 1,
"secondaryGenreId": 2,
"createdByUserId": 16
},
{
"movieId": 9,
"categoryId": 14,
"movieTitle": "Wonderful Journey",
"movieDescription": "Wonderful Journey' is one of the most misdirecting titles as yet for a film this year. Anything but wonderful, this is an absolute cinematic misadventure that will have you pulling out your hair strands in no time. ",
"movieSummary": "Some things in life simply cannot be averted, they say. I do agree, what with the late night show of 'Wonderful Journey' getting cancelled yesterday night and me courageously venturing out for it yet again today noon, only to embark on one of the most horrendous journeys I have ever gone for in my entire life. ",
"status": 1,
"languageId": 1,
"bannerImageUrl": "0",
"imdbRating": 1,
"rottenTomatoesRating": 3,
"userAvgRating": 2,
"mainGenreId": 1,
"secondaryGenreId": 1,
"createdByUserId": 16
},
{
"movieId": 10,
"categoryId": 14,
"movieTitle": "Oru New Generation Pani",
"movieDescription": "Very occasionally does a movie come along that almost makes you vow to stay off the screens for a few weeks, and this year, the one has finally arrived. I'd gladly go ahead with a no-star rating for this one, had it not been for a technical glitch that prevents me from doing so! ",
"movieSummary": "'Oru New Generation Pani' is an atrocity that shocks you with its attempt to spin out a story line that will have you banging you head against the rails. Inauthentic to the core, the film tells a story that will have an insomniac snoring away in no time. ",
"status": 1,
"languageId": 1,
"bannerImageUrl": "0",
"imdbRating": 1,
"rottenTomatoesRating": 3,
"userAvgRating": 2,
"mainGenreId": 1,
"secondaryGenreId": 2,
"createdByUserId": 16
}
]
I have to add the theaters and show time too in every json object ie ,every movie..

Assume theater_movie_mapping is mapped to Class TheaterMovie which contains Movie movie in it
ArrayList<TheaterMovie> list = new ArrayList<TheaterMovie>();
for(int i = 0 ; i < movies.size() ; i++){
list.addAll((ArrayList<TheaterMovie>)createQuery("From TheaterMovie tm where tm.movies = :mo").setParameter("mo",movies.get(i)).getList());
}
Now assume show_timings is mapped to Class ShowTiming which contains Theater theater in it
ArrayList<ShowTiming> showTimeList = new ArrayList<ShowTiming>();
for(int i = 0 ; i < list.size() ; i++){
showTimeList = (ArrayList<ShowTiming>)createQuery("From ShowTiming st where st.theater = :th").setParameter("th",list.get(i).getTheater()).getList();
}
I hope this works well for you

Related

#ManyToMany duplicate entries

I have a problem with persisting. I have a Meal class in which is a list of Products. In Product class is a list of Meals -- #ManyToMany relation.
When I try to save it Compiler want to save every product, but then products are duplicated in my DB.
How I can indicate that the products are already there?
Here is my code
#Entity
public class Meal {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#JsonManagedReference
#ManyToMany(cascade = {
CascadeType.MERGE
})
private List<Product> foodList = new ArrayList<>();
#NaturalId
#Column(unique = true, nullable = false)
private String mealName;
private Integer servingWeightGrams = 0;
private Integer servingQty = 0;
private Double nfCalories = 0d;
private Double nfTotalFat = 0d;
...
#Entity
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#JsonBackReference
#ManyToMany(mappedBy = "foodList")
private List<Meal> meals = new ArrayList<>();
#Column(unique = false, nullable = false)
private String foodName;
...
#Service
public class MealManager {
MealService mealService;
ProductService productService;
#Autowired
public MealManager(MealService mealService, ProductService productService)
{
this.mealService = mealService;
this.productService = productService;
}
public Meal saveMeal(List<Food> foodList, String mealName){
Meal newMeal = new Meal();
newMeal.setMealName(mealName);
List<Product> productList = parseFoodToProduct(foodList);
productList.stream().forEach(y -> newMeal.getFoodList().add(y));
for(Product food : productList) {
newMeal.setNfCalories(newMeal.getNfCalories() + food.getNfCalories());
newMeal.setNfCholesterol(newMeal.getNfCholesterol() + food.getNfCholesterol());
newMeal.setNfDietaryFiber(newMeal.getNfDietaryFiber() + food.getNfDietaryFiber());
newMeal.setNfP(newMeal.getNfP() + food.getNfP());
newMeal.setNfPotassium(newMeal.getNfPotassium() + food.getNfPotassium());
newMeal.setNfProtein(newMeal.getNfProtein() + food.getNfProtein());
newMeal.setNfSaturatedFat(newMeal.getNfSaturatedFat() + food.getNfSaturatedFat());
newMeal.setNfSodium(newMeal.getNfSodium() + food.getNfSodium());
newMeal.setNfSugars(newMeal.getNfSugars() + food.getNfSugars());
newMeal.setNfTotalCarbohydrate(newMeal.getNfTotalCarbohydrate() + food.getNfTotalCarbohydrate());
newMeal.setNfTotalFat(newMeal.getNfTotalFat() + food.getNfTotalFat());
newMeal.setServingWeightGrams(newMeal.getServingWeightGrams() + food.getServingWeightGrams());
/*if(! productService.ifExists(food.getFoodName())) */ productService.save(food);
}
return mealService.save(newMeal);
}
You probably don't need to invoke productService.save(food) at the end of your for loop in MealManager.
You can try adding some utility methods in the Meal class, to keep the relationship in sync, as described in this article.
So, in your Meal class, you can add a method like
public void addProduct(Product product) {
foodList.add(product);
product.getMeals().add(this);
}
and call this method inside the for loop in MealManager, instead of simply calling newMeal.getFoodList().add(y).
Because you have CascadeType.MERGE defined for ManyToMany, the relationship will then be synchronized in both entities.
Other observations:
I can't see what the parseFoodToProduct method is doing, but assuming it retrieves the necessary products from the db, you should mark the saveMeal method as #Transactional
you're looping 2 times through the productList in saveMeal... once with stream().forEach() and once with the enhanced for... I'd keep only the enhanced for in this context

org.hibernate.MappingException: Could not determine type for: java.util.List for Hierarchy Ref Cursor function result

I'm trying to call a procedure function in DB and to mapped the Hierarchy answer to entity class using hibernate.The entities that I wrote suppose to represent the result structure that is returned from a ref cursor function.
The result of the function has a property which is a list of objects and inside that object there is also a property that is also a list of another objects.
On application startup I get the MappingException as I wrote in the title above.
I tried to add the annotation #OneToMany but it is not working because it is not looking at tables in DB.
Again, the entities represent the function result and not select from table tables.
Someone has any idea of any annotation that could prevent from this exeception to araise in the application startup?
My Entities:
Main Entity that call to procedure function (rc):
#NamedNativeQuery(name = "GetDeliveryOptionsRC.runFunction",
query = "{ ? = call fn_get_delivery_options_rc_dev(:i_account_number,:i_work_order_number,:i_task_id,:i_task_type,:i_content_type_code,:i_sap_operator_code)}", resultClass = GetDeliveryOptionsRC.class,
hints = {#QueryHint(name = "org.hibernate.callable", value = "true")})
#Entity
#XmlRootElement(name = "GetDeliveryOptionsRC")
public class GetDeliveryOptionsRC implements Serializable {
#Id
private Long rownum;
#Column(name = "ACCOUNT_NUMBER")private Long accountNumber;
#Column(name = "TASK_TYPE")private Long taskType;
#Column(name = "CONTENT_TYPE")private String contentType;
#Column(name = "CONTENT_TYPE_CODE")private Long contentTypeCode;
#Column(name = "MESSAGE_CODE")private Long messageCode;
#Column(name = "MESSAGE_ERROR_CODE")private Long messageErrorCode;
#Column(name = "MESSAGE_ERROR_DESCR")private String messageErrorDescr;
#Column(name = "DELIVERY_OPTIONS")private List<DeliveryOptionsRC> deliveryOptions;
//getters & setters
}
Delivery Options Entity:
#Entity
#XmlRootElement(name = "DeliveryOptions")
public class DeliveryOptionsRC implements Serializable {
#Id
#Column(name = "DELIVERY_TYPE") private String deliveryType;
#Column(name = "DELIVERY_DESCR") private String deliveryDescr;
#Column(name = "PRICE") private Double price;
#Column(name = "EXISTS_FLAG") private String existFlag;
#Column(name = "IS_VALID") private String isValid;
#Column(name = "IS_SAP_ORDER") private String isSapOrder;
#Column(name = "IS_OTHER_ADDRESS") private String isOtherAddress;
#Column(name = "IS_SCHEDULE_NEEDED") private String isScheduledNeeded;
#Column(name = "PICKUP_SOURCE") private String pickupSource;
#OneToMany(targetEntity=ChargeJobs.class, mappedBy="deliveryOptionsRC", fetch=FetchType.EAGER)
#Column(name = "CHARGE_JOBES") private List<ChargeJobs> chargeJobs;
//getters & setters
}
Charge Jobs Entity:
#Entity
#XmlRootElement(name = "ChargeJobs")
public class ChargeJobs implements Serializable {
#Column(name = "JOB_OFFER_ID") private Long jobOfferId;
#Id
#Column(name = "JOB_CODE") private String jobCode;
#Column(name = "PRICE") private Double price;
#Column(name = "QUANTITY") private Long quantity;
//getters & setters
}
The RC function:
CREATE OR REPLACE FUNCTION YES_SIMPLE.fn_get_delivery_options_rc_dev (i_account_number NUMBER,
i_work_order_number NUMBER ,
i_task_id NUMBER ,
i_task_type NUMBER,
i_content_type_code NUMBER,
i_sap_operator_code NUMBER
)
RETURN sys_refcursor
is
out_ref sys_refcursor ;
ret tr.delivery_options_list_t;
xml sys.xmltype;
begin
ret:= TR.fn_get_delivery_options (p_account_number => i_account_number,
p_work_order_number =>i_work_order_number,
p_task_id =>i_task_id,
p_task_type =>i_task_type,
p_content_type_code =>i_content_type_code,
p_sap_operator_code => i_sap_operator_code) ;
open out_ref for
select ret.Account_number Account_number
,ret.Task_Type Task_Type,
ret.content_type content_type,
ret.content_type_code content_type_code,
ret.message_code message_code,
ret.message_error_code message_error_code,
ret.message_error_descr message_error_descr
,cursor(select DELIVERY_TYPE ,
DELIVERY_DESCR ,
PRICE ,
EXISTS_FLAG ,
IS_VALID ,
IS_SAP_ORDER ,
IS_OTHER_ADRESS ,
IS_SCHEDULE_NEEDED ,
PICKUP_SOURCE,
cursor(select * from(select * from(select * from table(select ret.delivery_options from dual) ))) charge_jobs
from table(select ret.delivery_options from dual) ) delivery_options
from dual;
return out_ref;
end;
Getting the following result:
ROWNUM 1
ACCOUNT_NUMBER 13
TASK_TYPE 1
CONTENT_TYPE OTT
CONTENT_TYPE_CODE 2
MESSAGE_CODE 98
MESSAGE_ERROR_CODE 98
MESSAGE_ERROR_DESCR
DELIVERY_OPTIONS <Cursor>
DELIVERY_TYPE T
DELIVERY_DESCR Tech
PRICE 0
EXISTS_FLAG N
IS_VALID Y
IS_SAP_ORDER N
IS_OTHER_ADRESS N
IS_SCHEDULE_NEEDED Y
PICKUP_SOURCE
CHARGE_JOBS <Cursor>
JOB_OFFER_ID 900310
JOB_CODE D80
PRICE 0
QUANTITY 1

GET transient field with zero int value in java spring data

We're making get requests through a controller. The model contains transient fields that are set in the controller. Only int fields that are not null or >0 are being returned by the controller. How can I allow a transient field to return a 0 value, as this is meaningful. In this case the transient fields are 'sentenceStart' and 'sentenceEnd'.
Controller:
#RequestMapping(value = "/{match_id}", method = RequestMethod.GET)
public Match getMatch(#PathVariable("match_id") long matchId) {
long start = System.currentTimeMillis();
LOGGER.info("REQUESTED RETRIEVAL OF MATCH WITH ID: " + matchId);
Match match = matchRepository.findOneById(matchId);
match.setActualText(matchRepository.getText(match.getId()));
match.setSentenceStart(matchRepository.getSentenceStart(match.getId()));
match.setSentenceEnd(matchRepository.getSentenceEnd(match.getId()));
match.setSentenceID(matchRepository.getSentenceId(match.getId()));
long end = System.currentTimeMillis();
LOGGER.info("DONE. TOOK " + (end - start) + " MILLISECONDS.");
return match;
} //getMatch()
Repository:
public interface MatchRepository extends JpaRepository<Match, Long>, JpaSpecificationExecutor<Match> {
#Query(value = "SELECT match_in_sentence_start FROM vTextMatch where match_id = :m_id LIMIT 1",
nativeQuery = true)
int getSentenceStart(#Param("m_id") long matchId);
#Query(value = "SELECT match_in_sentence_end FROM vTextMatch where match_id = :m_id LIMIT 1",
nativeQuery = true)
int getSentenceEnd(#Param("m_id") long matchId);
}
Model:
#Entity
#Table(name = "match_term")
#JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Match {
#Id
#GeneratedValue
#Column(name = "match_id", nullable = false)
private Long id;
#Column(name = "document_id", nullable = false)
private Long documentId;
#Column(name = "document_start")
private Integer documentStart;
#Column(name = "document_end")
private Integer documentEnd;
#Column(name = "is_meta", nullable = false)
private Boolean isMeta;
#Column(name = "date_inserted", nullable = false)
private Timestamp dateInserted;
#Transient
private String actualText;
#Transient
private int sentenceStart;
#Transient
private int sentenceEnd;
#Transient
private int sentenceID;
/*
|-------------------|
| AUXILIARY METHODS |
|-------------------|
*/
/*
|-------------------|
|SETTERS ANG GETTERS|
|-------------------|
*/
public int getSentenceStart() {
return sentenceStart;
}
public void setSentenceStart(int sentenceStart) {
this.sentenceStart = sentenceStart;
}
public int getSentenceEnd() {
return sentenceEnd;
}
public void setSentenceEnd(int sentenceEnd) {
this.sentenceEnd = sentenceEnd;
}
}
You should investigate line containing #JsonInclude(JsonInclude.Include.NON_EMPTY) - http://fasterxml.github.io/jackson-annotations/javadoc/2.0.0/com/fasterxml/jackson/annotation/JsonInclude.Include.html#NON_EMPTY
I would suggest slightly change your design and introduce some message type. You could avoid polluting your domain class with the not needed stuff.

How To Query Relationship Between Three Entities in Spring JPA

I am working on my senior project and my group's client has required that we use Spring Boot, which none of us are familiar with. Right now I'm working on making a paginated, sortable list that will show a logged in user the visits that are associated with their user id. Our models are as follows:
#Entity
#Table(name="users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#JsonView(View.User.class)
private long id;
#Column(name = "full_name")
#NotNull
#JsonView(View.User.class)
private String fullName;
#Column(name = "is_manager")
#NotNull
private boolean isManager;
#ManyToMany(cascade = CascadeType.ALL, mappedBy = "users")
private Set<Visit> visits;
#OneToMany(cascade=CascadeType.ALL, mappedBy="user")
private Set<VisitEntry> visitEntries;
-
#Entity
#Table(name="visits")
public class Visit implements Iterable<VisitEntry> {
static final public String INSPECTION_TYPE_FULL = "Full Inspection";
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#JsonView(View.Visit.class)
private long id;
#Column(name = "visit_number")
#NotNull
#JsonView(View.Visit.class)
private int visitNumber;
#ManyToOne(cascade=CascadeType.ALL)
#NotNull
#JsonView(View.Visit.class)
private Provider provider;
#ManyToOne(cascade=CascadeType.ALL)
private User leader;
#ManyToMany(cascade = {CascadeType.ALL})
#JoinTable(name="users_visits",
joinColumns={#JoinColumn(name="VISIT_ID")},
inverseJoinColumns = #JoinColumn(name = "USER_ID")
)
private Set<User> users;
#OneToMany(cascade=CascadeType.ALL, mappedBy="visit")
#JsonView(View.Visit.class)
#JsonManagedReference
private List<VisitEntry> visitEntries = new ArrayList<>();
#Column(name = "open")
#NotNull
private boolean open;
-
#Entity
#Table(name="visit_entries")
public class VisitEntry {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#JsonView(View.Visit.class)
private long id;
#Column(name = "pre_inspection")
#JsonView(View.Visit.class)
private int preInspectionPrepHours;
#ManyToOne(cascade = CascadeType.ALL)
#NotNull
#JsonBackReference
private Visit visit;
#ManyToOne(cascade=CascadeType.ALL)
#NotNull
#JsonView(View.Visit.class)
private User user;
So we have visits which have many visit entries and each visit entry has a user. What I need is to get all visits associated with a user.
Unfortunately after each reading various tutorials my teammates and I are incredibly confused and have entirely different ideas on how to do this, none of which have actually worked. Based on this question (Joining two table entities in Spring Data JPA) I created the relationship between visits and users thinking that I would then be able to use Page<Visit> findByUsers(User user, Pageable pageable); in my repository, but I always get an empty set. So now we've ended up with this ugly piece of code that works as far as paginating but does not do any sorting:
#RequestMapping(value="/visits/{pageNum}/{sort}/{direction}", method= RequestMethod.GET)
public String visits(#PathVariable int pageNum,
#PathVariable String sort,
#PathVariable String direction,
Model model,
HttpServletRequest request) {
User currentUser = getUser(request);
final int pageSize = 10;
Pageable pageable;
//get direction info from parameters and convert to Sort.Direction enum
if (direction.compareTo("asc") == 0)
pageable = new PageRequest(pageNum - 1, pageSize, Sort.Direction.ASC, sort);
else
pageable = new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, sort);
//get pageable list of visits dependant on current user
Page<Visit> visits;
if(currentUser.isManager()) {
visits = visitRepo.findAll(pageable);
}
else {
//visits = visitRepo.findByUser_Id(currentUser, pageable);
List<VisitEntry> entries = visitEntryDao.findByUser(currentUser);
List<Visit> visitList = new ArrayList<>();
for (int x = 0; x < entries.size(); x++) {
visitList.add(entries.get(x).getVisit());
}
int offset = (pageNum - 1) * pageSize;
int offsetEnd = offset + 10;
if (offsetEnd > visitList.size())
offsetEnd = visitList.size();
List<Visit> content = visitList.subList(offset, offsetEnd);
visits = new PageImpl<Visit>(content, pageable, visitList.size());
}
edu.ewu.timetrackers.util.Page[] pages = new edu.ewu.timetrackers.util.Page[visits.getTotalPages()];
for (int i = 0; i < visits.getTotalPages(); i++) {
pages[i] = new edu.ewu.timetrackers.util.Page(i + 1, pageNum == i + 1);
}
//add visit and number of pages to model
model.addAttribute("visits", visits);
model.addAttribute("pageCount", visits.getTotalPages());
//add sorting and paging info to model
model.addAttribute("pageNum", pageNum);
model.addAttribute("sort", sort);
model.addAttribute("direction", direction);
model.addAttribute("pages", pages);
//below attributes determine previous and next buttons for pagination
if (pageNum > 1)
model.addAttribute("notFirst", pageNum - 1);
if (pageNum < visits.getTotalPages())
model.addAttribute("notLast", pageNum + 1);
return "visits";
}
Can anyone clear up the correct way to do this? We've tried asking around and not found anyone in our community that uses Spring that can help us understand what we're missing here.
Thanks!

HQL - comparing dates and objects

So I have the following code:
Query query = session.createQuery("select p.festivalDay from Performance p where p.startingTimestamp < :startingTimestamp " +
"and p.endingTimestamp> :endingTimestamp" +
"and p.artist= :artist");
query.setTimestamp("beginningTimestamp", cal.getTime());
cal.set(endHour, endMonth, endDay, endHour, endMinute);
query.setTimestamp("endingTimestamp", cal.getTime());
query.setParameter("artist", a);
For some reason this query is never returning any results, artist is an object from the Class Artist, festivalDay is one of FestivalDay.
Both the timestamp comparisons and artist comparisons seem to be failing (I tried the query with just the timestamps and I tried it with just the artist). ("a" is obviously an Artist object)
This is my model for Performance:
#Entity
#Table(name = "T_Performance")
public class Performance{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private Date startingTimestamp;
private Date endingTimestamp;
private Date soundCheckUur;
#ManyToOne
#Cascade(org.hibernate.annotations.CascadeType.ALL)
#JoinColumn(name = "podiumId")
private Podium podium;
#ManyToOne
#Cascade(org.hibernate.annotations.CascadeType.ALL)
#JoinColumn(name = "artistId", nullable = false)
private Artist artist;
#ManyToOne
#Cascade(org.hibernate.annotations.CascadeType.ALL)
#JoinColumn(name = "festivalDayId", nullable = false)
private FestivalDay festivalDay;
public Optreden(){
}
public Optreden(Date startingTimestamp, Date endingTimestamp, Date soundCheckHour) {
this.startingTimestamp = startingTimestamp;
this.endingTimestamp = endingTimestamp;
this.soundCheckHour = soundCheckHour;
}
public void setPodium(Podium podium) {
this.podium = podium;
}
public void setArtist(Artist artist) {
this.artist = artist;
}
public void setFestivalDay(FestivalDay festivalDay) {
this.festivalDay = festivalDay;
}
}
There is nothing wrong with my model, I have changed some names to their English versions so if you think you spot an error in the model I probably just forgot to translate it.
I fixed it! I forgot that December is the 11th month to Java and not 12th... :(

Categories

Resources