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

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

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<>();

Spring boot JPARepository native Query

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);

how to store and retrieve image files from database using springboot

I'm building an angular springboot application but I find so many approaches to do this some of which I honestly do not understand.
how can I store 1 or more images at a time and retrieve them.
You can use #Lob to store Images or Any Files in the Database. The following example shows a simple implementation of this approach
#Entity
#Table(name = "file")
public class File {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "uuid")
private String uuid;
#Column(name = "content_type")
private String contentType;
#Column(name = "extension")
private String extension;
#Lob
#Column(name = "content", columnDefinition = "LONGBLOB")
private byte[] content;
}
#Service
public class FileService {
private final FileRepository repository;
#Autowired
public FileService(FileRepository repository) {
this.repository = repository;
}
#Transactional
public StreamingResponseBody download(Long id, HttpServletResponse response) {
final File file = repository.findById(id).orElseThrow(NotFoundException::new);
return outputStream -> {
String fileName = (file.getUuid() + file.getExtension()).trim();
response.setContentType(file.getContentType());
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
outputStream.write(file.getContent());
outputStream.flush();
};
}
public FileDto create(MultipartFile multipartFile, boolean general) {
String fileName = multipartFile.getOriginalFilename();
String fileExtension = Objects.requireNonNull(fileName).substring(fileName.lastIndexOf('.'));
String uuid = UUID.randomUUID().toString();
UserDto user = contextUtils.getPrincipal();
File file = new File();
file.setUuid(uuid);
file.setContentType(multipartFile.getContentType());
file.setExtension(fileExtension);
file.setGeneral(general);
file.setContent(multipartFile.getBytes());
file.setId(repository.save(file).getId());
return file;
}
}

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.

Hibernate: ManyToOne generating field raw(255)

I recently upgraded from hibernate-core 4.1.7 to 5.0.9 and Have problem with this code:
#ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
#JoinColumn(name = "FK_AAA", foreignKey = #ForeignKey(name = "CS_BBB"))
#org.hibernate.annotations.Index(name = "IDX_CCC", columnNames = "FK_DDD")
private ImportData importData;
This generate correct foreign columns pointing to the defining class, but also generating a column on the same class:
IMPORTDATA RAW(255)
Why is this raw(255) column generated ? I think it was not generated with Hibernate-core 4.1.7
any idea ?
Update 1: here is longer code fragments:
#MappedSuperclass
#Access(AccessType.PROPERTY)
public abstract class BaseEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public abstract Long getId();
}
#Entity
#Table(name = "IMPORT_DATA", uniqueConstraints = {
#UniqueConstraint(name = "UC_IMP_BID", columnNames = {"BUSINESS_ID"})
}, indexes = {
#Index(name = "IDX_IMP_DGXML_ID", columnList = "FK_DGXML_ID"),
#Index(name = "IDX_IMP_IMPXML_ID", columnList = "FK_IMPXML_ID")
})
public class ImportData extends BaseEntity {
#Id #GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() { return id; }
// ...
}
#Entity(name = "MUTATION")
#Table(name = "MUTATION")
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name = "TYPE", discriminatorType = DiscriminatorType.STRING)
#SequenceGenerator(name = "mutationsSeq", sequenceName = "MUTATIONS_SEQUENCE", allocationSize = 1)
public abstract class Mutation extends BaseEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "mutationsSeq")
private Long id;
#ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
#JoinColumn(name = "FK_IMP_ID", foreignKey = #ForeignKey(name = "CS_MUT_IMP_ID"))
#org.hibernate.annotations.Index(name = "IDX_MUT_IMP_ID", columnNames = "FK_IMP_ID")
protected ImportData importData;
}
#Entity(name="XXX")
#DiscriminatorValue("XXX_DISC")
public class XXX extends Mutation {
// ...
}
I found an answer on Mapping composite key with Hibernate produces a raw field in Oracle:
I was mixing annotations on fields and methods. I also had #Id on an abstract superclass, and a redefinition on a derived class.
Fixing theses two elements, cleaning DB and regenerating in "create" ddl mode proved that the fix was no longer generating RAW field type.
Thanks for all your helps!

Resources