Springboot posgresql reposity bean can't be autowired - java

I have simple Sprinngboot app where actual database is PostgreSQL.
My model:-
#Table("carrier")
#Entity
public class MyCarrier {
#Id
#Column("id")
private UUID id;
#Size(
max = 100
)
#Column("carrier_name")
private String carrierName;
#Size(
max = 3
)
#Column("smdg_code")
private String smdgCode;
#Size(
max = 4
)
#Column("nmfta_code")
private String nmftaCode;
public MyCarrier() {
}
public UUID getId() {
return this.id;
}
public String getCarrierName() {
return this.carrierName;
}
public String getSmdgCode() {
return this.smdgCode;
}
public String getNmftaCode() {
return this.nmftaCode;
}
public void setId(final UUID id) {
this.id = id;
}
public void setCarrierName(final String carrierName) {
this.carrierName = carrierName;
}
public void setSmdgCode(final String smdgCode) {
this.smdgCode = smdgCode;
}
public void setNmftaCode(final String nmftaCode) {
this.nmftaCode = nmftaCode;
}
protected boolean canEqual(final Object other) {
return other instanceof Carrier;
}
}
Repository:-
#Repository
public interface MyCarrierRepository extends JpaRepository<MyCarrier, Long> {
}
Controller:-
#RestController
#RequestMapping(path = "/upload")
public class ReactiveUploadResource {
Logger LOGGER = LoggerFactory.getLogger(ReactiveUploadResource.class);
private final SqlRequestHandler sqlRequestHandler;
#Autowired
private MyCarrierRepository myCarrierRepository;
public ReactiveUploadResource(SqlRequestHandler sqlRequestHandler) {
this.sqlRequestHandler = sqlRequestHandler;
}
}
I got this error:-
Description:
Field myCarrierRepository in com.consumer.controller.ReactiveUploadResource required a bean of type 'com.consumer.repository.MyCarrierRepository' that could not be found.
What is missing? Why Springboot doesn't find this repository?

You have to put the repository inside the package at the same level as Application class the packages to allow Spring boot to scan it

Related

could not serialize; nested exception is org.hibernate.type.SerializationException: could not serialize

