Ok so I am new to spring and don't really know how this works. I have been trying a few things and think its close to doing it but not getting any data from the server and giving me this error
Unsatisfied dependency expressed through constructor argument with index 4 of type [jp.co.fusionsystems.dimare.crm.service.impl.MyDataDefaultService]: : Error creating bean with name 'MyDataDefaultService' defined in file
My end point
//mobile data endpoint
#RequestMapping(
value = API_PREFIX + ENDPOINT_MyData + "/getMyData",
method = RequestMethod.GET)
public MyData getMyData() {
return MyDataDefaultService.getData();
}
My Object
public class MyData {
public MyData(final Builder builder) {
videoLink = builder.videoLink;
}
private String videoLink;
public String getVideoLink()
{
return videoLink;
}
public static class Builder
{
private String videoLink = "";
public Builder setVideo(String videoLink)
{
this.videoLink = videoLink;
return this;
}
public MyData build()
{
return new MyData(this);
}
}
#Override
public boolean equals(final Object other) {
return ObjectUtils.equals(this, other);
}
#Override
public int hashCode() {
return ObjectUtils.hashCode(this);
}
#Override
public String toString() {
return ObjectUtils.toString(this);
}
}
The Repository
public classMyServerMyDataRepository implements MyDataRepository{
private finalMyServerMyDataJpaRepository jpaRepository;
private final MyDataConverter MyDataConverter = new MyDataConverter();
#Autowired
publicMyServerMyDataRepository(finalMyServerMyDataJpaRepository jpaRepository) {
this.jpaRepository = Validate.notNull(jpaRepository);
}
#Override
public MyData getData() {
MyDataEntity entity = jpaRepository.findOne((long) 0);
MyData.Builder builder = new MyData.Builder()
.setVideo(entity.getVideoLink());
return builder.build();
}
The DefaultService that gets called by the endpoint
public class MyDataDefaultService {
private static final Logger logger = LoggerFactory.getLogger(NotificationDefaultService.class);
private finalMyServerMyDataRepository repository;
#Autowired
public MyDataDefaultService(MyServerMyDataRepository repository) {
this.repository = Validate.notNull(repository);
}
//Get the data from the server
public MobileData getData()
{
logger.info("Get Mobile Data from the server");
//Get the data from the repository
MobileData mobileData = repository.getData();
return mobileData;
}
}
The Converter
public class MyDataConverter extends AbstractConverter<MyDataEntity, MyData>
{
#Override
public MyData convert(MyDataEntity entity) {
MyData.Builder builder = new MyData.Builder()
.setVideo(entity.getVideoLink());
return builder.build();
}
}
My Entity
#Entity
#Table(name = “myServer”)
public class MyDataEntity extends AbstractEntity{
#Column(name = "video_link", nullable = true)
private String videoLink;
public String getVideoLink() {
return videoLink;
}
public void setVideoLink(final String videoLink) {
this.videoLink = videoLink;
}
}
Thank you for any help with this
Hibernate entity should have default constructor defined and implement Serializable interface as well, assume AbstractEntity matches the requirement. Hibernate won't accept an entity without a primary key so you have to define the one too:
#Entity
#Table(name = “myServer”)
public class MyDataEntity implements Serializable {
#Id
#GeneratedValue
private Long id;
#Column(name = "video_link", nullable = true)
private String videoLink;
public MyDataEntity() {
}
...setters&getters
}
MyData object represents the JSON server response, you can use Jackson annotations to control the result JSON properties:
public class MyDataResponse {
#JsonProperty("video_link")
private String videoLink;
public MyDataResponse() {
}
public MyDataResponse(String videoLink) {
this.videoLink = videoLink;
}
...setters&getters
}
Spring has an awesome project so called Spring Data that provides the JPA repositories, so there's no even the #Repository annotation ever needed:
public class MyDataRepository extends CrudRepository<MyDataEntity, Long> {
}
The Builder class represents the Service layer:
#Service
public class MyDataService {
#Autowired
private MyDataRepository myDataRepository;
public MyDataResponse getMyData(Long id) {
MyDataEntity entity = myDataRepository.findOne(id);
...rest logic, copy necessary data to MyDataResponse
}
}
Then a controller is:
#RestController // #ResponseBody not needed when using like this
public MyDataController {
#Autowired
private MyDataService myDataService;
#RequestMapping("/getMyData") // no need to specify method for GET
public MyDataResponse getMyData(#RequestParam("ID") Long myDataId) {
... validation logic
return myDataService.getMyData(myDataId); // return response
}
}
Now it should work, don't forget to add required dependencies to your classpath.
Related
findAll() of mongoRepository returns empty list. what is wrong with the below code?
API used for counting the number of documents in the collection works fine.
Controller
#RestController
#RequestMapping("/api/api-management/scopes")
public class AuthScopesController {
private final ScopesService scopesService;
#Autowired
AuthScopesController(ScopesService scopesService) {
this.scopesService = scopesService;
}
#PostMapping("/")
public AuthScope createScope(#RequestBody AuthScope authScope) {
return scopesService.createAuthScope(authScope);
}
#GetMapping("/")
public List<AuthScope> getAllScopes() {
return scopesService.getAuthScopes();
}
}
service
#Service
public class ScopesService {
private final AuthScopeRepository authScopeRepository;
public ScopesService(AuthScopeRepository authScopeRepository) {
this.authScopeRepository = authScopeRepository;
}
public AuthScope createAuthScope(AuthScope authScope) {
return authScopeRepository.save(authScope);
}
//TODO: recheck
public List<AuthScope> getAuthScopes() {
return authScopeRepository.findAll();
}
}
repository
#Repository
public interface AuthScopeRepository extends MongoRepository<AuthScope, String> {
Optional<AuthScope> findByScope(String id);
}
model is as follows
#Data
#Document("auth-scopes")
public class AuthScope {
#Id
private String scope;
private String belongsToApi;
private String belongsToApiTitle;
private String description;
}
found the issue. in order to findAll() to work, the model has to have deleted status.
I've updated the model as follows
#Data
#Document("auth-scopes")
public class AuthScope {
#Id
private String scope;
private String belongsToApi;
private String belongsToApiTitle;
private String description;
private boolean deleted;
}
I'm trying to do an application using Spring Boot MVC and I've run into a problem. For the Post and Put methods I receive status 200 ok but the values are "null". The new registration on database is created but just the Id (autoincrement) column is populated and received in Postman response. Could someone help me please?
` #RequestMapping("/api")
#RestController
public class ExtractedNumbersController {
private final ExtractedNumbersService extractedNumbersService;
#Autowired
public ExtractedNumbersController(ExtractedNumbersService extractedNumbersService) {
this.extractedNumbersService = extractedNumbersService;
}
#PostMapping("/addExtractedNumbers")
public ExtractedNumbers addExtractedNumbers(#RequestBody ExtractedNumbers extractedNumbers) {
return extractedNumbersService.addExtractedNumbers(extractedNumbers);
}
#GetMapping("/findAllExtractedNumbers")
public List<ExtractedNumbers> findAllActivities() {
return extractedNumbersService.findAllExtractedNumbers();
}
#GetMapping("findExtractedNumbersById/{id}")
public Optional<ExtractedNumbers> findExtractedNumbersById(#PathVariable("id") Integer id) {
return extractedNumbersService.findByIdExtractedNumbers(id);
}
#PutMapping("/updateExtractedNumbers/{id}")
public ExtractedNumbers updateProduct(#PathVariable("id") Integer id, #RequestBody ExtractedNumbers extractedNumbers) {
Optional<ExtractedNumbers> extractedNumbersFromDatabase = extractedNumbersService.findByIdExtractedNumbers(id);
if (extractedNumbersFromDatabase.isPresent()) {
extractedNumbersFromDatabase.get().setExtractedNumbers(extractedNumbers.getExtractedNumbers());
extractedNumbersFromDatabase.get().setExtractionDate(extractedNumbers.getExtractionDate());
final ExtractedNumbers updatedExtractedNumbers = extractedNumbersService.addExtractedNumbers(extractedNumbersFromDatabase.get());
return updatedExtractedNumbers;
}
return extractedNumbersService.addExtractedNumbers(extractedNumbers);
}
#DeleteMapping("/deleteExtractedNumbersById/{id}")
public void deleteExtractedNumbersById(#PathVariable("id") Integer id) {
extractedNumbersService.deleteExtractedNumbers(id);
}
}
#Data
#Table
#Entity
#AllArgsConstructor
#NoArgsConstructor
public class ExtractedNumbers {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer extractedNumbersId;
#Column
private String extractedNumbers;
#Column
private String extractionDate;
public ExtractedNumbers(String extractedNumbers, String extractionDate) {
this.extractedNumbers = extractedNumbers;
this.extractionDate = extractionDate;
}
public String getExtractedNumbers() {
return extractedNumbers;
}
public void setExtractedNumbers(String extractedNumbers) {
this.extractedNumbers = extractedNumbers;
}
public String getExtractionDate() {
return extractionDate;
}
public void setExtractionDate(String extractionDate) {
this.extractionDate = extractionDate;
}
}
public interface ExtractedNumbersService {
List<ExtractedNumbers> findAllExtractedNumbers();
ExtractedNumbers addExtractedNumbers(ExtractedNumbers extractedNumbers);
Optional<ExtractedNumbers> findByIdExtractedNumbers(Integer extractedNumbersId);
ExtractedNumbers update(ExtractedNumbers extractedNumbers);
void deleteExtractedNumbers(Integer extractedNumbersId);
}
#Service
public class ExtractedNumbersServiceImpl implements ExtractedNumbersService {
private final ExtractedNumbersRepository extractedNumbersRepository;
public ExtractedNumbersServiceImpl(ExtractedNumbersRepository extractedNumbersRepository) {
this.extractedNumbersRepository = extractedNumbersRepository;
}
#Override
public List<ExtractedNumbers> findAllExtractedNumbers() { return extractedNumbersRepository.findAll() ; }
#Override
public ExtractedNumbers addExtractedNumbers(ExtractedNumbers extractedNumbers) {
return extractedNumbersRepository.save(extractedNumbers);
}
#Override
public Optional<ExtractedNumbers> findByIdExtractedNumbers(Integer extractedNumbersId) {
return extractedNumbersRepository.findById(extractedNumbersId);
}
#Override
public ExtractedNumbers update(ExtractedNumbers extractedNumbers) {
return extractedNumbersRepository.save(extractedNumbers);
}
#Override
public void deleteExtractedNumbers(Integer extractedNumbersId) {
extractedNumbersRepository.deleteById(extractedNumbersId);
}
}`
[Database][1]
Postman
Extracted Numbers Class
Are your attributes in ExtractedNumbers consistent with the database table column?
if your table column is like extracted_numbers you need to do the underline to camel
I want to store a List of class : RestApiResponse into MySql. But getting below error:
org.hibernate.HibernateException: Could not determine a type for class: com.try.sreapi.beans.RestApiResponse
Below are my classes:
Entity class : SREAPITestingHistory.java
#NamedQueries(#NamedQuery(name="getSREAPITestHistory.findAll", query="SELECT a FROM SREAPITestingHistory a"))
#SqlResultSetMapping(name="sreapitestinghistoryres",
entities=#EntityResult(entityClass=SREAPITestingHistory.class))
#Entity
#Table(name="sreapi_testing_history_details")
#Transactional
public class SREAPITestingHistory implements Serializable{
private static final long serialVersionUID = -7221709766109001257L;
#Id
#Column(name="request_time")
private String request_time;
#Column(name="req_id")
private String req_id;
#Column(name="app_name")
private String app_name;
#Column(name="request_name")
private String request_name;
#Lob
#Column(name="response_body")
private List<RestApiResponse> response;
public String getRequest_time() {
return request_time;
}
public void setRequest_time(String request_time) {
this.request_time = request_time;
}
public String getReq_id() {
return req_id;
}
public void setReq_id(String req_id) {
this.req_id = req_id;
}
public String getApp_name() {
return app_name;
}
public void setApp_name(String app_name) {
this.app_name = app_name;
}
public String getRequest_name() {
return request_name;
}
public void setRequest_name(String request_name) {
this.request_name = request_name;
}
public List<RestApiResponse> getResponse() {
return response;
}
public void setResponse(List<RestApiResponse> response) {
this.response = response;
}
}
Repository Class: SREAPITestingRepository.java
#Repository
public interface SREAPITestingRepository extends CrudRepository< SREAPITestingHistory, String> {
#Modifying
#Transactional
#Query(value="INSERT into sreapi_testing_history_details (request_time,req_id,app_name,request_name,response_body)"+ "VALUES (:request_time,:req_id,:app_name,:request_name,:response_body)", nativeQuery = true)
public void setApiTestHistoryDetails(#Param("request_time") String request_time,#Param("req_id") String req_id,#Param("app_name") String app_name,#Param("request_name") String request_name,#Param("response_body") List<RestApiResponse> response_body);
}
When I am trying to add values for response_body which is actually a List of RestApiResponse class and I am getting Could not determine a type for class: com.try.sreapi.beans.RestApiResponse exception
From Official doc
A Lob may be either a binary or character type.
The Lob type is inferred from the type of the persistent field or
property, and except for string and character-based types defaults to
Blob.
Example 1:
#Lob #Basic(fetch=LAZY) #Column(name="REPORT")
String report;
Example 2:
#Lob #Basic(fetch=LAZY) #Column(name="EMP_PIC",
columnDefinition="BLOB NOT NULL") protected byte[] pic;
So you can convert your list of data into json string or bytes to store.
I want to get some data from Neo4j using Spring boot, but I always get nothing. In other words, it seems that java cannot get the data from the neo4j database.
The code is written according to the neo4j Spring tutorial.https://neo4j.com/developer/spring-data-neo4j/
domain class
#NodeEntity
public class Weather {
#Id
#GeneratedValue
private Long id;
private String name;
#Relationship(type = "HAS_INSTANCE")
private List<Instance> instances = new ArrayList<>();
#Relationship(type = "HAS_CHARACTERISTIC")
private List<Characteristic> characteristics = new ArrayList<>();
...
}
repository class
#RepositoryRestResource(collectionResourceRel = "weathers", path = "weathers")
public interface WeatherRepository extends Neo4jRepository<Weather, Long> {
}
service class
#Service
public class WeatherService {
private final WeatherRepository weatherRepository;
public WeatherService(WeatherRepository weatherRepository){
this.weatherRepository = weatherRepository;
}
#Transactional(readOnly = true)
public Iterable<Weather> findAll(){
Iterable<Weather> result = weatherRepository.findAll();
return result;
}
}
controller class
#RestController
#RequestMapping("/")
public class WeatherController {
private final WeatherService weatherService;
public WeatherController(WeatherService weatherService){
this.weatherService = weatherService;
}
#GetMapping("/findAll")
public Iterable<Weather> findAll(){
return weatherService.findAll();
}
}
And the username and password configuration are in the application.properties.
Could someone help me about it? Thanks!
I'm writing web application using SpringMVC. I would like to keep some data in session until user logout. Earlier I did it by #SessionAttributes("someData"), but then I had to put #ModelAttribute("someData") someDataType someData as argument for every request mapping method. So this is what I did :
My AccessData class :
#Component
#Scope(value = "session")
public class AccessData {
private long userID;
private String userKey;
public AccessData(long ID, String key) {
this.userID = ID;
this.userKey = key;
}
public long getUserID() {
return userID;
}
public void setUserID(long userID) {
this.userID = userID;
}
public String getUserKey() {
return userKey;
}
public void setUserKey(String userKey) {
this.userKey = userKey;
}
}
First controller(here I'm getting and validating user input from form) :
#Controller
#Scope(value = "session")
public class LoginController {
#ModelAttribute("accessData")
public AccessData getAccessData() {
return this.accessData;
}
private Utils utilsService;
private LoginService loginService;
#Autowired
private AccessData accessData;
#Autowired
public LoginController(LoginService loginService, Utils utils) {
this.loginService = loginService;
this.utilsService = utils;
}
#RequestMapping(value = ControllerPaths.LOGIN, method = RequestMethod.POST)
public ModelAndView showLoginStatus(
#ModelAttribute(LOGINDATA) LoginData loginData) {
try {
accessData = loginService.validateLoginData(loginData);
} catch (IncorrectLoginDataException e) {
logger.trace("Showing fail login screen...");
return utilsService.getShowView(ViewPaths.LOGIN_FAIL);
} catch (HTTPException e) {
return utilsService.getShowViewWithStringAttribute(
ViewPaths.INFO_VIEW, MESSAGE, CONNECTION_ERROR);
}
return utilsService.getShowView(ViewPaths.LOGIN_SUCCESS);
}
}
Second controller :
#Controller
#Scope(value = "session")
public class SecondController {
#ModelAttribute("accessData")
public AccessData getAccessData() {
return this.accessData;
}
private Utils utilsService;
private LoginService loginService;
#Autowired
private AccessData accessData;
#Autowired
public SecondController(LoginService loginService, Utils utils) {
this.loginService = loginService;
this.utilsService = utils;
}
#RequestMapping(value = ControllerPaths.SHOW_ACCESS_DATA, method = RequestMethod.GET)
public ModelAndView showAccessData(
System.out.println(accessData.getUserKey());
return utilsService.getShowView(ViewPaths.INDEX);
}
}
The problem is that when I'm printing userKey value in second controller, the value is null. I checked if I'm getting correct data from server in LoginController and it's ok. So what am I doing wrong? Thanks in advance for help
The problem is that you are assigning a new object to the accessData variable. Instead you should update the field of the object that it is already referring to.
accessData = loginService.validateLoginData(loginData);
// Replace above line with something like this. Implement the copyProperties
// method to copy the attributes you need
AccessData newAccessData = loginService.validateLoginData(loginData);
copyPropteries(accessData,newAccessData);
Also it is not required to make the Controllers session scoped, add proxyMode=TARGET_CLASS to the scope annotation of the AccessData class.