I'm trying to create compoundIndex on document in Spring. I could create manually on Mongoshell. But in Spring it's not working. Here is my code.
Document(collection = "Cars")
#CompoundIndexes({
#CompoundIndex(def = "{'brand':1,'model':1,'colour':1,'fuelTypes':1}", name = "cars_compound_indexes",unique = true)
})
public class Car {
private String brand;
private String model;
private List<FuelType> fuelTypes;
private String colour;
}
And also how can I update document when duplicate is entered.
Related
I have the QueueContent class that it has is a superclass of two others.
I get a String in JSON format that contains the information I need to extract. The super class is:
#Data
#JsonIgnoreProperties(ignoreUnknown = true)
public class QueueContent {
private String empresa;
private String empresa_cor;
private String empresa_contato;
private String empresa_url;
private String empresa_telefone;
private String empresa_idioma;
public QueueContent(String empresa, String empresa_cor, String empresa_contato, String empresa_url, String empresa_telefone, String empresa_idioma) {
this.empresa = empresa;
this.empresa_cor = empresa_cor;
this.empresa_contato = empresa_contato;
this.empresa_url = empresa_url;
this.empresa_telefone = empresa_telefone;
this.empresa_idioma = empresa_idioma;
}
public QueueContent() {
}
}
I'm using Lombok to generate Getters / Setters)
This is the child class:
#Data
public class EmailCameraOffline extends QueueContent {
private Timestamp camera_last_online;
private String camera_nome;
private String empresa_url_plataforma;
public EmailCameraOffline(String empresa, String empresa_cor, String empresa_contato, String empresa_url, String empresa_telefone, String empresa_idioma, Timestamp camera_last_online, String camera_nome, String empresa_url_plataforma) {
super(empresa, empresa_cor, empresa_contato, empresa_url, empresa_telefone, empresa_idioma);
this.camera_last_online = camera_last_online;
this.camera_nome = camera_nome;
this.empresa_url_plataforma = empresa_url_plataforma;
}
public EmailCameraOffline() {
}
}
So I've done:
EmailCameraOffline infosEmail = new ObjectMapper().readValue(content, EmailCameraOffline.class);
System.out.println(infosEmail);
And the output is:
EmailCameraOffline (camera_last_online = 2020-03-12 03: 01: 45.0, camera_nome = Pier Cam 1, empresa_url_platform = null)
How do I get my EmailCameraOffline object to have the superclass attributes initialized?
Everything should be loaded and initialized just fine, so calling:
System.out.println(infosEmail.getEmpresa());
should give expected value.
Problem
The problem is in the default implementation of toString() method (done via #Data) at EmailCameraOffline class, which does not include inherited fields.
Solution
To fix this you can "override" #Data's toString() implementation to include inherited fields as well using Lombok as:
#Data
#ToString(callSuper = true)
public class EmailCameraOffline extends QueueContent {
...
}
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!
what is the best way to represent the below properties in Spring for each category? Currently we have implemented for aaa properties. We always have two fields for each category.
We want to use the same POJO for all categories. Please suggest the best approach that fits.
Property file name package.properties
category.aaa.field1 = value1
category.aaa.field2 = value2
category.bbb.field1 = value1
category.bbb.field2 = value2
category.ccc.field1 = value1
category.ccc.field2 = value2
category.ddd.field1 = value1
category.ddd.field2 = value2
We have created a POJO with
#Data
public class CategoryPojo{
private String valueOne;
private String valueTwo;
}
we are reading it in #Configuration using #PropertySource
#Configuration
#ComponentScan(value = "com.category")
#PropertySource("classpath:package.properties")
public class CategoryConfig{
#Value("${category.aaa.field1}")
private String fieldOne;
#Value("${category.aaa.field2}")
private String fieldTwo;
#Bean(name = "getACategory")
public CategoryPojo getFields() {
return new CategoryPojo(fieldOne, fieldTwo);
}
}
You can, and should, use https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-typesafe-configuration-properties
To handle this.
#Data
#ConfigurationProperties(prefix="category")
public class MyProperties{
private CategoryPojo aaa;
private CategoryPojo bbb;
private CategoryPojo ccc;
private CategoryPojo ddd;
#Data
public static class CategoryPojo{
private String valueOne;
private String valueTwo;
}
}
You can then place #EnableConfigurationProperties(classes = MyProperties.class) on your main application class or another #Configuration and then #Autowire your MyProperties class where its needed.
I am learning spring boot. As a part of this learning, I am creating a invoicing application's backend using REST Webservices. Here is my JSON Request.
{
"invoice": {
"invoiceNumber":"KB123456",
"custId":"123",
"pricingId":"234",
"empId":"456",
"gstCode":"HSN1234",
"invoiceSubTotal":"1234.00",
"invoiceGst":"18%",
"invoiceGstAmount":"123.45",
"invoiceTotal":"1357.45",
"invoiceLineItems": [
{
"invoiceLineNo":"KB123456-1",
"invoiceLineDesc":"Des123",
"invoiceQty":"2",
"invoicePpu":"0.18",
"invoiceGstCode":"HSN1235",
"invoiceGstPercentage":"18%",
"invoiceLineAmount":"123",
"invoiceLineTaxAmount":"12",
"invoiceLineTotalAmount":"135"
},
{
"invoiceLineNo":"KB123456-2",
"invoiceLineDesc":"Des124",
"invoiceQty":"4",
"invoicePpu":"0.17",
"invoiceGstCode":"HSN1235",
"invoiceGstPercentage":"18%",
"invoiceLineAmount":"126",
"invoiceLineTaxAmount":"14",
"invoiceLineTotalAmount":"140"
}
]
}
}
invoiceLineItems can house up to 15 objects.
Here are my Entities Invoice and InvoiceLineItems
Invoice.Java
#Entity
public class Invoice {
#Id
#GeneratedValue
private long invoiceId;
private String invoiceNumber;
private long custId;
private long pricingId;
private long empId;
private String gstCode;
private String invoiceSubTotal;
private String invoiceGst;
private String invoiceGstAmount;
private String invoiceTotal;
#Transient
#OneToMany(mappedBy="invoice")
private List<InvoiceLineItems> invoiceLineItems;
}
InvoiceLineItems.Java
#Entity
public class InvoiceLineItems {
#Id
#GeneratedValue
private long invoiceLineId;
private String invoiceNumber;
private String invoiceLineNo;
private String invoiceLineDesc;
private String invoiceQty;
private String invoicePpu;
private String invoiceGstCode;
private String invoiceGstPercentage;
private String invoiceLineAmount;
private String invoiceLineTaxAmount;
private String invoiceLineTotalAmount;
#ManyToOne
private Invoice invoice;
}
Here is my REST Controller
#RestController
public class InvoiceResourceController {
#Autowired
InvoiceRepository invoiceRepository;
InvoiceLineRepository invoiceLineRepository;
#PostMapping("/invoice")
public ResponseEntity<Invoice> createInvoice(#RequestBody Invoice invoice) {
List<InvoiceLineItems> invoiceLineItemsList = invoice.getInvoiceLineItems();
Invoice savedInvoice = invoiceRepository.save(invoice);
/* for (int i = 0; i < invoiceLineItemsList.size(); i++) {
InvoiceLineItems invLn = new InvoiceLineItems();
invLn = invoiceLineItemsList.get(i);
invoiceLineRepository.save(invLn);
} */
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
.buildAndExpand(savedInvoice.getInvoiceNumber()).toUri();
return ResponseEntity.created(location).build();
}
}
Now, I have two tables Invoice and Invoice_Line_Items created by Spring Boot. I am able to persist the Invoice Entity to the Invoice table, but I'm struggling to get the InvoiceLineItems Array Object from request and persisting to Invoice_Line_Items table.
Any help will be appreciated.
Solved it.
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "invoiceNumber")
private List<InvoiceLineItems> invoiceLineItems;
I'm a newbie coder having just finished a 6 month coding crash-course. I'm working on a java webapp to demonstrate my skills, and the project idea I had involves retrieving JSON data from an API, something we didn't learn about in class. I made POJOs to match the JSON, and I'm trying to parse the JSON into java objects to store in a database, however my database tables are never filled with data when I run through the app. I suspect the problem is somewhere with my method to convert the JSON but any feedback is greatly appreciated. Here's all my code I think is relevant, sorry if its TMI. I also apologize if my code is ugly, I'm a beginner... Thanks!
API returns JSON like this:
{
"result":{
"status":1,
"num_results":1,
"total_results":500,
"results_remaining":499,
"matches":[{
"match_id":3188095188,
"match_seq_num":2784956606,
"start_time":1495079320,
"lobby_type":7,
"radiant_team_id":0,
"dire_team_id":0,
"players":[{
"account_id":86920222,
"player_slot":0,
"hero_id":18
},{
"account_id":61122568,
"player_slot":1,
"hero_id":85
},{
"account_id":10208661,
"player_slot":2,
"hero_id":13
},{
"account_id":106083675,
"player_slot":132,
"hero_id":50
}]
}]
}
}
My POJOs:
#Entity
#JsonIgnoreProperties(ignoreUnknown = true)
public class Result {
#JsonIgnore
#Id
#GeneratedValue
private int id;
#JsonProperty("status")
private int status;
#JsonProperty("num_results")
private int num_results;
#JsonProperty("total_results")
private int total_results;
#JsonProperty("results_remaining")
private int results_remaining;
#OneToMany
#JoinColumn(name = "result_id")
#ElementCollection(targetClass=Matches.class)
#JsonProperty("matches")
private List<Matches> matches;
// getters and setters
}
#Entity
#JsonIgnoreProperties(ignoreUnknown = true)
public class Matches {
#Id
#JsonProperty("match_id")
private int match_id;
#JsonIgnore
#ManyToOne
private Result result;
#JsonProperty("match_seq_num")
private int match_seq_num;
#JsonProperty("start_time")
private int start_time;
#JsonProperty("lobby_type")
private int lobby_type;
#JsonProperty("radiant_team_id")
private int radiant_team_id;
#JsonProperty("dire_team_id")
private int dire_team_id;
#OneToMany
#JoinColumn(name = "Matches_id")
#ElementCollection(targetClass=Players.class)
#JsonProperty("players")
private List<Players> players;
// getters and setters
}
#Entity
#JsonIgnoreProperties(ignoreUnknown = true)
public class Players {
#JsonIgnore
#Id
#GeneratedValue
private int id;
#JsonIgnore
#ManyToOne
private Matches matches;
#JsonProperty("account_id")
private int account_id;
#JsonProperty("player_slot")
private int player_slot;
#JsonProperty("hero_id")
private int hero_id;
// getters and setters
}
Services method to read and convert the JSON to objects (url is censored, don't want my API key to be public)
public class SteamService {
public static Result getMatchHistory(String steamid){
Result result = new Result();
String MatchHistoryUrl = "https:**URL**="+steamid;
RestTemplate restTemplate = new RestTemplate();
Result jsonresult = restTemplate.getForObject(MatchHistoryUrl, Result.class);
return jsonresult;
}
}
Controller
#Controller
#RequestMapping("")
public class HomeController {
#Autowired
private ResultsDao resultsDao;
#RequestMapping(value = "", method = RequestMethod.GET)
public String index(Model model){
model.addAttribute("title", "Welcome");
return "home/home";
}
#RequestMapping(value = "", method = RequestMethod.POST)
public String processSteamIdField(#RequestParam("steamid")String steamid, Model model) {
Result newresult = getMatchHistory(steamid);
resultsDao.save(newresult);
return "redirect:results";
}
}
DAO
#Repository
#Transactional
public interface ResultsDao extends CrudRepository<Result, Integer>{
}
Maybe my approach is a bit naive, but... If you want to store the JSON as string in the database, then I would use an object mapper for this:
new ObjectMapper().writeValueAsString(myObject);
and for reading a JSON and parsing it to a class I would do:
new ObjectMapper().readValue(JSON_STRING_HERE, "utf-8"), MyPOJO.class);
Also, if you already are using Spring, then your controller may look like this (for a POST, for example)
#RequestMapping(value = "/", method = RequestMethod.POST)
public MyPojo myController(#RequestBody MyPojo myBody) {
myRepository.save(myBody);
}
So, the parsing of the JSON that the client is sending to your app and your controller is already handled by Spring