I have spend way too much find finding the root cause of the below error:
org.springframework.orm.jpa.JpaSystemException: could not serialize; nested exception is org.hibernate.type.SerializationException: could not serialize
I am trying to save some value to db:
public void logFailure(Long objectID,Integer usLK){
StatusFailureDO failureDO = new StatusFailureDO(4,objectID, usLK);
failuresRepository.save(failureDO.getFailure());
}
#Repository
public interface FailuresRepository extends JpaRepository<GeneralFailure, Integer> {
GeneralFailure save(GeneralFailure aGeneralFailure);
void delete(GeneralFailure aGeneralFailure);
GeneralFailure findByObjectID(Long objectID);
}
There were many mapping errors and as such that I got pass now. I am trying to understand where in the process error occurs and what shall I look out for.
public class StatusFailureDO extends GeneralFailureDO implements Serializable
{
public StatusFailureDO(Integer failureTypeLK,Long objectID,
Integer usLK)
{
super(new StatusFailure(failureTypeLK,
"An exception occurred while trying to update an UploadStatus entry.",
objectID, usLK));
}
//more constructors and setters
}
public abstract class GeneralFailureDO implements ICISConstant, Serializable
{
private GeneralFailure mGeneralFailure;
//constructors and setters
}
#Entity
#Inheritance(strategy = InheritanceType.JOINED)
#Table(name = "GEN_FLR")
public class GeneralFailure implements Serializable,ICISConstant
{
#Column(name = "CRTN_TM")
private Date mCreationTime;
#Column(name = "TYP_LKP_ID")
private Integer failureTypeLK;
#Column(name = "STUS_LKP_ID")
private Integer mFailureStatusLK;
#Column(name="OBJ_ID")
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
#GenericGenerator(name = "native", strategy = "native")
private Long objectID;
#Column(name = "DSCR")
private String mDescription;
public Date getCreationTime()
{
return mCreationTime;
}
public void setCreationTime(Date aCreationTime)
{
mCreationTime = aCreationTime;
}
public String getDescription()
{
return mDescription;
}
public void setDescription(String aDescription)
{
if (aDescription != null && aDescription.length() > MAX_DESCRIPTION_LENGTH)
{
mDescription = aDescription.substring(0, MAX_DESCRIPTION_LENGTH);
}
else
{
mDescription = aDescription;
}
}
public Long getObjectID()
{
return objectID;
}
public void setObjectID(Long aObjectID)
{
objectID = aObjectID;
}
public Integer getFailureTypeLK()
{
return failureTypeLK;
}
public void setFailureTypeLK(Integer aFailureTypeLK)
{
failureTypeLK = aFailureTypeLK;
}
public Integer getFailureStatusLK()
{
return mFailureStatusLK;
}
public void setFailureStatusLK(Integer aFailureStatusLK)
{
mFailureStatusLK = aFailureStatusLK;
}
}
#Entity
#Table(name="STUS_FLR")
public class StatusFailure extends GeneralFailure implements Serializable
{
#Column(name = "STUS_OBJ_ID")
private Long mStatusObjectID;
#Column(name = "STUS_LKP_ID")
private Integer mStatusLK;
#Column(name = "RQST_TYP_LKP_ID")
private Integer mRequestTypeLK;
#Column(name = "CODE")
private String mCode;
#Column(name = "PST_TM")
private Timestamp mPostTime;
#Column(name = "MSG_SZ")
private Integer mMessageSize;
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private Collection<StatusFailureError> StatusFailureErrorList;
#Column(name = "SMPL_FLG")
private boolean mSimple;
public Integer getStatusLK()
{
return mStatusLK;
}
public void setStatusLK(Integer statusLK)
{
mStatusLK = statusLK;
}
public Long getStatusObjectID()
{
return mStatusObjectID;
}
public void setStatusObjectID(Long statusObjectID)
{
mStatusObjectID = statusObjectID;
}
public String getCode()
{
return mCode;
}
public void setCode(String aCode)
{
mCode = aCode;
}
public Collection<StatusFailureError> getStatusFailureErrorList()
{
return mStatusFailureErrorList;
}
public void setStatusFailureErrorList(
Collection<StatusFailureError> aStatusFailureErrorList)
{
mStatusFailureErrorList = aStatusFailureErrorList;
}
public void setErrorList(Collection<String> aErrorList)
{
if (aErrorList != null && !aErrorList.isEmpty())
{
mStatusFailureErrorList = new ArrayList<StatusFailureError>();
for (Iterator<String> iter = aErrorList.iterator(); iter.hasNext();)
{
String error = (String) iter.next();
StatusFailureError failureError = new StatusFailureError(this, error, getPostTime());
mStatusFailureErrorList.add(failureError);
}
}
else
{
mStatusFailureErrorList = null;
}
}
public Integer getMessageSize()
{
return mMessageSize;
}
public void setMessageSize(Integer aMessageSize)
{
mMessageSize = aMessageSize;
}
public Timestamp getPostTime()
{
return mPostTime;
}
public void setPostTime(Timestamp aPostTime)
{
mPostTime = aPostTime;
}
public Integer getRequestTypeLK()
{
return mRequestTypeLK;
}
public void setRequestTypeLK(Integer aRequestTypeLK)
{
mRequestTypeLK = aRequestTypeLK;
}
public boolean isSimple()
{
return mSimple;
}
public void setSimple(boolean aSimple)
{
mSimple = aSimple;
}
}
Any help is really appreciated.
It is not obvious what the failureDO.getFailure() returns exactly because you did not provide a method definition for the StatusFailureDO.getFailure() method and so I will assume that that method returns an instance of a GeneralFailure class (or StatusFailure that extends it).
For hibernate to successfully save objects into the database, the #Entity classes that you are trying to save need to consist of "base" types. I see that you have an object of class CLRISCache defined in your GeneralFailure data class, that is most definitely not of a base type and not another #Entity. You can prevent a field from being persisted by marking it with the #Transient annotation, but really you should keep your data class pure.
You can find a list of "base" types here: https://docs.jboss.org/hibernate/orm/5.0/mappingGuide/en-US/html/ch03.html
Actually I found the reason. The General failure has dateCreation variable of Date type and in mu status failure I had it as a timestamp. I need to make it to Date and it worked.

How to solve issue of "cannot cast object" for Microsoft SQL in spring boot?

