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... :(
Related
I would like to be able to include an #Entity from another table using a foreign key. I'm following guides but I'm still confused and can't seem to get this working. The end goal would be something like this:
#Entity
#Table(name = "Labor", schema = "dbo", catalog = "database")
public class LaborEntity {
private int laborId;
private Timestamp laborDate;
private Integer jobNumber;
private Integer customerId;
//mapping of customer to labor
private CustomerEntity customer;
#Id
#Column(name = "LaborID", nullable = false)
public int getLaborId() {
return laborId;
}
public void setLaborId(int laborId) {
this.laborId = laborId;
}
#Basic
#Column(name = "LaborDate", nullable = true)
public Timestamp getLaborDate() {
return laborDate;
}
public void setLaborDate(Timestamp laborDate) {
this.laborDate = laborDate;
}
#Basic
#Column(name = "JobNumber", nullable = true)
public Integer getJobNumber() {
return jobNumber;
}
public void setJobNumber(Integer jobNumber) {
this.jobNumber = jobNumber;
}
#Basic
#Column(name = "CustomerID", nullable = true)
public Integer getCustomerId() {
return customerId;
}
public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}
#ManyToOne(targetEntity = CustomerEntity.class)
#NotFound(action = NotFoundAction.IGNORE)
#JoinColumn(name = "CustomerID", //in this table
referencedColumnName = "CustomerID", //from CustomerEntity
insertable = false, updatable = false,
foreignKey = #javax.persistence.ForeignKey(value = ConstraintMode.NO_CONSTRAINT))
public CustomerEntity getCustomer() {
return this.customer;
}
public void setCustomer(CustomerEntity customer) {
this.customer = customer;
}
Anyway, the end goal is to get the Customer data from the Customer table as part of the Labor entity so it can be accessed directly with something like getCustomerEntity(). I supposed I would have to accomplish it by querying first using a JOIN like so:
TypedQuery<LaborEntity> query = entityManager.createQuery(
"SELECT l FROM LaborEntity l " +
"INNER JOIN CustomerEntity c " +
"ON l.customerId = c.customerId " +
"WHERE l.laborDate = '" + date + "'", LaborEntity.class);
List<LaborEntity> resultList = query.getResultList();
And then I can simply access the Customer that's associated like so:
resultList.get(0).getCustomer().getCustomerName();
Am I dreaming or is this actually possible?
Yes, this is completely possible.
(I'm not sure about what was the question though - but assuming you only want get it working)
You query needs to be a JPQL, not an SQL. And the Join is different on JPQL:
"SELECT l FROM LaborEntity l " +
"JOIN l.customer c " +
"WHERE ... "
The join starts from the root entity and then you use the field name (not column).
You can also use JOIN FETCH, then the associated entity (customer) will be loaded in the same query. (that is, Fetch EAGER)
Other recommendations:
Don't concat the parameters like that date. Instead use setParameter.
You don't need those #Basic
You don't need that targetEntity = CustomerEntity.class. It'll be detected automatically.
I am learning spring data close projection. However, it does not give the expected results. This means, instead of the expected interface, it gives org.springframework.aop.framework.JdkDynamicAopProxy. I have researched this for days and I couldn't find the solution. I have attached my code as well.
Entity class - Agent
#Entity
#Table(name = "TBLDMS_AGENT")
public class Agent {
#Id
#Column(name = "AGENT_ID")
private long agentId;
#Column(name = "AGENT_NAME")
private String agentName;
#Column(name = "ADDRESS")
private String address;
#Column(name = "CONTACT_NO")
private String contactNo;
#Column(name = "STATUS")
private boolean status;
#Column(name = "PROFILE_ID")
private int profileId;
Repository - AgentRepository
#Repository
public interface AgentRepository extends JpaRepository<Agent, Long> {
#Query(value =
"SELECT AGENT_NAME, " +
" PROFILE_CODE " +
"FROM TBLDMS_AGENT " +
"WHERE CONTACT_NO = :number", nativeQuery = true)
List<AgentInformation> findByContactNumber(#Param("number") String number);
public static interface AgentInformation {
String getAgentName();
String getProfileCode();
}
}
Usage
com.dms.agentmanagementservice.persister.AgentRepository.AgentInformation agent = agentRepository.findByContactNumber(number);
String agentName = agent.getAgentName();
String profileId = agent.getProfileCode();
But and getting null values for both agentName and profileId. Can someone tell me what I am doing wrong here?
Thank you very much in advance!
In my application, I am using Spring Data and hibernate as JPA provider to persist and read data.
I have top level Entity class:
#Entity
#Getter #Setter
#Table(name = "operation")
#Inheritance(strategy = InheritanceType.JOINED)
#EqualsAndHashCode(of = {"operationId"})
public abstract class Operation implements Serializable {
public static final int OPERATION_ID_LENGTH = 20;
#Id
#Column(name = "operation_id", length = OPERATION_ID_LENGTH, nullable = false, columnDefinition = "char")
private String operationId;
#Column(name = "operation_type_code")
#Getter(AccessLevel.NONE)
#Setter(AccessLevel.NONE)
private String operationTypeCode;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "begin_timestamp", nullable = false)
private Date beginTimestamp = new Date();
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "end_timestamp")
private Date endTimestamp;
#Column(name = "operation_number", length = 6, columnDefinition = "char")
private String operationNumber;
#Enumerated(EnumType.STRING)
#Column(name = "operation_status", length = 32, nullable = false)
private OperationStatus status;
#ManyToOne(optional = false)
#JoinColumn(name = "user_id")
private User user;
#ManyToOne
#JoinColumn(name = "terminal_id")
private Terminal terminal;
#Column(name = "training_mode", nullable = false)
private boolean trainingMode;
}
For inherited class I have corresponding repository:
public interface ConcreteOperationRepository extends JpaRepository<ConcreteOperation, String> {
#Query("SELECT o FROM ConcreteOperation o WHERE o.beginTimestamp BETWEEN :from AND :to AND o.status = :status AND o.terminal.deviceId = :deviceId AND o.trainingMode = :trainingMode")
Collection<ConcreteOperation> findOperations(#Param("from") Date startDay,
#Param("to") Date endDay,
#Param("status") OperationStatus status,
#Param("deviceId") String deviceId,
#Param("trainingMode") boolean trainingMode);
}
And I have integration test with following method:
#Transactional
#Test
public void shouldFindOperationByPeriodAndStatusAndWorkstationId() {
Date from = new Date(Calendar.getInstance().getTime().getTime());
List<String> terminalIds = loadTerminalIds();
List<OperationStatus> typeForUse = Arrays.asList(OperationStatus.COMPLETED,
OperationStatus.LOCKED, OperationStatus.OPEN);
int countRowsForEachType = 3;
int id = 100001;
for (String terminalId : terminalIds) {
for (OperationStatus status : typeForUse) {
for (int i = 0; i < countRowsForEachType; i++) {
concreteOperationRepository.save(createConcreteOperation(status, terminalId,
String.valueOf(++id)));
}
}
}
Date to = new Date(Calendar.getInstance().getTime().getTime());
for (String terminalId : terminalIds) {
for (OperationStatus status : typeForUse) {
Collection<ConcreteOperation> operations =
concreteOperationRepository.findOperations(from, to, status, terminalId, false);
assertEquals(countRowsForEachType, operations.size());
}
}
}
But this test fails when I using MySql database due to empty result (but passes when I switch to HSQLDB)
Also, this test passes if I put delay "Thread.sleep(1000)" for one second at the beginning of the test, just after the first line.
When I execute SQL from Hibernate log it gives me right result. What's wrong with my code?
In JPA, the Date requires a temporal hint. Normally, you could set the TemporalType when setting the JPA Query parameter:
query.setParameter("from", from), TemporalType.TIMESTAMP);
With Spring Data you need to use the #Temporal annotation, so your query becomes:
#Query("SELECT o FROM ConcreteOperation o WHERE o.beginTimestamp BETWEEN :from AND :to AND o.status = :status AND o.terminal.deviceId = :deviceId AND o.trainingMode = :trainingMode")
Collection<ConcreteOperation> findOperations(
#Param("from") #Temporal(TemporalType.TIMESTAMP) Date startDay,
#Param("to") #Temporal(TemporalType.TIMESTAMP) Date endDay,
#Param("status") OperationStatus status,
#Param("deviceId") String deviceId,
#Param("trainingMode") boolean trainingMode
);
I realized my problem. The problem was due to difference of precision between type of field in MySql (default timestamp precision cut of milliseconds) and Java date (with milliseconds)
I've altered my table:
ALTER TABLE transaction modify end_timestamp TIMESTAMP(6)
and that's solved my problem.
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
I fresh on spring technology and hibernate. Some days ago i create query getting all rows from table using repository. Today i was try get 2 fields from database. When i try read data form result list i getting Ljava.lang.Object; cannot be cast. This is my enity
#Entity
#Table(name = "cms")
public class Cms implements Serializable{
private static final long serialVersionUID = 1759832392332242809L;
#Id
#GeneratedValue
private Long id_page;
#Column(nullable = false)
private String title;
private String content;
#Temporal(TemporalType.DATE)
private Date createDate;
#Temporal(TemporalType.DATE)
private Date modifyDate;
#Column(nullable = true)
private int createBy;
#Column(nullable = true)
private int modifedBy;
#Column(nullable = false)
private Boolean inMenu;
public Cms(Long id_page, String title, String content, Date createDate,
Date modifyDate) {
this.id_page = id_page;
this.title = title;
this.content = content;
this.createDate = createDate;
this.modifyDate = modifyDate;
this.createBy = 1;
this.modifedBy = 1;
this.inMenu = true;
}
//getters setters to string
}
Repository
public interface CmsRepository extends Repository<Cms, Long>{
#Query("Select u.id_page,u.title from Cms u")
List<Cms> getMenu();
}
And takie this on controller
List<Cms> menus= cmsservice.menuAll();
System.out.println(menus.get(0).toString()); //error
Some one can explain me on example what is bad and how can fix this, this will helpfull for me.
Thats because you are retrieving individual properties - not the entire Cms Object.
I would use an instance of Query for this:
EntityManager em = emf.createEntityManager();
Query query = em.createQuery("Select u.id_page,u.title from Cms u");
List<Object[]> results = query.getResultList();
for(Object[] elements: results){
Long id = Long.valueOf(String.valueOf(elements[0]));
String title = String.valueOf(elements[1]);
}
SELECT NEW org.agoncal.javaee7.CustomerDTO(c.firstName, c.lastName, c.address.
street1)
FROM Customer c