How i can separate a table which have null and non null elements using spring concept - spring

for instance, I have a table with different locations and their description too. Now I need to print the locations which have descriptions on one page or in one box and simultaneously the locations which do not have descriptions should be displayed on another page.
NOTE:
this has to be done by using spring concept only
for reference, I was able to print the locations which have no descriptions in the below fashion.
entity
package com.test.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
#Entity
#Table(name= "loc_dtls")
public class Location {
#Id
#GeneratedValue(strategy = jakarta.persistence.GenerationType.IDENTITY)
private long id;
#Column(name="place_name")
private String placeName;
#Column(name="place_description")
private String placeDesc;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getPlaceName() {
return placeName;
}
public void setPlaceName(String placeName) {
this.placeName = placeName;
}
public String getPlaceDesc() {
return placeDesc;
}
public void setPlaceDesc(String placeDesc) {
this.placeDesc = placeDesc;
}
#Override
public String toString() {
return "Location [id=" + id + ", placeName=" + placeName + ", placeDesc=" + placeDesc + "]";
}
}
controller
#GetMapping("/")
public String singleElement(Model m) {
List<Location> util = locRepo.findByplaceDesc(null);
m.addAttribute("unlist_places", util);
return "index";
}
repository
#Repository
public interface LocationRepository extends JpaRepository<Location, Long> {
public List<Location> findByplaceName(String placeName);
public List<Location> findByplaceDesc(String placeDesc);
}
html
<select>
<option>--select--</option>
<option th:each="p : ${unlist_places}"
th:text="${p.placeName}">
</option>
</select>
MySql Database

Related

Java Spring Boot Entites not saving to JpaRepository

That's my first project with Spring Boot implemented. I tried going step by step with official Spring tutorial but I'm stuck with a problem that I can't find any answer about.
Whenever I try to call findAll() or find() method on my repository it returns empty array [].
Even with manual preloading enitites like done in tutorial and immediately trying to display database content I get the same result.
I can guess I'm missing something silly, but I can't figure it out for some hours now. What's the cause? Tomcat/jpa/spring version mismatch? Missing annotation somewhere?
Here's my AnimalRepository.java
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface AnimalRepository extends JpaRepository<Animal, Long> {
}
LoadDatabase.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.Transactional;
#Configuration
class LoadDatabase {
private static final Logger log = LoggerFactory.getLogger(LoadDatabase.class);
#Bean
CommandLineRunner initDatabase(AnimalRepository repository) {
return args -> {
log.info("Preloading " + repository.save(new Lion("Bilbo")));
log.info("Preloading " + repository.save(new Lion("Frodo")));
log.info(repository.findAll().toString()); //try to log content to console
};
}
}
The logging above basically ends up with this console output:
logging result
Probably not as important, but AnimalController.java
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
public class AnimalController {
private final AnimalRepository repository;
AnimalController(AnimalRepository repository) {
this.repository = repository;
}
#GetMapping("/animals")
List<Animal> all() {
repository.save(new Lion("Bilbo")); //this doesn't work either
return repository.findAll();
}
#PostMapping("/animals")
Animal newAnimal(#RequestBody Animal newAnimal) {
return repository.save(newAnimal);
}
#GetMapping("/animals/{id}")
Animal one(#PathVariable Long id) {
return repository.findById(id)
.orElseThrow(() -> new AnimalNotFoundException(id));
}
#PutMapping("/animals/{id}")
Animal replaceAnimal(#RequestBody Animal newAnimal, #PathVariable Long id) {
return repository.findById(id)
.map(animal -> {
animal.setName(newAnimal.getName());
animal.setSpecies(newAnimal.getSpecies());
return repository.save(animal);
})
.orElseGet(() -> {
newAnimal.setId(id);
return repository.save(newAnimal);
});
}
#DeleteMapping("/animals/{id}")
void deleteAnimal(#PathVariable Long id) {
repository.deleteById(id);
}
}
And the finally Lion.java
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import java.util.Objects;
#Entity
public class Lion implements Animal {
private #Id
#GeneratedValue Long id;
private String name;
private String species;
private int requiredFood;
//private Zone zone;
public Lion(String name) {
this.name = name;
this.species = this.getClass().getSimpleName();
this.requiredFood = LION_REQUIRED_FOOD;
}
public Lion() {
}
#Override
public Long getId() {
return id;
}
#Override
public void setId(Long id) {
this.id = id;
}
#Override
public String getName() {
return name;
}
#Override
public void setName(String name) {
this.name = name;
}
#Override
public String getSpecies() {
return species;
}
#Override
public void setSpecies(String species) {
this.species = species;
}
#Override
public int getRequiredFood() {
return requiredFood;
}
#Override
public void setRequiredFood(int requiredFood) {
this.requiredFood = requiredFood;
}
#Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Animal animal))
return false;
return Objects.equals(this.id, animal.getId()) && Objects.equals(this.name, animal.getName())
&& Objects.equals(this.species, animal.getSpecies());
}
#Override
public int hashCode() {
return Objects.hash(this.id, this.name, this.species);
}
#Override
public String toString() {
return "Animal{" + "id=" + this.id + ", name='" + this.name + '\'' + ", species='" + this.species + '\'' + '}';
}
}
I tried switching JpaRepository to CrudRepository, but that didn't work out.
I think the problem here is that your data haven't been saved to the database, because of the transaction. try to change your repository.save() to repository.saveAndFlush()

