Spring boot JPARepository native Query - sql-server

I am using springboot JPAREPOSITORY and SQL server as db and getting the following exception while using JPARepository."org.hibernate.exception.GenericJDBCException: could not execute query; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not execute query".
JPARepository method like findAll() works fine. Facing issue when I am using any native query.
#Entity
#Getter
#NoArgsConstructor
#Table(name = "ABC_Data")
public class WeeklyActualESBDao
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#JsonIgnore
#Column(name = "ESB_ACTUALSDATA_ID")
private Integer actualsId;
#Column(name = "division")
private Integer division;
#Column(name = "familyTreeLevel")
private String familyTreeLevel;
#Column(name = "departmentCode")
private Integer departmentCode;
#Column(name = "year")
private Integer year;
#Column(name = "period")
private Integer period;
#Column(name = "week_of_period")
private Integer weekOfPeriod;
#Column(name = "net_sales")
private BigDecimal netSales = new BigDecimal(0);
#Column(name = "delivered_gross")
private BigDecimal deliveredGross = new BigDecimal(0);
#Column(name = "units")
private Integer units;
}
#Query(value = "SELECT ADYEAR , ADPERIOD, ADWEEK "
+ " FROM "
+ " ESB_ACTUALS_DATA where ADYEAR = :year", nativeQuery = true)
List<WeeklyActualESBDao> getSales(#Param("year") Integer year);

Related

Spring DataJPA not saving 3rd tabledata to the database

I have no problem with saving my entities to the database. However when I try to insert values into my 3rd many-to-many table, it simply doesn't do anything.
Here is my student entity;
#Table(name = "student", schema = "school")
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long studentId;
#Column(name = "name")
private String name;
#Column(name = "surname")
private String surname;
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "student_classroom", schema = "school")
private Collection<Classroom> classroom = new ArrayList<>();
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
#JoinTable(name = "student_teacher",
joinColumns = {
#JoinColumn(name = "student_id", referencedColumnName = "studentId",
nullable = false, updatable = false)},
inverseJoinColumns = {
#JoinColumn(name = "teacher_id", referencedColumnName = "teacherId",
nullable = false, updatable = false)})
private Set<Teacher> teachers = new HashSet<>();
The teacher entity.
#Entity
#Table(name = "teacher", schema = "school")
public class Teacher {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long teacherId;
#Column(name = "name")
private String name;
#Column(name = "surname")
private String surname;
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "teacher_classroom", schema = "school")
private Collection<Classroom> classroom = new ArrayList<>();
#ManyToMany(mappedBy = "teachers", fetch = FetchType.LAZY)
private Set<Student> students = new HashSet<>();
Here is my service method.
public void addTeacherToStudent(long teacherId, long studentId) {
Optional<Teacher> teacher = teacherRepository.findById(teacherId);
Optional<Student> student = studentRepository.findById(studentId);
student.get().getTeachers().add(teacher.get());
teacher.get().getStudents().add(student.get());
}
It has no problem saving the teachers and students in the sets in memory, however it doesn't reach the database. I have tried every annotation, didn't work.
Try adding this in Teacher entity
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(
name = "student_teacher",
joinColumns = #JoinColumn(name = "teacher_id"),
inverseJoinColumns = #JoinColumn(name = "student_id")
)
private Set<Student> students = new HashSet<>();

How can I model a drone medication delivery system in a database structure?

I have thought extensively about it and came up with these 2 classes:
public class Drone {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#NotEmpty(message = "Serial Number is required")
#Size(max = 100)
private String serial_number;
private ModelType model;
#Max(500)
private int weight_limit;
#NotEmpty(message = "Battery capacity is required")
private BigDecimal battery_capacity;
private StateType state;
}
and
public class Medication {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Pattern(regexp = "^[a-zA-Z0-9_-]*$")
private String name;
private float weight;
#Pattern(regexp = "^[a-zA-Z0-9_]*$")
private String code;
#Column(nullable = true, length = 64)
private String image;
}
But I just can't figure out how to link them since each drone will be carrying medications. I still think I'm missing something. Any ideas?

