Spring boot jpa/hibernate tables connection - java

professionals!
I have a question. What is a better idea to connect 2 tables in spring boot via ID? As an example: we have 2 tables client and books. Each client can borrow a book and the status of book will be changed.
I know how to make it in DB using SQL. But the question is, how to do this in jpa/hibernate.
I have an error of ManyToMany or OneToMany.....
#Entity
public class Book implements java.io.Serializable {
private static final long serialVersionUID = 1L;
#TableGenerator(name = "BOOK_GEN", allocationSize = 1)
#Id
#GeneratedValue(generator = "BOOK_GEN")
private int id;
private String book_name;
private String ISBN;
private String publish_year;
private String publisher;
private Boolean status;
#OneToMany(mappedBy="book" ,cascade=CascadeType.ALL , fetch = FetchType.LAZY)
private Collection<Client> authors =new ArrayList<Client>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBook_name() {
return book_name;
}
public void setBook_name(String book_name) {
this.book_name = book_name;
}
public String getISBN() {
return ISBN;
}
public void setISBN(String iSBN) {
ISBN = iSBN;
}
public String getPublish_year() {
return publish_year;
}
public void setPublish_year(String publish_year) {
this.publish_year = publish_year;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public Collection<Author> getAuthors() {
return authors;
}
public void setClients(Collection<Client> clients) {
this.clients = clients;
}}
#Entity
public class Client implements java.io.Serializable {
private static final long serialVersionUID = 1L;
#TableGenerator(name = "CLT_GEN", allocationSize = 1)
#Id
#GeneratedValue(generator = "CLT_GEN")
private int id;
private Boolean bookedstatus;
private Boolean bookstatus;
#ManyToOne(fetch = FetchType.LAZY)
private Book book;
private String name ;
private String surname;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Boolean getBookedstatus() {
return bookedstatus;
}
public void setBookedstatus(Boolean bookedstatus) {
this.bookedstatus = bookedstatus;
}
public Boolean getBookstatus() {
return bookstatus;
}
public void setBookstatus(Boolean bookstatus) {
this.bookstatus = bookstatus;
}
}

Since you have mentioned "A client can borrow a book", one-to-one mapping should work the best for you. Please refer to the below code. Also you didn't mention the error you are facing with your current implementation.
#Entity
public class Book implements java.io.Serializable {
private static final long serialVersionUID = 1L;
#TableGenerator(name = "BOOK_GEN", allocationSize = 1)
#Id
#GeneratedValue(generator = "BOOK_GEN")
private int id;
private String book_name;
private String ISBN;
private String publish_year;
private String publisher;
private Boolean status;
#OneToOne(fetch = FetchType.LAZY, mappedBy = "book", cascade = CascadeType.ALL)
private Collection<Client> authors;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBook_name() {
return book_name;
}
public void setBook_name(String book_name) {
this.book_name = book_name;
}
public String getISBN() {
return ISBN;
}
public void setISBN(String iSBN) {
ISBN = iSBN;
}
public String getPublish_year() {
return publish_year;
}
public void setPublish_year(String publish_year) {
this.publish_year = publish_year;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public Collection<Client> getAuthors() {
return authors;
}
public void setAuthors(Collection<Client> authors) {
this.authors = authors;
}
}
#Entity
public class Client implements java.io.Serializable {
private static final long serialVersionUID = 1L;
#TableGenerator(name = "CLT_GEN", allocationSize = 1)
#Id
#GeneratedValue(generator = "CLT_GEN")
private int id;
private Boolean bookedstatus;
private Boolean bookstatus;
#OneToOne(fetch = FetchType.LAZY)
#PrimaryKeyJoinColumn
private Book book;
private String name ;
private String surname;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Boolean getBookedstatus() {
return bookedstatus;
}
public void setBookedstatus(Boolean bookedstatus) {
this.bookedstatus = bookedstatus;
}
public Boolean getBookstatus() {
return bookstatus;
}
public void setBookstatus(Boolean bookstatus) {
this.bookstatus = bookstatus;
}
}

Related

Error while passing value to list of entities using container entity using Post method

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;

How to resolve java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer in Spring

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.

OneToOne Bi-Directional Mapping using Hibernate annotation

I want a Bi-Directional mapping on my 2 Entities(PersonDetail,
PassportDetail) but it seems that it doesn't work fine. I want that
PersonDetail has a PassportId and PassportDetail has a PersonId as well.
My PersonDetail java Code
#Entity
#Table(name="persondetail")
public class PersonDetail {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="person_id")
private int id;
#Column(name="person_name")
private String name;
#Column(name="person_phone")
private long phone;
#OneToOne(mappedBy="person",cascade=CascadeType.ALL)
#JoinColumn(name="passport_id")
private PassportDetail passport;
public PassportDetail getPassport() {
return passport;
}
public void setPassport(PassportDetail passport) {
this.passport = passport;
}
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 long getPhone() {
return phone;
}
public void setPhone(long phone) {
this.phone = phone;
}
#Column(name="passport_id")
private int passort_id;
public int getPassort_id() {
return passort_id;
}
public void setPassort_id(int passort_id) {
this.passort_id = passort_id;
}
}
Here is my PassportDetail Java Code
#Entity
#Table(name="PassportDetail")
public class PassportDetail {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="passport_id")
private int id;
#Column(name="passport_number")
private String passportNumber;
#Column(name="country_name")
private String country;
#Column(name="issue_date")
#Temporal(TemporalType.DATE)
private Date date;
#OneToOne
#JoinColumn(name="person_id")
private PersonDetail person;
public String getPassportNumber() {
return passportNumber;
}
public void setPassportNumber(String passportNumber) {
this.passportNumber = passportNumber;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public PersonDetail getPerson() {
return person;
}
public void setPerson(PersonDetail person) {
this.person = person;
}
}
Here is the Output in MySql
Here is the Output of Both table as you can clearly see the problem i.e PersonDetail has a column named passport_id but it dosesn't have any value
Here is the insertion code
public class MappingMain {
public static void main(String[] args) {
PersonDetail person=new PersonDetail();
PassportDetail passport = new PassportDetail();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-mm-dd");
person.setName("Ankit");
person.setPhone(790148565);
passport.setCountry("india");
try {
passport.setDate(sdf.parse("2018-04-15"));
}
catch(Exception e)
{
}
passport.setPassportNumber("QUJMZ123");
passport.setPerson(person);
person.setPassport(passport);
PersonDao dao=new PersonDao();
dao.save(person);
}
Here is the DAO class
public class MappingDao {
SessionFactory sf=Util.getSessionFactory();
public void save(UserDemo user)
{
Session session=sf.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
session.close();
}
}

How to delete child records using Spring Data JPA

I am having alot of issues trying to delete child records using JPA. Consider the mappings below. I am trying to delete all the state data in the jobs table. When it is removed it will cascade all deletes down the chain. Here is the chain:
Job -> State -> TaskState -> Step
When I try to remove state from job table it is set to NULL. However it is not cascaded down the chain. How would I go about achieving this?
Here is how I am deleting the data:
#Transactional
public void runJob(Long id) throws IOException, JAXBException {
Job job = jobRepository.findOne(id);
if(job.getState() != null){
State stateObj = stateRepository.findOne(job.getState().getId());
stateObj.setTasks(null);
stateRepository.delete(stateObj);
}
job.setState(null);
jobRepository.save(job);
}
Jobs:
#Entity
#Table(name = "jobs")
public class Job implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "name")
private String name;
#Column(name = "description")
private String description;
#Temporal(TemporalType.TIMESTAMP)
private Date date;
#OneToOne
private Image image;
#OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
private State state;
#OneToMany
private List<Task> tasks;
#Column(name = "status")
#Enumerated(EnumType.STRING)
private JobStatusEnum status;
#ManyToMany
private List<Device> devices;
#OneToMany
private List<JobRun> runs;
#OneToMany
private List<Container> containers;
public Job() {
this.image = new Image();
this.status = JobStatusEnum.New;
this.devices = new ArrayList<>();
this.runs = new ArrayList<>();
this.containers = new ArrayList<>();
}
public Job(String name, String description, Date date, Image image, State state, List<Task> tasks, JobStatusEnum status, List<Device> devices, List<JobRun> runs, List<Container> containers) {
this.name = name;
this.description = description;
this.date = date;
this.image = image;
this.state = state;
this.tasks = tasks;
this.status = status;
this.devices = devices;
this.runs = runs;
this.containers = containers;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Image getImage() {
return image;
}
public void setImage(Image image) {
this.image = image;
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
public List<Task> getTasks() {
return tasks;
}
public void setTasks(List<Task> tasks) {
this.tasks = tasks;
}
public JobStatusEnum getStatus() {
return status;
}
public void setStatus(JobStatusEnum status) {
this.status = status;
}
public List<Device> getDevices() {
return devices;
}
public void setDevices(List<Device> devices) {
this.devices = devices;
}
public List<JobRun> getRuns() {
return runs;
}
public void setRuns(List<JobRun> runs) {
this.runs = runs;
}
public List<Container> getContainers() {
return containers;
}
public void setContainers(List<Container> containers) {
this.containers = containers;
}
}
State:
#Entity
#Table(name = "state")
public class State implements Serializable {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name="name")
private String name;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<TaskState> tasks;
public State() {
tasks = new ArrayList<>();
}
public State(Long id, String name, List<TaskState> tasks) {
this.id = id;
this.name = name;
this.tasks = tasks;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<TaskState> getTasks() {
return tasks;
}
public void setTasks(List<TaskState> tasks) {
this.tasks = tasks;
}
}
TaskState:
#Entity
#Table(name = "task_state")
public class TaskState implements Serializable {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "parent")
private Long parent;
#Column(name = "referenceid")
private Long referenceId;
#Column(name = "name")
private String name;
#Column(name = "status")
private TaskStatusEnum status;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Step> steps;
#Column(name = "maxAttempts")
private Integer maxAttempts;
#ManyToOne
#JsonIgnore
private State state;
public TaskState() {
status = TaskStatusEnum.New;
steps = new ArrayList<>();
maxAttempts = 5;
}
public TaskState(Long id, Long parent, Long referenceId, String name, TaskStatusEnum status, List<Step> steps, Integer maxAttempts) {
this();
this.id = id;
this.parent = parent;
this.referenceId = referenceId;
this.name = name;
this.status = status;
this.steps = steps;
this.maxAttempts = maxAttempts;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getParent() {
return parent;
}
public void setParent(Long parent) {
this.parent = parent;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public TaskStatusEnum getStatus() {
return status;
}
public void setStatus(TaskStatusEnum status) {
this.status = status;
}
public List<Step> getSteps() {
return steps;
}
public void setSteps(List<Step> steps) {
this.steps = steps;
}
public Long getReferenceId() {
return referenceId;
}
public void setReferenceId(Long referenceId) {
this.referenceId = referenceId;
}
public Integer getMaxAttempts() {
return maxAttempts;
}
public void setMaxAttempts(Integer maxAttempts) {
this.maxAttempts = maxAttempts;
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
}
Step:
#Entity
#Table(name = "step")
public class Step implements Serializable {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "name")
private String name;
#Column(name = "groupname")
private String group;
#Column(name = "route")
private String route;
#Column(name = "celerytask")
private String celeryTask;
#Column(name = "postbackqueuename")
private String postBackQueueName;
#Column(name = "postbackerrorqueuename")
private String postBackErrorQueueName;
#Enumerated(EnumType.STRING)
#Column(name = "status")
private TaskStatusEnum status;
#ElementCollection
private List<String> arguements;
#Column(name="runningTaskId")
private Long runningTaskId;
#Column(name="result")
private String result;
#Column(name="attempt")
private Integer attempt;
#JsonIgnore
#ManyToOne
private TaskState task;
public Step() {
arguements = new ArrayList<>();
status = TaskStatusEnum.New;
attempt = 0;
}
public Step(String name, String group, String route, String celeryTask, String postBackQueueName, String postBackErrorQueueName, TaskStatusEnum status, List<String> arguements, Long runningTaskId) {
this();
this.name = name;
this.group = group;
this.route = route;
this.celeryTask = celeryTask;
this.postBackQueueName = postBackQueueName;
this.postBackErrorQueueName = postBackErrorQueueName;
this.status = status;
this.arguements = arguements;
this.runningTaskId = runningTaskId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getRoute() {
return route;
}
public void setRoute(String route) {
this.route = route;
}
public String getCeleryTask() {
return celeryTask;
}
public void setCeleryTask(String celeryTask) {
this.celeryTask = celeryTask;
}
public String getPostBackQueueName() {
return postBackQueueName;
}
public void setPostBackQueueName(String postBackQueueName) {
this.postBackQueueName = postBackQueueName;
}
public String getPostBackErrorQueueName() {
return postBackErrorQueueName;
}
public void setPostBackErrorQueueName(String postBackErrorQueueName) {
this.postBackErrorQueueName = postBackErrorQueueName;
}
public List<String> getArguements() {
return arguements;
}
public void setArguements(List<String> arguements) {
this.arguements = arguements;
}
public TaskStatusEnum getStatus() {
return status;
}
public void setStatus(TaskStatusEnum status) {
this.status = status;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public Integer getAttempt() {
return attempt;
}
public void setAttempt(Integer attempt) {
this.attempt = attempt;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getRunningTaskId() {
return runningTaskId;
}
public void setRunningTaskId(Long runningTaskId) {
this.runningTaskId = runningTaskId;
}
public TaskState getTask() {
return task;
}
public void setTask(TaskState task) {
this.task = task;
}
}
It's not cascading because of stateObj.setTasks(null);.
You're breaking the link between the State and its Tasks so when you're deleting the State, the delete doesn't cascade on anything.

How Hibernate to query three tables in a time?

I have three tables :
1. org,
2. product_info
3. service_info.
And, table product_info is mapping table service_info ManyToMany,
means,many products mapping many services.
While,table org is mapping table product_info OneToMany,
means,one org have many products.
When I initialize my web
I want to view the org table's column. How to do ?
Under classes are the persistent classes for three tables.
ProductService class:
`
#Entity
#Table(name="product_service")
#Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
public class ProductService implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private String id;
private ServiceInfo serviceInfo;//this is the service table
private String parammapping;
private ProductInfo productInfo;//this is the product table
// Constructors
/** default constructor */
public ProductService() {
}
/** minimal constructor */
public ProductService(String id) {
this.id = id;
}
// Property accessors
#Id
#Column(name="ID", unique=true, nullable=false, length=50)
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="SERVICEID")
public ServiceInfo getServiceInfo() {
return this.serviceInfo;
}
public void setServiceInfo(ServiceInfo serviceInfo) {
this.serviceInfo = serviceInfo;
}
#Column(name="PARAMMAPPING", length=1000)
public String getParammapping() {
return parammapping;
}
public void setParammapping(String parammapping) {
this.parammapping = parammapping;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="PRODUCTID")
public ProductInfo getProductInfo() {
return this.productInfo;
}
public void setProductInfo(ProductInfo productInfo) {
this.productInfo = productInfo;
}
}`
baseOrg class:
#Entity
#Table(name="base_org")
#Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
public class BaseOrg implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String code;
private String name;
private List<BaseRuleEngineLog> serviceUsedLogs = new ArrayList<BaseRuleEngineLog>(0);
private List<ProductInfo> productInfos = new ArrayList<ProductInfo>(0);
private List<BaseCreditQuery> baseCreditQueries = new ArrayList<BaseCreditQuery>(0);
// Constructors
/** default constructor */
public BaseOrg() {
}
/** minimal constructor */
public BaseOrg(String id) {
this.id = id;
}
#Id
#Column(name="ID", unique=true, nullable=false, length=50)
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
#Column(name="CODE", length=50)
public String getCode() {
return this.code;
}
public void setCode(String code) {
this.code = code;
}
#Column(name="NAME", length=200)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="baseOrg")
public List<BaseRuleEngineLog> getServiceUsedLogs() {
return this.serviceUsedLogs;
}
public void setServiceUsedLogs(List<BaseRuleEngineLog> serviceUsedLogs) {
this.serviceUsedLogs = serviceUsedLogs;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="baseOrg")
public List<ProductInfo> getProductInfos() {
return this.productInfos;
}
public void setProductInfos(List<ProductInfo> productInfos) {
this.productInfos = productInfos;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="baseOrg")
public List<BaseCreditQuery> getBaseCreditQueries() {
return this.baseCreditQueries;
}
public void setBaseCreditQueries(List<BaseCreditQuery> baseCreditQueries) {
this.baseCreditQueries = baseCreditQueries;
}
}
productInfo class:
#Entity
#Table(name="product_info")
#Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
public class ProductInfo implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private String id;
private BaseOrg baseOrg;//baseOrg table
private String code;
private String name;
private String orgcode;
private List<ProductService> productServices = new ArrayList<ProductService>(0);
// Constructors
/** default constructor */
public ProductInfo() {
}
/** minimal constructor */
public ProductInfo(String id) {
this.id = id;
}
// Property accessors
#Id
#Column(name="ID", unique=true, nullable=false, length=50)
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="ORGID")
public BaseOrg getBaseOrg() {
return this.baseOrg;
}
public void setBaseOrg(BaseOrg baseOrg) {
this.baseOrg = baseOrg;
}
#Column(name="CODE", length=100)
public String getCode() {
return this.code;
}
public void setCode(String code) {
this.code = code;
}
#Column(name="NAME", length=100)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name="ORGCODE", length=100)
public String getOrgcode() {
return this.orgcode;
}
public void setOrgcode(String orgcode) {
this.orgcode = orgcode;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="productInfo")
public List<ProductService> getProductServices() {
return this.productServices;
}
public void setProductServices(List<ProductService> productServices) {
this.productServices = productServices;
}
}
serviceInfo class
#Entity
#Table(name="service_info")
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class ServiceInfo implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String name;
private String code;
private List<ProductService> productServices = new ArrayList<ProductService>(0);
// Constructors
/** default constructor */
public ServiceInfo() {
}
/** minimal constructor */
public ServiceInfo(String id) {
this.id = id;
}
// Property accessors
#Id
#Column(name="ID", unique=true, nullable=false, length=50)
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
#Column(name="NAME", length=100)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name="CODE", length=100)
public String getCode() {
return this.code;
}
public void setCode(String code) {
this.code = code;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="serviceInfo")
public List<ProductService> getProductServices() {
return this.productServices;
}
public void setProductServices(List<ProductService> productServices) {
this.productServices = productServices;
}
}
product_service table
Thank you for forgiving my poor English,this is my first time questioning on Stack Overflow.
OK,I resolve it.
i found its so sample,lol.
Because,most criteria have been packaged.At the first time ,I want to use the HQL to resolve it,but in vain.I just add this sentences,and getted it.
enter image description here

Categories

Resources