I am trying to call a stored procedure for my application using Microsoft SQL. However, when I run the stored procedure to pass back the contents of the object it fails. I have the objects as AVSApplication and in that class it has a list of variables and methods. I tried using an Iterable and a List but both produce the same error. I am not sure where I went wrong. I looked at other similar StackOverflow questions but I didn't get much from it.
Error:
java.lang.ClassCastException: java.base/[Ljava.lang.Object; cannot be cast to com.Mapping.AVSApplication
at com.Mapping.Employeecontroller.getAll(Employeecontroller.java:33) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~
Java Entity Code:
import java.util.*;
import javax.persistence.*;
#Entity
#NamedStoredProcedureQueries(value= {
#NamedStoredProcedureQuery(name= "procedure-one", procedureName= "GetAllAppWithStatus")
})
public class AVSApplication implements java.io.Serializable {
private static final long serialVersionUID = 1L;
#Id
private String appcode;
private String acronym;
private String appname;
private String sys_id;
private String mapstatus;
private String sdg;
private String status;
private String statuscode;
//Constructor
public AVSApplication(String appcode, String acronym, String appname, String sys_id, String mapstatus,
String sdg, String status, String statuscode) {
super();
this.appcode = appcode;
this.acronym = acronym;
this.appname = appname;
this.sys_id = sys_id;
this.mapstatus = mapstatus;
this.sdg = sdg;
this.status = status;
this.statuscode = statuscode;
}
//Getters
public String getAppcode() {
return appcode;
}
public String getAcronym() {
return acronym;
}
public String getAppname() {
return appname;
}
public String getSys_id() {
return sys_id;
}
public String getMapstatus() {
return mapstatus;
}
public String getSdg() {
return sdg;
}
public String getStatus() {
return status;
}
public String getStatuscode() {
return statuscode;
}
//Setters
public void setAppcode(String appcode) {
this.appcode = appcode;
}
public void setAcronym(String acronym) {
this.acronym = acronym;
}
public void setAppname(String appname) {
this.appname = appname;
}
public void setSys_id(String sys_id) {
this.sys_id = sys_id;
}
public void setMapstatus(String mapstatus) {
this.mapstatus = mapstatus;
}
public void setSdg(String sdg) {
this.sdg = sdg;
}
public void setStatus(String status) {
this.status = status;
}
public void setStatuscode(String statuscode) {
this.statuscode = statuscode;
}
}
DAO:
#Repository
public class Employeedao {
#Autowired
private EntityManager em;
/**
* Method to fetch all employees from the db.
* #return
*/
#SuppressWarnings("unchecked")
public List<AVSApplication> getAllEmployees() {
return em.createNamedStoredProcedureQuery("procedure-one").getResultList();
}
}
Controller:
#RestController
public class Employeecontroller {
#Autowired
Employeedao edao;
/**
* Method to fetch all employees from the db.
* #return
*/
#RequestMapping(value= "/getall")
public void getAll() {
System.out.println("All objects: " + edao.getAllEmployees());
System.out.println("Get the first item in list: " + edao.getAllEmployees().get(0).getAppcode());
}
}
In given code there is nothing that would map rows returned by stored procedure AVSApplication instances:
#NamedStoredProcedureQueries(value= {
#NamedStoredProcedureQuery(name= "procedure-one", procedureName= "GetAllAppWithStatus")
})
If stored procedure matches nicely to entity, then definining result class can be enough:
#NamedStoredProcedureQueries(value= {
#NamedStoredProcedureQuery(
name= "procedure-one",
procedureName= "GetAllAppWithStatus",
resultClasses = {AVSApplication.class}
})
If there is some discrepancies, one must define SqlResultSetMapping and refer to it from resultsetMappings.

SDN4 is not returning nested Entities