JPQL with Group by clause in SQL Server database not working

I am new to SQL Server database. The below JPQL query is not getting executed and not throwing any errors. Just my application hanging over at this query. This code is working fine with MySQL database, but not with SQL Server(2019) database.
#Query(value = "SELECT R.riskType, count(distinct V.bname) FROM RiskViolation V JOIN V.job J JOIN V.risk R WHERE J.id = ?1 GROUP BY R.riskType ")
public List<Object[]> sodUserByRiskType(Long jobId);
But when I run the below converted sql query directly in the SQL Server database, it is working fine.
select count(distinct riskviolat0_.bname) as col_1_0_, risklog2_.risk_type as col_0_0_ from risk_violation riskviolat0_ inner join analysis_job analysisjo1_ on riskviolat0_.job_id=analysisjo1_.id inner join risk_log risklog2_ on riskviolat0_.risk_id=risklog2_.id where analysisjo1_.id=? group by risklog2_.risk_type;
Here are the Java entity classes which are used in JPQL query:
RiskViolation.java
#Entity
#Table(name = "risk_violation")
public class RiskViolation {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "job_id")
private AnalysisJob job;
private String bname;
private String riskName;
private String violations;
#Column(name = "violated", columnDefinition = "BIT", length = 1)
private boolean violated;
#Column(name = "simulation", columnDefinition = "BIT", length = 1)
private boolean simulation;
#Column(name = "mitigation_name")
private String mitigationName;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "risk_id")
private RiskLog risk;
#JsonIgnore
#OneToMany(mappedBy = "riskViolation", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<RuleViolation> ruleViolations;
}
AnalysisJob.java
#Entity
#Table(name = "analysis_job")
public class AnalysisJob {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "profile_name")
private String profileName;
#OneToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "profile_id")
#OnDelete(action = OnDeleteAction.CASCADE)
private AnalysisProfileLog profileLog;
#Column(name = "description")
private String description;
#Column(name = "status")
private String status;
#Column(name = "started_on")
private Date startedOn;
#Column(name = "completed_on")
private Date completedOn;
#Column(name = "completion_message")
private String completionMessage;
#Column(name = "percent_completed")
private float percentCompleted;
#Column(name = "run_by")
private String runBy;
#Column(name = "removed", columnDefinition = "BIT", length = 1)
private boolean removed;
#OneToMany(mappedBy = "job", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY)
private List<JobResultData> resultData;
#Column(name = "pos_analysis", columnDefinition = "BIT", length = 1)
private boolean posAnalysis;
#Column(name = "submitted", columnDefinition = "BIT", length = 1)
private boolean submitted;
#Column(name = "position_id")
private String positionId;
}
RiskLog.java
#Entity
#Table(name = "risk_log")
public class RiskLog {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long jobId;
private String name;
private String riskDescription;
private String riskCondition;
private String businessProcess;
#Column(name = "business_sub_process")
private String subProc;
private String riskType;
#JsonIgnore
#OneToMany(mappedBy = "riskLog", cascade = CascadeType.ALL)
protected List<RuleLog> rules;
}
Do I need to make any changes to the query and entity classes to make it work?
Here is Query Plan URL
Estimated Execution Plan
Actual Execution Plan
Query Plan with Actual Rows
It worked after avoiding facade class between Java class (where my business logic resides) and JPA repository( use to execute JPQL queries). Directly invoked JPA repository method from Java class. Not sure why it did not work with facade class with SQL Server, but same worked with MySQL database.

Bridge table primary as foreign key in another table (JPA)

