Insert ID manually for JPA in Spring Boot - java

How can I insert id manually for this JPA entity in Spring boot? I don't want the id to be autogenerated. I tried sending a POST request using postman sending this JSON object to a RestController:
{
"id":"1",
"name":"New York"
}
I get an error saying that I should manually assing id. Why it is not taking the id that I'm passing in the request?
The Code:
Entity
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class City{
#Id
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long Id) {
this.Id = Id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Controller:
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class CityService{
private CityService cityService;
#Autowired
public void setCityService(CityService CityService) {
this.CityService = CityService;
}
#RequestMapping(method=RequestMethod.POST, value="/cities")
public void cities(#RequestBody City city){
cityService.save(city);
}
}
Service:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
#Service
public class CityService {
private CityRepository cityRepository;
#Autowired
public CityServiceImpl(CityRepository cityRepository) {
this.cityRepository= cityRepository;
}
#Override
public void saveCity(City city) {
CityRepository.save(city);
}
}

Theres probably something wrong with your setters. Try generating them again.

There was an old table with a different structure in the database. There was no error in the code.

Related

How to get selective columns in Export Csv in Spring boot

I am new to spring boot and i am creating a spring boot app to generate csv files from data fetched from database .I'm using h2 database for it and want to get selective columns from my entity-id,amount
entity class:
package com.reports.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity(name="reportDetails")
#Table(name = "reports")
public class Report {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="id")
private long id;
#Column(name="name")
private String name;
#Column(name="email")
private String email;
#Column(name="amount")
private int amount;
public Report() {
super();
}
public Report(int id, String name, String email, int amount) {
super();
this.id = id;
this.name = name;
this.email = email;
this.amount = amount;
}
public long getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
}
main class:
package com.reports;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.reports.entities.Report;
import com.reports.repository.ReportsRepository;
#SpringBootApplication
public class ExportCsvApplication implements CommandLineRunner {
#Autowired
ReportsRepository reportsRepository;
public static void main(String[] args) {
SpringApplication.run(ExportCsvApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
List<Report> reports = new ArrayList<>();
// create dummy employees
reports.add(new Report(1,"roy","roy#123.com",2500));
reports.add(new Report(2,"joy","joy#123.com",2500));
reports.add(new Report(3,"soy","soy#123.com",2500));
reports.add(new Report(4,"moy","moy#123.com",2500));
reports.add(new Report(5,"noy","noy#123.com",2500));
reportsRepository.saveAll(reports);
}
}
repository :
package com.reports.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.reports.entities.IReport;
import com.reports.entities.Report;
#Repository("reportsRepository")
public interface ReportsRepository extends JpaRepository<Report,Long>{
}
Service class:
package com.reports.services;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.reports.entities.IReport;
import com.reports.entities.Report;
import com.reports.repository.ReportsRepository;
#Transactional
#Service
public class ReportsService {
#Autowired
ReportsRepository reportsRepository;
public List<Report> fetchAll() {
return (List<Report>) reportsRepository.findAll();
}
}
Controller:
package com.reports.controllers;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.opencsv.CSVWriter;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import com.reports.entities.Report;
import com.reports.services.ReportsService;
#RestController
public class ReportsController {
#Autowired
ReportsService reportsService;
#GetMapping("/export-report")
public void exportCSV(HttpServletResponse response) throws Exception {
// set file name and content type
String filename = "details.csv";
response.setContentType("text/csv");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + filename + "\"");
// create a csv writer
StatefulBeanToCsv<Report> writer = new StatefulBeanToCsvBuilder<Report>(response.getWriter()).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER).withSeparator(CSVWriter.DEFAULT_SEPARATOR).withOrderedResults(false).build();
// write all employees to csv file
writer.write(reportsService.fetchAll());
}
}
I want to know what would be the best method to incorporate for it i tried query but faced errors.Please let me know how do i get this done
This is more of being related to the opencsv library than Spring or Spring Boot itself.
When constructing the StatefullBeanToCsvBuilder, you should use the withIgonreField builder property to instruct the final StatefullBeanToCsv on which fields to ignore for which types.
Say you want only the id and amount fields out of your Report entity, you can achieve this as follows:
#RestController
public class ReportsController {
#Autowired
ReportsService reportsService;
#GetMapping("/export-report")
public void exportCSV(HttpServletResponse response) throws Exception {
// set file name and content type
String filename = "details.csv";
response.setContentType("text/csv");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + filename + "\"");
// Configure the CSV writer builder
StatefulBeanToCsvBuilder<Report> builder = new StatefulBeanToCsvBuilder<Report>(response.getWriter()).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER).withSeparator(CSVWriter.DEFAULT_SEPARATOR).withOrderedResults(false);
// Ignore any field except the `id` and `amount` ones
Arrays.stream(Report.class.getDeclaredFields())
.filter(field -> !("id".equals(field.getName()) || "amount".equals(field.getName())))
.forEach(field -> builder.withIgnoreField(Report.class, field));
// create a csv writer
StatefulBeanToCsv<Report> writer = builder.build();
// write all employees to csv file
writer.write(reportsService.fetchAll());
}
}