Hello Stack overflow,
I have the following Problem:
I have these entity classes:
public class UnknownEntity extends NetworkEntity{
#Id
#GeneratedValue(strategy = UuidStrategy.class)
private String id;
#Override
public void setId(String id) {
this.id = id;
}
#Override
public String getId() {
return id;
}
}
#NodeEntity
public class NetworkEntity {
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Id
protected String id;
public List<NetworkInterfaceEntity> getInterfaces() {
return interfaces;
}
public void setInterfaces(List<NetworkInterfaceEntity> interfaces) {
this.interfaces = interfaces;
}
#Relationship(type = "is_composed_of")
protected List<NetworkInterfaceEntity> interfaces ;
}
#NodeEntity
public class NetworkInterfaceEntity {
public String getInterfaceId() {
return interfaceId;
}
public void setInterfaceId(String interfaceId) {
this.interfaceId = interfaceId;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public String getNetmask() {
return netmask;
}
public void setNetmask(String netmask) {
this.netmask = netmask;
}
public String getMacAddress() {
return macAddress;
}
public void setMacAddress(String macAddress) {
this.macAddress = macAddress;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public InterfaceState getState() {
return state;
}
public void setState(InterfaceState state) {
this.state = state;
}
public List<NetworkInterfaceEntity> getSubInterfaces() {
return subInterfaces;
}
public void setSubInterfaces(List<NetworkInterfaceEntity> subInterfaces) {
this.subInterfaces = subInterfaces;
}
public long getBytesSent() {
return bytesSent;
}
public void setBytesSent(long bytesSent) {
this.bytesSent = bytesSent;
}
public long getBytesRecived() {
return bytesRecived;
}
public void setBytesRecived(long bytesRecived) {
this.bytesRecived = bytesRecived;
}
#Id
private String interfaceId;
private String ipAddress;
private String netmask;
private String macAddress;
private String name;
private InterfaceState state;
#Relationship(type = "is_composed_of")
private List<NetworkInterfaceEntity> subInterfaces;
private long bytesSent;
private long bytesRecived;
}
When I now try to query the UnknownEntities via a Neo4j Crud Repository with a custom #Query Method, the UnknownEntities wont be nested with the necessary NetworkInterfaceObjects, even tough my query returns these.
public interface UnknownEntityRepository extends CrudRepository<UnknownEntity,String> {
#Query("MATCH (u:UnknownEntity)-[:is_composed_of]->(i:NetworkInterfaceEntity) WHERE i.ipAddress IN {0} WITH u as unknown MATCH p=(unknown)-[r*0..1]-() RETURN collect(unknown),nodes(p),rels(p)")
List<UnknownEntity> searchMachinesByIp(List<String> ipAddresses);
}
In this particular case the NetworkInterfaceEntities do not contain more subInterfaces, so I only want the NetworkInterfaceEntities that belong the the UnknownEntity. But when I use this Query I only get UnknownEntities where the NetworkInterfaceList is null. I even tried different Querys to no avail for example:
"MATCH p=(u:UnknownEntitie)-[:is_composed_of]-(n:NetworkInterfaceEntity) WHERE n.ipAddress in {0} RETURN collect(n),nodes(p),rels(p)".
My Question is, if what I want is even possible with SDN4 Data and if it is, how I can achieve this, Since my alternative is to query the database for every NetworkInterface separately, which I think is really ugly.
Any help would be much appreciated.
please try if returning the full path like this:
public interface UnknownEntityRepository extends CrudRepository<UnknownEntity,String> {
#Query("MATCH (u:UnknownEntity)-[:is_composed_of]->(i:NetworkInterfaceEntity) WHERE i.ipAddress IN {0} WITH u as unknown MATCH p=(unknown)-[r*0..1]-() RETURN p")
List<UnknownEntity> searchMachinesByIp(List<String> ipAddresses);
}
works for your. If not, try naming the objects in question, i.e. RETURN i as subInterfaces works for you.
Are you using Spring Data Neo4j 4 or 5? If you're on 4, consider the upgrade to 5 to be on a supported level.
Please let me know, if this helps.

Spring Boot API returns json without labels

I'm building a rest API with Java Spring Boot and I'm running into a problem, I have the following class with a method (which is in my controller for testing purposes, I will send its logic to the service later):
#RestController
#RequestMapping("/api/readings")
public class Readings {
#Autowired
private ReadingService readingService;
#RequestMapping(method = RequestMethod.GET, produces = "application/json")
public List<Reading> getRelevant(#RequestParam("start") String start, #RequestParam("end") String end){
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:MM:SS");
start += " 00:00:00";
end += " 23:59:59";
try {
Date startdate = df.parse(start);
Date enddate = df.parse(end);
return readingService.getRelevant(startdate, enddate);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
}
This makes use of a service that calls the following repository function:
#Query("SELECT pmtwofive, pmten, recording FROM Reading WHERE recording >= ?1 AND recording <= ?2")
List<Reading> getRelevant(Date start, Date end);
Everything works fine, except for the format of the result:
[[10,20,1505801743816],[14,21,1505802311976],[14,21,1505802330610],[10,13,1505803302960],[10,13,1505803321966]]
Instead of this, I was expecting something like I get when using the CrudRepository from hibernate querying my whole table instead of just these three values:
{
{
pmtwofive: 10,
pmten: 20,
reading: 1505801743816
},
{
...
}
}
What should I do to get my expected result? Thank you!
Reading Class:
package com.amione.models;
import javax.persistence.*;
import java.sql.Timestamp;
#Entity
public class Reading {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(columnDefinition = "serial")
private long reading_id;
private int sensor_id;
private int function;
private int directionstart;
private int pmtwofive;
private int pmten;
private int checksumlow;
private int checksumhigh;
private Timestamp recording;
public long getReading_id() {
return reading_id;
}
public void setReading_id(int reading_id) {
this.reading_id = reading_id;
}
public int getSensor_id() {
return sensor_id;
}
public void setSensor_id(int sensor_id) {
this.sensor_id = sensor_id;
}
public int getFunction() {
return function;
}
public void setFunction(int function) {
this.function = function;
}
public int getDirectionstart() {
return directionstart;
}
public void setDirectionstart(int directionstart) {
this.directionstart = directionstart;
}
public int getPmtwofive() {
return pmtwofive;
}
public void setPmtwofive(int pmtwofive) {
this.pmtwofive = pmtwofive;
}
public int getPmten() {
return pmten;
}
public void setPmten(int pmten) {
this.pmten = pmten;
}
public int getChecksumlow() {
return checksumlow;
}
public void setChecksumlow(int checksumlow) {
this.checksumlow = checksumlow;
}
public int getChecksumhigh() {
return checksumhigh;
}
public void setChecksumhigh(int checksumhigh) {
this.checksumhigh = checksumhigh;
}
public Timestamp getRecording() {
return recording;
}
public void setRecording(Timestamp recording) {
this.recording = recording;
}
}
Ok I have the answer. It must be done with custom constructor:
#Data
#EqualsAndHashCode(callSuper = true)
#Entity
public class City extends AbstractEntity {
#Column
private String name;
#Embedded
private Geopoint centre=new Geopoint();
public City(){}
public City(String name){
this.setName(name);
}
// #OneToMany(mappedBy="city")
// private Set<Place> places;
}
Repository:
public interface CityRepository extends JpaRepository<City, Long>{
City findOneByName(String name);
#Query("SELECT name FROM City")
public List<City> findMethod1();
#Query("SELECT c.name FROM City c")
public List<City> findMethod2();
Controller:
#Autowired
private CityRepository cityRepository;
#GetMapping("/test")
public List<City> test(){
List<City> ret=new ArrayList();
ret.addAll(cityRepository.findMethod1());
ret.addAll(cityRepository.findMethod2());
ret.addAll(cityRepository.findMethod3());
return ret;
}
and the result:
As you can see, 3rd method works. I told you it will came up.
As empty values are still serialized, you can use a DTO object to encapsule only required fields (and SELECT new EntityDTO(field1,field2,field3) FROM Entity)
Another option would bo to configure Jackson to not to serialize null values with annotation or configuratio, but that is just beyond the scope of question.

Spring Hibernate CRUD: ORA-00923: FROM keyword not found where expected

I've been receiving the "ORA-00923: FROM keyword not found where expected" error in my code. I am trying to implement CRUD operations using Spring Hibernate. I've checked for syntax errors as well as quotes in my sql query, but can't seem to detect anything out of the ordinary.
User Class:
package com.spring.model;
import javax.persistence.*;
#Entity
#Table(name="PATIENT_MODEL")
public class User {
private int id;
private String patientFirstName;
private String patientLastName;
private String patientEmail;
private String patientAddress1;
private String patientAddress2;
#Id
#GeneratedValue
#Column(name="PATIENT_ID")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name="PATIENT_FIRST_NAME")
public String getPatientFirstName() {
return patientFirstName;
}
public void setPatientFirstName(String patientFirstName) {
this.patientFirstName = patientFirstName;
}
#Column(name="PATIENT_LAST_NAME")
public String getPatientLastName() {
return patientLastName;
}
public void setPatientLastName(String patientLastName) {
this.patientLastName = patientLastName;
}
#Column(name="PATIENT_EMAIL_ADDRESS")
public String getPatientEmail() {
return patientEmail;
}
public void setPatientEmail(String patientEmail) {
this.patientEmail = patientEmail;
}
#Column(name="PATIENT_ADDRESS_LINE 1")
public String getPatientAddress1() {
return patientAddress1;
}
public void setPatientAddress1(String patientAddress1) {
this.patientAddress1 = patientAddress1;
}
#Column(name="PATIENT_ADDRESS_LINE_2")
public String getPatientAddress2() {
return patientAddress2;
}
public void setPatientAddress2(String patientAddress2) {
this.patientAddress2 = patientAddress2;
}
}
The problem is the #Column(name="PATIENT_ADDRESS_LINE 1"). Could it be the database column is actually named PATIENT_ADDRESS_LINE_1?
If you really need to use column whose name includes one or more spaces, then you need to instruct Hibernate to quote the column name. Also see Oracle documentation.

Categories