could not extract ResultSet; SQL [n/a];nested exception is org.hibernate.exception.SQLGrammarException While trying to fetch Department list - spring-boot

I have tried many way to solve this problem but Can't,
If I remove custome repository and use JpaRepository then it is woking fine without changing single digit code. I don't know why this is happening. When I'm trying to fetch department list then it is occuring error on postman
Please help me as soon as possible
Here is the my code please check it
College.java
#Entity
#Table(name = "colleges")
public class College {
#Id
#GeneratedValue(
strategy = GenerationType.IDENTITY
)
#Column(name = "college_id")
private Long id;
#Column(name = "college_name", nullable = false)
private String collegeName;
#Column(name = "address", nullable = false)
private String address;
#OneToMany(mappedBy = "college", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Department> departments = new HashSet<>();
#OneToMany(mappedBy = "faccollege", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Faculty> faculties = new HashSet<>();
//Getter setters
}
Department.java
#Entity
#Table(name = "departments")
public class Department {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "department_id")
private long id;
private String departmentName;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "college_id", nullable = false)
private College college;
#OneToMany(mappedBy = "department", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Faculty> faculties = new HashSet<>();
//Getter and Setters
}
DepartmentRepository
#Repository
#Transactional
public class DepartmentRepository{
#Autowired
SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf) {
this.sessionFactory = sf;
}
public List<Department> findAll(){
Session session = this.sessionFactory.getCurrentSession();
List<Department> departmentList = session.createQuery("from Department").list();
return departmentList;
}
#Transactional
public Department save(Department department) {
Session session = this.sessionFactory.getCurrentSession();
session.save(department);
return department;
}
public Department findById(long id) {
Session session = this.sessionFactory.getCurrentSession();
Department department = (Department) session.get(Department.class, id);
return department;
}
}

Related

Spring Data Projection with OneToMany error

I have a entity call Circuit.
#Entity
public class Circuit implements Comparable<Circuit>, Serializable {
#Column
private String id;
#OneToMany(mappedBy = "circuit", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
private Set<Step> workflow = new HashSet<>();
...
}
I have a class called CircuitLight
public class CircuitLight {
private String id;
private Set<Step> workflow;
/* constructor, getters and setters */
}
In my CircuitRepository, i'm trying to make a projection
#Transactional(readOnly = true)
#Query("select new com.docapost.circuit.CircuitLight(c.id, c.workflow) from Circuit c where c.account.siren = :siren")
Set<CircuitLight> findAllByAccountSirenProjection(#Param("siren") String siren);
When i execute, i have a error message:
could not extract ResultSet; SQL [n/a] com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'circuit0_.id' in 'on clause'
I try with other entity. Every time i have a property with a relation #OneToMany, i have the issue...
Is it possible to make a projection with class (Without use a interface) when there are a relation OneToMany ?
UPDATE:
Step.class
#Entity
public class Step implements Comparable<Step>, Serializable {
private static final List<String> INDEXABLE_PROCESSES = Arrays.asList(
ParapheurWorkflowModel.SERVER,
ParapheurWorkflowModel.SIGN,
ParapheurWorkflowModel.VISA
);
#Id
#GeneratedValue
#Expose
#SerializedName("step_id")
public long id;
#ManyToOne
public Circuit circuit;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(joinColumns = #JoinColumn(name = "step_id"), inverseJoinColumns = #JoinColumn(name = "technicalGroup_id"))
private List<TechnicalGroup> technicalGroups = new ArrayList<>();
#Column(name = "step_type", nullable = false)
#Expose
#SerializedName("subprocess_ref")
public String type;
#Column(nullable = false)
public int orderIndex;
/* contructor, getters and setters */
}
UPDATE 2:
Hum.... My bad, in my circuit class, i have a EmbeddedId
#EmbeddedId
private CircuitPK key;
#Embeddable
public static class CircuitPK implements Serializable {
public String id;
public String siren;
}
I try with this code in Step.class
#ManyToOne
#JoinColumns(value = {
#JoinColumn(name = "circuit_siren", referencedColumnName = "siren"),
#JoinColumn(name = "circuit_id", referencedColumnName = "id")
})
public Circuit circuit;
The result is the same
Write the following code in the Step entity
#ManyToOne
#JoinColumn(name="id", nullable=false)
private Circuit circuit;