Adding default values for collection of objects inside outer object

I am trying to add default values to property attributes.I have one class inside which i have other class type injected as list.
I am able to get the default values for all attributes even on dependent class.I want to know is there any way using #value to add one more list of default values of custom objects.
My model classes are-
package com.example.test.Model;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
#Component
public class Employee {
#Value("1")
private Integer id;
#Value("Anubham")
private String name;
#Autowired
private List<Departments>departments;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Departments> getDepartments() {
return departments;
}
public void setDepartments(List<Departments> departments) {
this.departments = departments;
}
public Employee() {
super();
}
public Employee(Integer id, String name, List<Departments> departments) {
super();
this.id = id;
this.name = name;
this.departments = departments;
}
#Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", departments=" + departments + "]";
}
}
Another one is:
package com.example.test.Model;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
#Component
public class Departments {
#Value("1")
private int id;
#Value("computer")
String subject;
public Departments() {
super();
}
public Departments(int id, String subject) {
super();
this.id = id;
this.subject = subject;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
#Override
public String toString() {
return "Departments [id=" + id + ", subject=" + subject + "]";
}
}
I am getting output as Employee [id=1, name=Anubham, departments=[Departments [id=1, subject=computer]]].
I want to have one more record for departments field.
I wonder is it possible using #value without using any other way.
In your example "Departments" is a bean that is injected into Employee bean. If you want to have multiple departments, you have to create interface/abstraction "Department" and implement it in beans with concrete values that you want (DepartmentA, DepartmentB).
But Value annotation is not meant do inject static content but rather values from properties files. I don't know what you want to achieve this way.

#OneToOne(cascade = {CascadeType.ALL}) problem

I have a problem with my code. I do a little CarRent webservice and when i try to assign Errand to the car, errand which i want to assign is add to list of errands...
this is controller of errand
package com.RentCar.Rent_A_car.domain.Controllers;
import com.RentCar.Rent_A_car.domain.Car;
import com.RentCar.Rent_A_car.domain.Errand;
import com.RentCar.Rent_A_car.domain.Services.CarService;
import com.RentCar.Rent_A_car.domain.Services.ErrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
#Controller
public class ErrandController {
#Autowired
CarService carService;
#Autowired
ErrandService errandService;
#RequestMapping("/assignErrand")
public String assignQuest(#RequestParam("plate") String plate, Model model){
Car car = carService.getCar(plate);
List<Errand> errandList = errandService.getAllCurrentErrands();
model.addAttribute("car",car);
model.addAttribute("errands",errandList);;
return "assignErrand";
}
#RequestMapping(value = "/assignErrand", method = RequestMethod.POST)
public String assignQuest(Car car){
carService.updateCar(car);
System.out.println("assignquest");
return "redirect:/cars";
}
These are my repositories
#Repository
public class CarsRepository {
// class to do CRUD operation on cars and errands
Map<String, Car> CarList = new HashMap<>();
#PersistenceContext
private EntityManager em;
#Transactional
public void AddCar (String mark, String plate, int mileage){
Car newCar = new Car(mark, plate, mileage);
em.persist(newCar);
}
//pobiera aktualne id i dodaje do mapy
#Transactional
public void AddCar(Car car) {
em.persist(car);
}
// dla każdego "powyzej" usuniętego trzeba zmniejszyć id o 1 ; pętla o dlugosci pozostałych aut id--; KONIECZNE FINALNIE, do budowy nie
#Transactional
public void DellateCar(String plate){
Car c = em.find(Car.class, plate);
em.remove(c);
}
public Car getCar(String plate){
Car car = em.createQuery("from Car c where c.plate=:plate", Car.class)
.setParameter("plate", plate).getSingleResult();
return car;
}
public Collection<Car> getAllCars() {
return em.createQuery("from Car",Car.class).getResultList();
}
#Transactional
public void updateCar(Car car) {
em.merge(car);
}
// public String getPlate() {
// if (CarList.isEmpty()) {
// return "Car list is empty";
// } else {
// return (String)CarList.keySet();
// }
// }
// #PostConstruct
// public void build() {
// AddCar("BMW","DW",100000);
// AddCar("Opel","DTR",100043);
// AddCar("Toyota","WB",1012300);
// AddCar("Audi","DST",102340);
//
// }
#Override
public String toString() {
return "CarsRepository{" +
"CarList=" +
'}' + "\n";
}
}
Nr
#Repository
public class ErrandRepository {
#PersistenceContext
private EntityManager ee;
List<Errand> ErrandList = new ArrayList<>();
#Transactional
public void createErrand(String description) {
Errand newErrand = new Errand(description);
ee.persist(newErrand);
System.out.println(newErrand);
}
public void createErrand(Errand errand){ErrandList.add(errand);}
public List<Errand> getAll () {
return ee.createQuery("from Errand", Errand.class).getResultList();
}
public void delateErrand(Errand errand) {
ee.remove(errand);
}
#Transactional
public void delateErrand(int x) {
ErrandList.remove(x);
}
public Errand getErrandId(Integer x){
return ee.find(Errand.class, x );
}
#PostConstruct
#Transactional
public void init(){
Errand e1 = new Errand("zlecenie na wrocław");
Errand e2 = new Errand("zlecenie na wasdw");
Errand e3 = new Errand("zlecenie na wfgasfdław");
}
#Override
public String toString() {
return "ErrandRepository{" +
"ErrandList=" + ErrandList +
'}';
}
}
this is a part of CarService
public void updateCar(Car car) {
carsRepository.updateCar(car);
System.out.println("tu sie wywołuje updatecar");
}
i don't know what is a problem... can you help me ?
edit, i add car and errand class
package com.RentCar.Rent_A_car.domain;
import javax.persistence.*;
import javax.persistence.Entity;
#Entity
public class Car {
// #Id
// #GeneratedValue(strategy = GenerationType.AUTO)
// public int id;
String mark;
#Id
String plate;
int mileage;
#OneToOne(cascade = CascadeType.ALL)
public Errand errand;
public Car() { }
public Car(String mark, String plate, int mileage) {
this.mark = mark;
this.plate = plate;
this.mileage = mileage;
}
public void setErrand(Errand errand) {
this.errand = errand;
}
public String getMark() {
return mark;
}
public void setMark(String mark) {
this.mark = mark;
}
public String getPlate() {
return plate;
}
public void setPlate(String plate) {
this.plate = plate;
}
public int getMileage() {
return mileage;
}
public void setMileage(int mileage) {
this.mileage = mileage;
}
public Errand getErrand() {
return errand;
}enter code here
And errand class
package com.RentCar.Rent_A_car.domain;
import net.bytebuddy.dynamic.loading.InjectionClassLoader;
import javax.persistence.*;
import javax.persistence.Entity;
#Entity
public class Errand {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public int Id;
public String description;
public Errand() {
}
public Errand(String description) {
this.description = description;
}
#Override
public String toString() {
return description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
I'm not quite sure about what is the actual problem. But anyway, I can make you some recommendations:
use plural nouns for REST uris, like:
#GetMapping("cars")
#GetMapping("errands")
and so on. Not verbs, like: assignErrand
If you split Repositories and Services, do not put login in repos, like
#Transactional
public void createErrand(String description) {
Errand newErrand = new Errand(description);
ee.persist(newErrand);
System.out.println(newErrand);
}
In the repos you should do just the persistence job. Leave the logic to the service
To add errands, I would go with something like this:
#PostMapping("/cars/{carId}/errands")
public Car addErranr(#PathVariable int carId, #RequestBody Errand errand){
Car car = this.carService.findById(carId);
car.getErrands().add(errand);
return this.carService.save(car);
}

Spring Boot MongoDB - MongoDB cannot generate 'ID'

I have some problem with my Spring Boot application.
When I save one document in my repository application works fine, but when I save more than one documents, my aplication not working. Here is my code.
Article.java
import org.springframework.data.annotation.Id;
public class Article {
#Id
private String id;
private String title;
private String description;
public Article() {}
public Article(String title, String description) {
this.title = title;
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "Article{" +
"id='" + id + '\'' +
", title='" + title + '\'' +
", description='" + description + '\'' +
'}';
}
}
ArticleRepository.java
public interface ArticleRepository extends MongoRepository<Article, String> {}
DatabaseLoader.java
import java.util.HashSet;
import java.util.Set;
#Component
public class DatabaseLoader implements CommandLineRunner {
#Autowired
private ArticleRepository articleRepository;
#Override
public void run(String... args) throws Exception {
articleRepository.deleteAll();
// example 1: if I save one document to my repo everything works fine
// example: articleRepository.save(new Article("Title 1", "description 1"));
// console returns: Article{id='596f480e4e118123574a13f1', title='Title 1', description='description 1'}
// but here is problem
Set<Article> articleList = new HashSet<Article>(){
{
add(new Article("Title 1", "description 1"));
add(new Article("Title 2", "description 2"));
}
};
// because if I try to save my collection
articleRepository.save(articleList);
// console returns: com.mongodb.DuplicateKeyException:
// Write failed with error code 11000 and error message
// 'insertDocument :: caused by :: 11000 E11000 duplicate key
// error index: test.article.$user dup key: { : null }'
System.out.println(articleRepository.findAll());
}
}
Application.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(SimpleMongoApplication.class, args);
}
}
Do you know, why I have this problem?
Thank you for all your answers.
OK, here is #Afridi's solution.
All you need to do is adding #Document(collection="collection-name") annotation in your document. here is an example:
#Document(collection = "articles") // here is solution
public class Article {
#Id
private String id;
private String title;
private String description;
//getters, setters and constructor
}

Couchbase query exception on runtime Unsupported parameter type for key: class com.couchbase.client.protocol.views.Query

I am getting this exception every time i try to query a view on Couchbase DB from my spring boot application.
Unsupported parameter type for key: class com.couchbase.client.protocol.views.Query.
I was setting a string on setKey() method of Query class, got an exception. But then I checked the API and provided a json to setKey, still not working. Have searched a lot but could not get this to work.
I am sharing the code snippet in this post as well.
Application.properties
spring.couchbase.bucket.password=
spring.couchbase.bucket.name=default
spring.couchbase.bootstrap-hosts=127.0.0.1
spring.data.couchbase.repositories.enabled=true
PlayerRepository
public interface PlayerRepository extends CouchbaseRepository<Player, Integer>
{
#View(designDocument = "player", viewName = "all")
public List<Player> findAll();
#View(designDocument = "player", viewName = "by_Name")
public Player findByName(Query query);
#View(designDocument = "player", viewName = "by_TeamId")
public List<Player> findByTeamId(Query query);
}
Player.java
#Document
public class Player
{
#Id
int playerId;
#Field
String name;
#Field
String type;
#Field
String country;
#Field
String playingHand;
#Field
String era;
#Field
int teamId;
#Field
int odiCenturies;
#Field
int testCenturies;
public Player(){}
public Player(int playerId, String name, String type, String country, String playingHand, String era, int teamId,
int odiCenturies, int testCenturies) {
super();
this.playerId = playerId;
this.name = name;
this.type = type;
this.country = country;
this.playingHand = playingHand;
this.era = era;
this.teamId = teamId;
this.odiCenturies = odiCenturies;
this.testCenturies = testCenturies;
}
SpringBootApplication class
#SpringBootApplication
public class CricketTeamSelectionMain
{
/**
* #param args
*/
public static void main(String[] args)
{
SpringApplication.run(CricketTeamSelectionMain.class, args);
}
#Configuration
#EnableCouchbaseRepositories
public static class DBConfig extends AbstractCouchbaseConfiguration
{
#Value("${spring.couchbase.bucket.name}")
private String bucketName;
#Value("${spring.couchbase.bucket.password}")
private String password;
#Value("${spring.couchbase.bootstrap-hosts}")
private String ip;
#Override
public String getBucketName() {
return this.bucketName;
}
#Override
public String getBucketPassword() {
return this.password;
}
#Override
public List<String> getBootstrapHosts() {
return Arrays.asList(this.ip);
}
}
}
PlayerService class
package org.ups.fantasyCricket.service;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.ups.fantasyCricket.CricketTeamSelectionMain.DBConfig;
import org.ups.fantasyCricket.Model.Player;
import org.ups.fantasyCricket.Repository.PlayerRepository;
import com.couchbase.client.CouchbaseClient;
import com.couchbase.client.protocol.views.Query;
import com.couchbase.client.protocol.views.View;
import com.couchbase.client.protocol.views.ViewResponse;
#Service
public class PlayerService
{
#Autowired
PlayerRepository playerRepo;
private CouchbaseClient client;
public List<Player> getAllPlayers()
{
List<Player> allPlayerLists = new ArrayList<Player>();
/*allPlayerLists.addAll((Collection<? extends Player>) playerRepo.findAll());
return allPlayerLists;*/
playerRepo.findAll().forEach(allPlayerLists::add);
return allPlayerLists;
}
public Player getPlayerByName(String name)
{
DBConfig dbCon = new DBConfig();
try
{
Query query = new Query();
query.setIncludeDocs(true);
query.setKey(name);
Player player = playerRepo.findByName(query);
return player;
}
catch(Exception e)
{
e.printStackTrace();
System.out.println(e.getMessage());
}
return null;
}
public String addPlayer(Player player)
{
playerRepo.save(player);
return "Success";
}
public String updatePlayer(Player player, int id)
{
playerRepo.save(player);
return "Success";
}
public List<Player> getPlayersByTeamId(int teamId)
{
List<Player> allPlayerLists = new ArrayList<Player>();
Query query = new Query();
query.setKey(String.valueOf(teamId));
playerRepo.findByTeamId(query).forEach(allPlayerLists::add);
return allPlayerLists;
}
public String addPlayers(List<Player> players)
{
playerRepo.save(players);
return "Success";
}
}
View by_Name on CouchBase DB
function (doc) {
emit(doc.name, doc);
}
Which version of spring-data-couchbase are you using? Starting with 2.x, the #Query annotation uses query derivation and you cannot use a ViewQuery as a parameter anymore... Have a look at the docs, on query derivation with a view.
You could probably use the CouchbaseTemplate to perform a manual query though.

Resources