I'm designing a student enrollment database
Student-Table
student_id (pk)
//other attributes
Course-Table
course_id (pk)
//other attributes
Student_course-Table
student_course_id(pk)
course_id (fk)
student_id (fk)
Lectrue-Table
lecture_id(pk)
student_course_id(fk - > student_course table)
// other attributes
Basically I want to store which student is enrolled to which course and has attend how many lectures for that particular course.
Q1 ) Is this design correct? Should I use primary key of Bridge table as foreign key in another table.
Q2 ) I did manyToMany mapping between student <-> course and oneToMany between student_course <-> lecture and got the following error :
org.hibernate.MappingException: Foreign key must have same number of columns as the referenced primary key
Any idea how to proceed?
//UPDATE Entity class
#Entity
#Table(name = "STUDENT")
public class Student implements Serializable {
#Id
#Column(name = "STUDENT_ID")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#ManyToMany(mappedBy = "students" ,cascade = CascadeType.ALL)
#MapKey(name = "courseName")
private Map<String, Course> courses;
}
#Entity
#Table(name = "COURSE", uniqueConstraints = #UniqueConstraint(columnNames = {"COURSE_NAME"}))
public class Course implements Serializable {
#Id
#Column(name = "COURSE_ID")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "STUDENT_COURSE", joinColumns = {
#JoinColumn(name = "COURSE_ID") }, inverseJoinColumns = {
#JoinColumn(name = "STUDENT_ID") })
private Set<Student> students;
#Column(name = "COURSE_NAME")
private String courseName;
}
#Entity
#Table(name = "LECTURE")
public class Lecture {
#Id
#Column(name = "LECTURE_ID")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "STUDENT_COURSE_ID")
private StudentCourse studentCourse;
}
#Entity
#Table(name = "STUDENT_COURSE")
public class StudentCourse {
#Id
#Column(name = "STUDENT_COURSE_ID")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "STUDENT_ID")
private Long studentId;
#Column(name = "COURSE_ID")
private Long courseId;
#OneToMany(mappedBy = "studentCourse")
private Set<Lecture> lectures = new HashSet<Lecture>();
}

Failed to load resource: the server responded with a status of 415

I have a error when call the POST. I am using AngularJS, Tomee, restful
Error: Failed to load resource: the server responded with a status of 415
POST:
$http({method: 'POST', url:'http://localhost:8080/WSGestionCobros/webresources/atenciones/',data: {"atenciones" : $scope.atencion}}).success(function(data, status, headers, config) {
...
}
My class
#Stateless
#Path("atenciones")
public class AtencionesFacadeREST extends AbstractFacade<Atenciones> {
#PersistenceContext(unitName = "WSCobrosPU")
private EntityManager em;
public AtencionesFacadeREST() {
super(Atenciones.class);
}
#POST
#Override
#Consumes({"application/json"})
public void create(Atenciones entity) {
super.create(entity);
}
...
...
...
The entity class:
#Entity
#Table(name = "atenciones")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Atenciones.findAll", query = "SELECT a FROM Atenciones a"),
#NamedQuery(name = "Atenciones.findByCasoid", query = "SELECT a FROM Atenciones a WHERE a.casoid = :casoid"),
#NamedQuery(name = "Atenciones.findByCedula", query = "SELECT a FROM Atenciones a WHERE a.cedula = :cedula"),
#NamedQuery(name = "Atenciones.findByUsuario", query = "SELECT a FROM Atenciones a WHERE a.usuario = :usuario"),
#NamedQuery(name = "Atenciones.findByEstado", query = "SELECT a FROM Atenciones a WHERE a.estado = :estado"),
#NamedQuery(name = "Atenciones.findByFechaCreacion", query = "SELECT a FROM Atenciones a WHERE a.fechaCreacion = :fechaCreacion")})
public class Atenciones implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "casoid")
private Integer casoid;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 50)
#Column(name = "cedula")
private String cedula;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 50)
#Column(name = "usuario")
private String usuario;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 3)
#Column(name = "estado")
private String estado;
#Basic(optional = false)
#NotNull
#Column(name = "fecha_creacion")
#Temporal(TemporalType.TIMESTAMP)
private Date fechaCreacion;
...
I tried put header Content-Type: application/json but nothing
Maybe add #Produces("application/json") ont the method or class

Resources