org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException

This is my orderservice implementation for creating and saving orders here with the customerid I'm getting customer and customer has a cart and in the cart product list is there and for that product list, I should create an order.
public Order save(int custid) {
Optional<Customer> cust = customerRepo.findById(custid);//here customer is there and inside customer cart is there inside cart medicine list is there.
Cart ct= cust.get().getCart();//getting cart from customer
if(ct.getMedicineList().size()!=0) {//create order only if the medicine list is not empty. there are 8 fields **orderDate,dispatchDate,status,medicineList,totalCost,customer and orderId(GeneratedValue)** I can't set the orderId cuz it is auto generated.
LocalDate todaysDate = LocalDate.now();
LocalDate dispatchdate = todaysDate.plusDays(3);
List<Medicine> orderList= new ArrayList<Medicine>();
List<Medicine> cartList= new ArrayList<Medicine>();
cartList=ct.getMedicineList();
orderList.addAll(cartList);
Order ord = new Order();
ord.setCustomer(cust.get());
ord.setMedicineList(orderList);
ord.setDispatchDate(dispatchdate);
ord.setOrderDate(todaysDate);
ord.setStatus("Placed");
ord.setTotalCost((float)ct.getTotalAmount());
logger.info("Add order to the database");
return orderRepository.save(ord);
}
return null;
}
this is my order controller
#PostMapping("/order/{custid}")
public ResponseEntity<Order> addOrder(#Valid #PathVariable("custid") int custid) {
logger.info("Add order in database");
return new ResponseEntity<>(orderService.save(custid), HttpStatus.OK);
}
this is my medicine Entity
#Data
#RequiredArgsConstructor
#ToString
#Table(name = "medicine")
#Entity
public class Medicine {
#Id
#Column(name = "medicine_id", nullable = false)
#NonNull
#GeneratedValue
private int medicineId;
#NonNull
#Size(min = 3, message = "Minimum charecters in medicine name should be 3.")
#NotEmpty
#Column(unique = true, name = "medicine_name", nullable = false)
private String medicineName;
#NonNull
#Column(name = "medicine_cost", nullable = false)
private float medicineCost;
#NonNull
#Column(name = "mfd", nullable = false)
private LocalDate mfd;
#NonNull
#Column(name = "expiry_date", nullable = false)
private LocalDate expiryDate;
#NonNull
#Column(name = "medicine_quantity", nullable = false)
private int medicineQuantity = 1;
#NonNull
private String medicineCategory;
#NonNull
private String medicineDescription;
#JsonIgnore
#ManyToMany(cascade = CascadeType.ALL, mappedBy = "medicineList",fetch = FetchType.EAGER)
private List<Order> orderList;
}
this is my order Entity
#Data
#AllArgsConstructor
#NoArgsConstructor
#ToString
public class Order {
#Id
#Column(name = "orderId")
#GeneratedValue
private int orderId;
#NonNull
private LocalDate orderDate;
#ManyToMany(targetEntity = Medicine.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinTable(name = "ord_med", joinColumns = { #JoinColumn(name = "ord_id") }, inverseJoinColumns = {
#JoinColumn(name = "med_id") })
private List<Medicine> medicineList = new ArrayList<>();
#NonNull
private LocalDate dispatchDate;
#NotEmpty
private float totalCost;
#NonNull
private String status;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name="c_ord_fk",referencedColumnName = "customerId")
#NonNull
private Customer customer;
}
here when i try to create order for the list inside cart it gives me [36m.m.m.a.ExceptionHandlerExceptionResolver[0;39m [2m:[0;39m Resolved [org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction]
i'm not sure but i think its because of the id but it is autogenerated. Idk how to create an order object for the list of products or is this the correct way to do it.
Actually I found the answer, all I have to do is when you use ManyToMany mapping the cascade type must be cascade = {CascadeType.MERGE,CascadeType.REFRESH} instead of {cascade = CascadeType.ALL} and it works fine. reference JPA: detached entity passed to persist: nested exception is org.hibernate.PersistentObjectException

jpa - list OneToMany not saved

I have the below room entity which has many disponibilities, when i add a room with a list of disponibilities, the room is saved but the list is not. what am i missing in the relationship ?
#Entity
public class RoomEntity {
#Id
private String classRoomId;
private String label;
#OneToMany(mappedBy = "room", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<DisponibilityEntity> disponibilities;
public void addDisponibilities(List<DisponibilityEntity> disponibilityEntities) {
if (CollectionUtils.isEmpty(disponibilities)) {
disponibilities = new ArrayList<>();
}
disponibilities.addAll(disponibilityEntities);
disponibilityEntities.forEach(item -> item.setRoom(this));
}
}
#Entity
public class DisponibilityEntity {
#Id
private String disponibilityId;
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "fk_room")
private RoomEntity room;
}
roomEntity.addDisponibilities(classRoomEntity.getDisponibilities());
roomRepository.save(roomEntity);

#One-to-Many relationship does not working in Spring

I have an Entity Recipe with a relationship OneToMany with Ingredients.
#Entity
public class Recipe {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
private String name;
#OneToOne(cascade = CascadeType.ALL) // se eliminiamo la Recipe eliminiamo anche notes
private Notes notes;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "recipe")
private Set<Ingredient> ingredients;
#ManyToMany(fetch=FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(name = "recipe_category",
joinColumns = #JoinColumn(name = "recipe_id"),
inverseJoinColumns = #JoinColumn(name = "category_id"))
private Set<Category> categories;
...getter and setter...
}
And an Entity Ingredient:
#Entity
public class Ingredient {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String description;
private int amount;
#ManyToOne
private Recipe recipe;
...getter and setter...
}
In order to test it I have used a controller to insert and retrieving all row:
#GetMapping({"","/"})
public List<Recipe> allRecipe() {
return recipeRepository.findAll();
}
#GetMapping("/insert")
public Recipe addRecipe() {
Set<Ingredient> ingredients = new HashSet<>();
ingredients.add(new Ingredient("ingredient-"+Math.random(), 10));
Recipe newRecipe = new Recipe("Recipe-"+Math.random(),
null, ingredients, null);
return recipeRepository.save(newRecipe);
}
The repository is a JPA Repository.
I do not have any errors, but when I try to retrieve an object I get no ingredients even though they are saved on the table (but with recipe_id = null).
How can I solve this problem?
Initialize your ingredients as
#OneToMany(cascade = CascadeType.ALL, mappedBy = "recipe")
private Set<Ingredient> ingredients = new HashSet<>();
Change your your controller to,
#GetMapping("/insert")
public Recipe addRecipe() {
Ingredient ingredient = new Ingredient("ingredient-"+Math.random(), 10));
Recipe newRecipe = new Recipe("Recipe-"+Math.random(),
null, null); //constructor without ingredient arg
newRecipe.getIngredients.add(ingredient);
ingredient.setRecipe(newRecipe);
return recipeRepository.save(newRecipe);
}

Spring JPA 2 nested many to many relationship

I am having a problem with my many to many relationship. Basically, here is what I am trying to do.
I have 2 many to many tables that are nested, as seen on the following image.
Db diagram
When compiling my code, I get the following error:
Caused by: java.sql.SQLSyntaxErrorException: Unknown column 'weeks0_.employee_project_employee_id' in 'field list'
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) ~[mysql-connector-java-8.0.18.jar:8.0.18]
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.18.jar:8.0.18]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.18.jar:8.0.18]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953) ~[mysql-connector-java-8.0.18.jar:8.0.18]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1003) ~[mysql-connector-java-8.0.18.jar:8.0.18]
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52) ~[HikariCP-3.4.1.jar:na]
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java) ~[HikariCP-3.4.1.jar:na]
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:57) ~[hibernate-core-5.4.6.Final.jar:5.4.6.Final]
So I understand that I have a problem with the weeks.
here are my entities:
Week:
package com.achsogo.rpt.entity;
import javax.persistence.*;
import java.util.Set;
#Entity
#Table(name="week")
public class Week {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private int weekNumber;
private int year;
#OneToMany(mappedBy = "week", cascade = CascadeType.ALL, orphanRemoval = true, fetch =
FetchType.EAGER)
private Set<EmployeeProjectWeek> employeeProjects;
public Week() {
}
public Week(int weekNumber, int year) {
this.weekNumber = weekNumber;
this.year = year;
} //Getter and Setters
Project:
import javax.persistence.*;
import java.util.*;
#Entity
#Table(name = "project")
public class Project {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String alias;
private String pspElement;
private int contractValue;
private int plannedCost;
private int plannedHours;
private int assignedHours;
private Date startDate;
private Date endDate;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "project", orphanRemoval = true, fetch =
FetchType.EAGER)
private Set<ProjectAP> projectAPS;
#ManyToOne
private Department department;
#OneToMany(mappedBy = "project", cascade = CascadeType.ALL, orphanRemoval = true, fetch =
FetchType.EAGER)
private Set<EmployeeProject> employees;
//Empty constructor
public Project(){}
//constructor for new project with default names
public Project(String alias){
this.alias = alias;
}
Employee:
#Entity
#Table(name = "employee")
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
private String email;
private int employeeNumber;
private String acronym;
private int availability;
#OneToMany(mappedBy = "employee", cascade = CascadeType.ALL, orphanRemoval = true, fetch =
FetchType.EAGER)
private Set<EmployeeProject> projects;
#ManyToOne
private Department department;
#ManyToOne
private Role role;
Table between Project and Employee (with the class to create the ID):
EmployeeProjectID:
#Embeddable
public class EmployeeProjectId implements Serializable {
private Long projectId;
private Long employeeId;
private EmployeeProjectId(){}
public EmployeeProjectId(Long projectId, Long employeeId){
this.employeeId = employeeId;
this.projectId = projectId;
}
EmployeeProject: It is here that the weeks are being called (If I am not mistaken)
#Entity
#Table(name = "project_employee")
public class EmployeeProject {
#EmbeddedId
private EmployeeProjectId id;
#ManyToOne(fetch = FetchType.EAGER)
#MapsId("projectId")
private Project project;
#ManyToOne(fetch = FetchType.EAGER)
#MapsId("employeeId")
private Employee employee;
#Column(name = "amount_time")
private int amountTime = 0;
#Column(name = "is_project_leader")
private boolean isProjectLeader = false;
#OneToMany(mappedBy = "employeeProject", cascade = CascadeType.ALL, orphanRemoval = true, fetch =
FetchType.EAGER)
private Set<EmployeeProjectWeek> weeks;
public EmployeeProject(){}
And now the table between Week and Employee Project:
EmployeeProjectWeekId: To create the ID for the nested many to many table:
#Embeddable
public class EmployeeProjectWeekId implements Serializable {
private EmployeeProjectId employeeProjectId;
private Long weekId;
private EmployeeProjectWeekId(){}
And finally the EmployeeProjectweek:
#Entity
#Table(name="project_employee_week")
public class EmployeeProjectWeek {
#EmbeddedId
private EmployeeProjectWeekId id;
#ManyToOne(fetch = FetchType.EAGER)
#MapsId("weekId")
private Week week;
#ManyToOne(fetch = FetchType.EAGER)
#MapsId("employeeProjectId")
private EmployeeProject employeeProject;
#Column(name="amount_time")
private int amountTime = 0;
#Column(name="is_project_leader")
private boolean isProjectLeader= false;
public EmployeeProjectWeek(Week week, EmployeeProject employeeProject) {
this.week = week;
this.employeeProject = employeeProject;
this.id = new EmployeeProjectWeekId(employeeProject.getId(), week.getId());
}
Does anyone has a clue where I have done an error? Thanks in advance for your time!
It was a naming problem. I solved this by dropping all the tables in my DB and having Spring to automatically generate the tables. Now everything works well.
I entered the following lines in my application.properties:
spring.jpa.hibernate.ddl=true
spring.jpa.hibernate.ddl-auto=update

Resources