I am trying to fetch list of train entities using source and destination properties of route entity which has one to many relationship with each other. The train table having route id as foreign key. The table names are route and train respectively. Please help me as the query is throwing java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List com.infyrail.app.repository.RouteRepository.findBySourceDestination(java.lang.String,java.lang.String)!
RouteRepository:
public interface RouteRepository extends JpaRepository<RouteEntity, Integer> {
#Query("SELECT t FROM train t JOIN route r WHERE r.source=?1 AND r.destination=?2")
public List<TrainEntity> findBySourceDestination(String source,String destination);
}
RouteEntity:
#Entity
#Table(name="route")
public class RouteEntity {
#Id
#GenericGenerator(name="route_id",
strategy="com.infyrail.app.generator.RouteIdGenerator")
#GeneratedValue(generator = "route_id")
#Min(value = 100)
#Max(value = 999)
Integer id;
String source;
String destination;
#OneToMany(mappedBy = "route",
cascade=CascadeType.ALL,orphanRemoval = true)
private List<TrainEntity> trainList;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public List<TrainEntity> getTrainList() {
return trainList;
}
public void setTrainList(List<TrainEntity> trainList) {
this.trainList = trainList;
}
}
TrainEntity:
#Entity
#Table(name="train")
public class TrainEntity {
//#GeneratedValue(strategy = GenerationType.IDENTITY)
#Id
#GenericGenerator(name="train_id",
strategy="com.infyrail.app.generator.TrainIdGenerator")
#GeneratedValue(generator = "train_id")
#Min(value = 100)
#Max(value = 999)
Integer id;
String trainName;
String arrivalTime;
String departureTime;
Double fare;
#ManyToOne(fetch = FetchType.LAZY)
#Autowired
RouteEntity route;
public RouteEntity getRoute() {
return route;
}
public void setRoute(RouteEntity route) {
this.route = route;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTrainName() {
return trainName;
}
public void setTrainName(String trainName) {
this.trainName = trainName;
}
public String getArrivalTime() {
return arrivalTime;
}
public void setArrivalTime(String arrivalTime) {
this.arrivalTime = arrivalTime;
}
public String getDepartureTime() {
return departureTime;
}
public void setDepartureTime(String departureTime) {
this.departureTime = departureTime;
}
public Double getFare() {
return fare;
}
public void setFare(Double fare) {
this.fare = fare;
}
}
Here is the problem. Your query should define the table bean name instead of the actual table name.
In your case you should use TrainEntity instead of train and RouteEntity instead of route.
public interface RouteRepository extends JpaRepository<RouteEntity, Integer> {
#Query("SELECT t FROM TrainEntity t JOIN RouteEntity r WHERE r.source=?1 AND r.destination=?2")
public List<TrainEntity> findBySourceDestination(String source,String destination);
}
Related
I wanted to pass list of train entities to route entity using RouteDto and TrainDto. But the train data is not persisting in db. I also want the the ids to be auto generated. I am using post method in controller class and calling save method from repository using RouteService.
RouteDto.java
public class RouteDto {
#GeneratedValue
#Min(value = 100)
#Max(value = 999)
int id;
#NotEmpty(message="Source cannot be null")
#Pattern(regexp="^[A-Za-z]+$")
String source;
#NotEmpty(message="Destination cannot be null")
#Pattern(regexp="^[A-Za-z]+$")
String destination;
#OneToMany
// #NotEmpty(message="Train List cannot be null")
private List<TrainDto> trainList;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public List<TrainDto> getTrainList() {
return trainList;
}
public void setTrainList(List<TrainDto> trainList) {
this.trainList = trainList;
}
public RouteEntity createEntity() {
RouteEntity routeEntity=new RouteEntity();
routeEntity.setId(this.getId());
routeEntity.setSource(this.getSource());
routeEntity.setDestination(this.getDestination());
List<TrainEntity> trainEntityList=new ArrayList<TrainEntity>();
List<TrainDto> trainDtoList=this .getTrainList();
if(trainDtoList!=null) {
for(TrainDto train:trainDtoList) {
trainEntityList.add(train.createEntity());
}
}
routeEntity.setTrainList(trainEntityList);
return routeEntity;
}
}
TrainDto.java
public class TrainDto {
int id;
String trainName;
String arrivalTime;
String departureTime;
Double fare;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTrainName() {
return trainName;
}
public void setTrainName(String trainName) {
this.trainName = trainName;
}
public String getArrivalTime() {
return arrivalTime;
}
public void setArrivalTime(String arrivalTime) {
this.arrivalTime = arrivalTime;
}
public String getDepartureTime() {
return departureTime;
}
public void setDepartureTime(String departureTime) {
this.departureTime = departureTime;
}
public Double getFare() {
return fare;
}
public void setFare(Double fare) {
this.fare = fare;
}
public TrainEntity createEntity() {
TrainEntity trainEntity=new TrainEntity();
trainEntity.setId(this.getId());
trainEntity.setTrainName(this.getTrainName());
trainEntity.setArrivalTime(this.getArrivalTime());
trainEntity.setDepartureTime(this.getDepartureTime());
trainEntity.setFare(this.getFare());
return trainEntity;
}
}
RouteService.java
#Service
public class RouteService {
#Autowired
RouteRepository routeRepository;
public int createRoute(RouteDto route) {
RouteEntity routeEntity=route.createEntity();
routeRepository.save(routeEntity);
return routeEntity.getId();
}
}
RouteController.java
#RestController
public class RouteController {
#Autowired
RouteService routeService;
#PostMapping("/routes")
public ResponseEntity<Integer> createRoute(#Validated #RequestBody RouteDto routeDto){
int routeId=routeService.createRoute(routeDto);
return new ResponseEntity<>(routeId, HttpStatus.OK);
}
}
POST JSON sent:
{
"id":102,
"source":"Howrah",
"destination":"Sonarpur",
"trainlist":[{
"id":"203"
"trainame":"Sonarpur Local",
"arrivaltime":"00:00:00",
"departuretime":"00:00:00",
"fare":"30.00"
}]
}
RouteEntity.java
#Entity
#Table(name="route")
public class RouteEntity {
#Id
int id;
String source;
String destination;
#OneToMany
private List<TrainEntity> trainList;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public List<TrainEntity> getTrainList() {
return trainList;
}
public void setTrainList(List<TrainEntity> trainList) {
this.trainList = trainList;
}
}
TrainEntity.java
#Entity
#Table(name="train")
public class TrainEntity {
#Id
#GeneratedValue
int id;
String trainName;
String arrivalTime;
String departureTime;
Double fare;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTrainName() {
return trainName;
}
public void setTrainName(String trainName) {
this.trainName = trainName;
}
public String getArrivalTime() {
return arrivalTime;
}
public void setArrivalTime(String arrivalTime) {
this.arrivalTime = arrivalTime;
}
public String getDepartureTime() {
return departureTime;
}
public void setDepartureTime(String departureTime) {
this.departureTime = departureTime;
}
public Double getFare() {
return fare;
}
public void setFare(Double fare) {
this.fare = fare;
}
}
The train list is coming empty.
In RouteEntity table add #GeneratedValue on id to generate id
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
int id;
And add CascadeType.ALL so that trainList persist
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
private List<TrainEntity> trainList;
MenuModel
#Entity
#Table(name="M_MENU", uniqueConstraints={#UniqueConstraint(columnNames={"NAME"})})
public class MenuModel {
private Integer id;
private String code;
private String name;
private String controller;
private Integer parent_id;
#Id
#Column(name="ID")
#GeneratedValue(strategy=GenerationType.TABLE, generator="M_MENU")
#TableGenerator(name="M_MENU", table="M_SEQUENCE",
pkColumnName="SEQUENCE_NAME", pkColumnValue="M_MENU_ID",
valueColumnName="SEQUENCE_VALUE", allocationSize=1, initialValue=0
)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name="CODE")
public String getCode() {
return code;
}
public void setCode(String kode) {
this.code = kode;
}
#Column(name="NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name="CONTROLLER")
public String getController() {
return controller;
}
public void setController(String controller) {
this.controller = controller;
}
#Column(name="PARENT_ID")
public Integer getParent_id() {
return parent_id;
}
public void setParent_id(Integer parent_id) {
this.parent_id = parent_id;
}
}
UserAccessModel
#Entity
#Table(name="M_USER_ACCESS")
public class UserAccessModel {
private Integer id;
//join table role
private Integer idRole;
private RoleModel roleModel;
//join table menu
private Integer idMenu;
private MenuModel menuModel;
#Id
#Column(name="ID")
#GeneratedValue(strategy=GenerationType.TABLE, generator="M_USER_ACCESS")
#TableGenerator(name="M_USER_ACCESS", table="M_SEQUENCE",
pkColumnName="SEQUENCE_NAME", pkColumnValue="M_USER_ACCESS_ID",
valueColumnName="SEQUENCE_VALUE", allocationSize=1, initialValue=0
)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name="ID_ROLE")
public Integer getIdRole() {
return idRole;
}
public void setIdRole(Integer idRole) {
this.idRole = idRole;
}
#ManyToOne
#JoinColumn(name="ID_ROLE", nullable=true, updatable=false, insertable=false)
public RoleModel getRoleModel() {
return roleModel;
}
public void setRoleModel(RoleModel roleModel) {
this.roleModel = roleModel;
}
#Column(name="ID_MENU")
public Integer getIdMenu() {
return idMenu;
}
public void setIdMenu(Integer idMenu) {
this.idMenu = idMenu;
}
#ManyToOne
#JoinColumn(name="ID_MENU", nullable=true, updatable=false, insertable=false)
public MenuModel getMenuModel() {
return menuModel;
}
public void setMenuModel(MenuModel menuModel) {
this.menuModel = menuModel;
}
}
MenuDaoImpl
#Override
public List<MenuModel> searchByRole(Integer idRole) {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
List<MenuModel> menuModelListRole = new ArrayList<MenuModel>();
Criteria userAccessCriteria = session.createCriteria(UserAccessModel.class,"UA");
Criteria menuCriteria = userAccessCriteria.createCriteria("menuModel","M");
userAccessCriteria.add(Restrictions.eq("idRole", ""+idRole+""));
ProjectionList properties = Projections.projectionList();
properties.add(Projections.property("M.id"));
properties.add(Projections.property("M.name"));
properties.add(Projections.property("M.code"));
properties.add(Projections.property("M.controller"));
properties.add(Projections.property("M.parent_id"));
menuCriteria.setProjection(properties);
menuModelListRole = menuCriteria.list();
return menuModelListRole;
}
I want to get result of the following sql:
select M.ID ID, M.NAME NAME, M.CODE CODE, M.CONTROLLER CONTROLLER,
M.PARENT_ID PARENT from M_MENU M join M_USER_ACCESS UA on UA.ID_MENU
= M.ID where UA.ID_ROLE="+idRole+"
I got error in method searchByRole in menuModelListRole = menuCriteria.list();. How can i resolve the problem?
Here private Integer idRole; is of Integer type, but you are passing idRole as String in Restrictions.eq("idRole", ""+idRole+""). SO you are getting java.lang.String cannot be cast to java.lang.Integer in Spring
Changing you restriction value from Restrictions.eq("idRole", ""+idRole+"") to Restrictions.eq("idRole", idRole) should solve your problem.
i have two entity classes named Qa.java and Answeres.java
my Qa entity consists of lists of answers.
Qa.Java
#Entity
#Table(name = "qa")
public class Qa {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
private String question;
private String type;
private String description;
private String param;
private int maxlength;
#OneToMany(mappedBy = "qa", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Answers> answersList = new ArrayList<>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getParam() {
return param;
}
public void setParam(String param) {
this.param = param;
}
public int getMaxlength() {
return maxlength;
}
public void setMaxlength(int maxlength) {
this.maxlength = maxlength;
}
public List<Answers> getAnswersList() {
return answersList;
}
public void setAnswersList(List<Answers> answersList) {
this.answersList = answersList;
}
}
Answers.java
#Entity
#Table(name = "answers")
public class Answers {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String ans_label;
private int ans_value;
private int ans_weightage;
private int is_default;
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "question_id", referencedColumnName = "id",nullable = false)
private Qa qa;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAns_label() {
return ans_label;
}
public void setAns_label(String ans_label) {
this.ans_label = ans_label;
}
public int getAns_value() {
return ans_value;
}
public void setAns_value(int ans_value) {
this.ans_value = ans_value;
}
public int getAns_weightage() {
return ans_weightage;
}
public void setAns_weightage(int ans_weightage) {
this.ans_weightage = ans_weightage;
}
public int getIs_default() {
return is_default;
}
public void setIs_default(int is_default) {
this.is_default = is_default;
}
public Qa getQa() {
return qa;
}
public void setQa(Qa qa) {
this.qa = qa;
}
}
My controller from where i am trying to insert data.
TableDataController.java
#Controller
public class TabletDataController {
#Autowired
QaRepository qaRepository;
#RequestMapping(value = "/saveApiData", method = RequestMethod.GET)
public void saveApiData(){
Qa qa = new Qa();
qa.setParam("");
qa.setType("input_spinner");
qa.setDescription("");
qa.setQuestion("व्यक्तिको पहिलो नाम ?");
ArrayList<Answers> answersArrayList = new ArrayList<>();
Answers answers = new Answers();
answers.setAns_label("नेपाली");
answers.setAns_value(1);
answers.setAns_weightage(0);
answers.setIs_default(0);
Answers answers1 = new Answers();
answers1.setAns_label("english");
answers1.setAns_value(2);
answers1.setAns_weightage(2);
answers1.setIs_default(2);
Answers answers2 = new Answers();
answers2.setAns_label("japense");
answers2.setAns_value(3);
answers2.setAns_weightage(3);
answers2.setIs_default(3);
answersArrayList.add(answers);
answersArrayList.add(answers1);
answersArrayList.add(answers2);
qa.setAnswersList(answersArrayList);
answers.setQa(qa);
qaRepository.save(qa);
}
}
my qaRepository extends JpaRepository. so whenever i call this api only first object i.e
Answers answers = new Answers();
answers.setAns_label("नेपाली");
answers.setAns_value(1);
answers.setAns_weightage(0);
answers.setIs_default(0);
is saved. how can i saved all the given list?
You have to set the qa object to answers1 and answers2 objects as well and not just for the answers object.
These are my model classes:
Film.java
#Entity
public class Film {
private Integer id;
private String title;
private List<FilmActor> filmActors;
#OneToMany(mappedBy = "film")
public List<FilmActor> getFilmActors() {
return filmActors;
}
public void setFilmActors(List<FilmActor> filmActors) {
this.filmActors = filmActors;
}
}
Actor.java
#Entity
public class Actor {
private Integer id;
private String firstname;
private String lastname;
private List<FilmActor> filmActors;
#OneToMany(mappedBy = "actor")
public List<FilmActor> getFilmActors() {
return filmActors;
}
public void setFilmActors(List<FilmActor> filmActors) {
this.filmActors = filmActors;
}
}
And this is the Join Table Entity:
#Entity
#Table(name = "film_actor")
public class FilmActor {
private FilmActorPK id;
private Film film;
private Actor actor;
private Timestamp lastUpdate;
#EmbeddedId
public FilmActorPK getId() {
return id;
}
public void setId(FilmActorPK id) {
this.id = id;
}
#ManyToOne
#MapsId("film")
#JoinColumn(name = "film_id")
public Film getFilm() {
return film;
}
public void setFilm(Film film) {
this.film = film;
}
#ManyToOne
#MapsId("actor")
#JoinColumn(name = "actor_id")
public Actor getActor() {
return actor;
}
public void setActor(Actor actor) {
this.actor = actor;
}
#Column(name = "last_update")
public Timestamp getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(Timestamp lastUpdate) {
this.lastUpdate = lastUpdate;
}
}
and the Primary Key class:
#Embeddable
public class FilmActorPK implements Serializable {
private int actorId;
private int filmId;
#Column(name = "actor_id")
public int getActorId() {
return actorId;
}
public void setActorId(int actorId) {
this.actorId = actorId;
}
#Column(name = "film_id")
public int getFilmId() {
return filmId;
}
public void setFilmId(int filmId) {
this.filmId = filmId;
}
}
So I want to find films where 2 given actors acts. This is what I have:
#Override
public Collection<Film> filmsActorsTogether(Actor a, Actor b) {
final List<Film> filmsOfActorA = filmsOfActor(a);
final List<Film> filmsOfActorB = filmsOfActor(b);
final Collection<Film> intersection = CollectionUtils.intersection(filmsOfActorA, filmsOfActorB);
return intersection;
}
#Override
public List<Film> filmsOfActor(Actor actor) {
final EntityManager entityManager = persistenceUtil.getEntityManager();
final Actor persistentActor = entityManager.find(Actor.class, actor.getId());
final ArrayList<Film> films = new ArrayList<Film>();
for (FilmActor filmActor : persistentActor.getFilmActors()) {
films.add(filmActor.getFilm());
}
entityManager.close();
return films;
}
Is there any way to achieve this without fetching ALL films of 2 actors, and using filtering in memory? How do I get the Films directly from the DB with JQL?
Maybe there is something more elegant, but the following query should work:
select f from Film f where
(select count(fa.id) from FilmActor fa
where fa.film = f
and (fa.actor = :actor1 or fa.actor = :actor2)) = 2
Side note: your PK class should have a correct equals() and hashCode() methods
I want to convert the following query into HQL:
SELECT C.ID, E.DESCRIPTION as STATUS, E1.DESCRIPTION as SUBJECT
FROM CRED C
join CODE_EVN E
ON E.CODE = C.STATUS_CODE
AND E.SUBCODE = C.STATUS_SUBCODE
join CODE_EVN E1
ON E1.CODE = C.SUBJECT_CODE
AND E1.SUBCODE = C.SUBJECT_SUBCODE
I have two classes User and Codes with no mapping in between them, so how do I execute the following query in Hibernate?
I have tried out many things but nothing seems to work
These are my 2 bean classes:
User class:
#Entity
#Table(name="CRED")
public class User {
private String id;
private String STATUS_CODE;
private String STATUS_SUBCODE;
private String SUBJECT_CODE;
private String SUBJECT_SUBCODE;
#Id
#Column(name="ID")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setSTATUS_CODE(String sTATUS_CODE) {
STATUS_CODE = sTATUS_CODE;
}
public String getSTATUS_CODE() {
return STATUS_CODE;
}
public void setSTATUS_SUBCODE(String sTATUS_SUBCODE) {
STATUS_SUBCODE = sTATUS_SUBCODE;
}
public String getSTATUS_SUBCODE() {
return STATUS_SUBCODE;
}
public void setSUBJECT_CODE(String sUBJECT_CODE) {
SUBJECT_CODE = sUBJECT_CODE;
}
public String getSUBJECT_CODE() {
return SUBJECT_CODE;
}
public void setSUBJECT_SUBCODE(String sUBJECT_SUBCODE) {
SUBJECT_SUBCODE = sUBJECT_SUBCODE;
}
public String getSUBJECT_SUBCODE() {
return SUBJECT_SUBCODE;
}
}
Codes class:
#Entity
#Table(name="CODE_EVN")
public class Codes {
#Id
private String CODE;
private String SUBCODE;
private String DESCRIPTION;
public void setCODE(String cODE) {
CODE = cODE;
}
public String getCODE() {
return CODE;
}
public void setSUBCODE(String sUBCODE) {
SUBCODE = sUBCODE;
}
public String getSUBCODE() {
return SUBCODE;
}
public void setDESCRIPTION(String dESCRIPTION) {
DESCRIPTION = dESCRIPTION;
}
public String getDESCRIPTION() {
return DESCRIPTION;
}
}