Is there a way to make spring boot mongodb not changing your id attribute value to his object_id?

I am working in a project to learn spring boot, i have a problem where i have a attribute actor_id stored in mongodb with a value x but when i do mongoRepository.findall(), he changes the value of my actor_id to the value of the object_id generated automatically by mongodb, so even if i want to find a value by id i have to put the object_id value instead of the value of actor_id stored in database. Image below to better help understand.
I wanted that the returned value of a get http://localhost:8093/actors in actor_id be = 1 instead of 61634ad37e775d4b87635129.
Below is my code.
Actor.java:
package com.film.SpringAplication.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import org.springframework.data.mongodb.core.mapping.MongoId;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
#Document(collection="actor")
#AllArgsConstructor
#Data
public class Actor {
#Id
String actor_id;
String first_name;
String last_name;
}
ActorController.java
package com.film.SpringAplication.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.film.SpringAplication.model.Actor;
import com.film.SpringAplication.service.ActorService;
#RestController
#RequestMapping("/actors")
public class ActorController {
#Autowired
ActorService actorService;
#PostMapping
public String addActor(#RequestBody Actor actor) {
return actorService.addActor(actor);
}
#GetMapping
public List<Actor> getActors() {
return actorService.getActors();
}
#GetMapping("/{id}")
public List<Actor> getActor(#PathVariable String id) {
return actorService.getActor(id);
}
#DeleteMapping("/{id}")
public String deleteActor(#PathVariable String id) {
return actorService.deleteActor(id);
}
}
ActorService.java:
package com.film.SpringAplication.service;
import java.util.List;
import java.util.Optional;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import com.film.SpringAplication.model.Actor;
import com.film.SpringAplication.repository.ActorRepository;
import lombok.RequiredArgsConstructor;
#Service
#RequiredArgsConstructor
public class ActorService {
private final ActorRepository actorRepository;
private final MongoTemplate mongoTemplate;
public String addActor(Actor actor) {
actorRepository.save(actor);
return "Actor Added";
}
public List<Actor> getActors() {
List<Actor> lista = actorRepository.findAll();
return lista;
}
public List<Actor> getActor(String id) {
Query query=new Query()
.addCriteria(Criteria.where("actor_id").is(id));
return mongoTemplate.find(query,Actor.class);
//return actorRepository.findById(id);
}
public String deleteActor(String id) {
actorRepository.deleteById(id);
return "User deleted";
}
}
ActorRepository.java:
package com.film.SpringAplication.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.film.SpringAplication.model.Actor;
public interface ActorRepository extends MongoRepository<Actor,String>{
}
What you can do is, you can use #Field. You annotate #Id to actor_id. So basically it takes as the default primary key. You can do two things. You can annotate _id as default primary key.
#Document(collection="actor")
#AllArgsConstructor
#Data
public class Actor {
#Id
ObjectId _id;
String actor_id;
String first_name;
String last_name;
}
Else you can annotate #Field
#Document(collection="actor")
#AllArgsConstructor
#Data
public class Actor {
#Id
#Field("actor_id")
String actor_id;
String first_name;
String last_name;
}
Related answer

How can I reach database as json value when i request on my local browser?

Note: This is a project which has a connection with database on other tables. I just made a new table, but i must have something wrong in my codes, because i cant get what i want.
I have a City table, and this table has 3 columns, named id, name, city_id. And i imported a csv file, so when i query, I can see some data.
I wrote Entity, Repository, Controller, and Service, in Java on Eclipse
What should I do? For example, when i search like localhost:8181/mfc/city/getAllCities that should give me all the cities as json
Could you tell me what i should add?
City.java
package com.mfc.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="city")
public class City{
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
int id;
#Column(name="city_name")
String cityName;
#Column(name="city_id")
int cityId;
public City() {
super();
}
public City(int id, String cityName, int cityId) {
super();
this.id = id;
this.cityName = cityName;
this.cityId = cityId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
}
CityController.java
package com.mfc.admin.controller;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.mfc.admin.service.CityService;
import com.mfc.entity.City;
#RestController
#RequestMapping("/city")
public class CityController {
private static final Logger logger = LogManager.getLogger(CityController.class);
#Autowired
CityService cityService;
#RequestMapping(value="/getAllCities", method=RequestMethod.GET, headers = "Accept=application/json")
public List getCities() {
logger.trace("CityController: getAllCities begins");
List listOfCities = cityService.getAllCities();
logger.trace("CityController: getAllCities ends");
return listOfCities;
}
#RequestMapping(value="/getCity/{id}", method=RequestMethod.GET, headers = "Accept=application/json")
public City getCityById(#PathVariable int id) {
return cityService.getCity(id);
}
}
CityService.java
package com.mfc.admin.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.mfc.entity.City;
import com.mfc.repository.CityRepository;
#Service("cityService")
public class CityService {
#Autowired
CityRepository cityDTO;
#Transactional
public List getAllCities() {
return cityDTO.getAllCities();
}
#Transactional
public City getCity(int id) {
return cityDTO.getCity(id); // getCity is red here, there is mistake i guess
}
}
CityRepository.java
package com.mfc.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.mfc.entity.City;
public interface CityRepository extends JpaRepository<City, Integer>{
List getAllCities();
City getCity();
}
In the CityService you call the CityRepository like this
return cityDTO.getCity(id); // getCity is red here, there is mistake i guess
But no such method is defined in the CityRepository. Try using this line return cityDTO.findById(id).get();
You can't see the method findById(Integer id) in the CityRepository, but it is there, because the CityRepository extends JpaRepository<City, Integer>. Find some Spring Data tutorial to know what's really going on in here, long story short the Spring Data is able to generate a lot of standard methods for you.
The method cityDTO.findById(id) returns Optional<City>, not City. To get the instance of City, just add '.get()' method, as it is in the example. It should work for you if city exists in the database. For proper work with Optional find some tutorial. It is a wrapper of an object that may or may not be present, detailed explanation is out of the scope of this answer.
maybe you can try to set up message converter manualy, google MappingJackson2HttpMessageConverter and you'll know what to do.

Spring JPA "And" Methods and Not Null

Been having ridiculous trouble with using the AND in the CrudReposity. All I want to do it find if two things are Not Null and display them.
public interface StudentRepository extends CrudRepository<Student, Integer>{
List<Student> findByItemAIsNotNullAndItemBIsNotNull();
}
When I run this, it seems to be running the AND as an OR (I tried both), so it's showing things that all null in one of them.
Any Help will be appreciated
You Code is correct may be problem in other section. Otherwise you can see this code. It may help you. Here I skipped service layer though its for only test.
package com.example.stack;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Data{
#Id
#GeneratedValue
Integer id;
String itemA;
String itemB;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getItemA() {
return itemA;
}
public void setItemA(String itemA) {
this.itemA = itemA;
}
public String getItemB() {
return itemB;
}
public void setItemB(String itemB) {
this.itemB = itemB;
}
}
Repository Class
package com.example.stack;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
public interface TestRepository extends CrudRepository<Data, Integer>{
List<Data> findByItemAIsNotNullAndItemBIsNotNull();
}
Controller CLass
package com.example.stack;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping(value = "/test")
public class TestController {
#Autowired
TestRepository repo;
#GetMapping
public List<Data> getTest()
{
return (List<Data>) repo.findByItemAIsNotNullAndItemBIsNotNull();
}
}
Database :
Response :

Java Spring Boot problem LoggiFailureAnalysisReporter

I am new to Boot-Spring apparently, I mostly copy some code from youtube on this case. However, after modification, in the end, I got a message like this;
APPLICATION FAILED TO START
Description:
Field postService in com.example.demo.BlogController required a bean of type 'Server.PostService' that could not be found.
Action:
Consider defining a bean of type 'Server.PostService' in your configuration.
.....Any idea how to deal with this situation. Thank you for the support.
1stclass-BlogApplciation-----com.example.demo(package)
2nd-Blog Controller--------same package as BlogApplication
3rdclass-Post---entities
4rthclass-PostRepositories---Repositories
**package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class BlogApplication {
public static void main(String[] args) {
SpringApplication.run(BlogApplication.class, args);
}
}**
**package com.example.demo;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import Server.PostService;
import entities.Post;
import java.util.Date;
#RestController
public class BlogController {
#Autowired
private PostService postService;
#GetMapping(value="/")
public String index() {
return "index";
}
#GetMapping(value="/posts")
public List<Post>posts(){
return postService.getAllPosts();
}
#PostMapping(value="/post")
public void publishPost(#RequestBody Post post) {
if(post.getDatecreation() == null)
post.setDatecreation(new Date());
postService.insert(post);
}
}**
**package entities;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Post {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String title;
private String body;
private Date Datecreation;
public Post() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String gettitle() {
return title;
}
public void settitle(String title) {
this.title= title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public Date getDatecreation() {
return Datecreation;
}
public void setDatecreation(Date datecreation) {
this.Datecreation = datecreation;
}
}**
**package Repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import entities.Post;
#Repository
public interface PostRepository extends JpaRepository<Post,Long>{
}**
Your BlogApplication Class, which is the class annotated with #SpringBootApplication is in the package com.example.demo. That means that, by default, Spring is going to launch a Component Scan starting from that package.
The problem is that your class PostService and your interface PostRepository are not in the same package as (or in a sub-package of) com.example.demo, so Spring can't find them and won't automatically create these beans for you.
To correct this issue, move the packages you created inside your root package (com.example.demo).
You can find more information about the use of #SpringBootApplication here.
EDIT:
You are missing PostService class or you have imported incorrect class as Server.PostService.
try to create a service like this one:
#Component
public class PostService {
public List<Post> getAllPosts(){
//your code
}
}

Categories