Spring Boot - Apache Derby duplicating IDs of a ListArray objects - spring

This little project follows a basic MVC pattern, i'm using spring boot and apache derby as an embedded data base.
1) When adding a hardcoded object list inside service class, they all share the same id. Is there an explanation for this behavior ?
This shows the problem (Don't mind the 'kkk' objects, i've solved that part already)
Screen1
So this is the object account i'm working with :
#Entity
public class Account {
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
private String owner;
private double budget;
private double budgetInvest;
private double budgetFonction;
public Account() {
}
public Account(String owner, double budget, double budgetInvest, double budgetFonction
) {
this.owner=owner;
this.budget = budget;
this.budgetInvest = budgetInvest;
this.budgetFonction = budgetFonction;
}
public Account (String owner, double budget) {
this.owner = owner;
this.budget=budget;
}
public Account (String owner) {
this.owner=owner;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public double getBudget() {
return budget;
}
public void setBudget(double budget) {
this.budget = budget;
}
public double getBudgetInvest() {
return budgetInvest;
}
public void setBudgetInvest(double budgetInvest) {
this.budgetInvest = budgetInvest;
}
public double getBudgetFonction() {
return budgetFonction;
}
public void setBudgetFonction(double budgetFonction) {
this.budgetFonction = budgetFonction;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
}
These are the lines responsible for displaying the objects inside the view :
<tr th:each="account : ${accounts}">
<td th:text="${account.id}">id</td>
<td><a href="#" th:text="${account.owner}">Title
...</a></td>
<td th:text="${account.budget}">Text ...</td>
</tr>
Here is the controller :
#Controller
public class AccountController {
#Autowired
private AccountService accountService;
#RequestMapping(value="/", method=RequestMethod.GET)
public String index() {
return "index";
}
#RequestMapping(value="/accountAdd", method=RequestMethod.GET)
public String addAccount(Model model) {
model.addAttribute("account", new Account());
return "accountAdd";
}
#RequestMapping(value="/accountAdd", method=RequestMethod.POST)
public String postAccount(#ModelAttribute Account account) {
accountService.addAccount(account);
return "redirect:listAccount";
}
#RequestMapping(value="/listAccount", method=RequestMethod.GET)
public String listAccount(Model model) {
System.out.println(accountService.getAllAccounts());
model.addAttribute("accounts",accountService.getAllAccounts());
return "listAccount";
}
}
And finally the service class :
#Service
public class AccountService {
#Autowired
private AccountRepository accountRepository;
public List<Account> getAllAccounts(){
List<Account>accounts = new ArrayList<>(Arrays.asList(
new Account("Maths Department",1000000,400000,600000),
new Account("Physics Department",7000000,200000,500000),
new Account("Science Department",3000000,700000,1000000)
));
accountRepository.findAll().forEach(accounts::add);
return accounts;
}
public Account getAccount(long id) {
return accountRepository.findById(id).orElse(null);
}
public void addAccount(Account account) {
accountRepository.save(account);
}
public void updateAccount(long id, Account account) {
accountRepository.save(account);
}
public void deleteAccount(long id) {
accountRepository.deleteById(id);
}
}

Ok, so while i haven't yet found the exact answer as to why it affects the same id for every object in a static list.
I found an elegant workaround to not only solve the issue but also enhance the structure of the code.
Instead of doing whatever barbaric initialization I was trying to perform, It's way better to do this inside the main class :
#SpringBootApplication
public class PayfeeApplication {
#Autowired
private AccountRepository accountRepository;
public static void main(String[] args) {
SpringApplication.run(PayfeeApplication.class, args);
}
#Bean
InitializingBean sendDatabase() {
return () -> {
accountRepository.save(new Account("Maths Department",1000000,400000,600000));
accountRepository.save(new Account("Physics Department",7000000,200000,500000));
accountRepository.save(new Account("Science Department",3000000,700000,1000000));
};
}
}

Related

Spring Boot Rest

i am practicing with spring boot for work with restful applications
I have set a #RestController and #Entity like this
#RestController
#RequestMapping(value = "/api")
public class RestControllerCar {
#Autowired
private CarRepository carRepository;
#RequestMapping(value = "/cars")
public Iterable<Car> getCars() {
return carRepository.findAll();
}
}
and
#Entity
public class Car {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String brand, model, color, registerNumber;
private Integer year, price;
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
#ManyToMany(mappedBy = "cars")
private Set<Owner> owners;
public Car() {
}
public Car(String brand, String model, String color, String registerNumber, Integer year, Integer price) {
super();
this.brand = brand;
this.model = model;
this.color = color;
this.registerNumber = registerNumber;
this.year = year;
this.price = price;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getRegisterNumber() {
return registerNumber;
}
public void setRegisterNumber(String registerNumber) {
this.registerNumber = registerNumber;
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public Set<Owner> getOwner() {
return owners;
}
public void setOwner(Set<Owner> owners) {
this.owners = owners;
}
when i use postman to http://localhost:8080/cardatabase/api/cars i get a list of Cars
but even if i go to http://localhost:8081/cardatabase/cars, with _embedded on the top
it`s normal?
Thanks!!!!
Is your repository annotated #RestRepository? The _embedded make me think to the kind of output given by a #RestRepository for an array.
#RestRepository auto create all endpoint. As #M.Deinum pointed out, with the data rest starter, if ou remove it , you only have your controller, and not the one generated by #RestRepository.
Two main choices here:
You dont annotate the Repository. Just an interface which implement JpaRepository<YourEntity, TypeOfYourID> and use your controllers
You use only the auto created controllers by #RestRepository.
Or, you can install swagger2 on your project, so, accessing the docs on your browser, you will see all available endpoints, and it may be more clear for you.
With swagger you will also see what is the return type of the endpoint, the parameters etc..
Swagger is really easy to install in a project and to use. (dependencies, one annotation and it's good.. for basic usage).

Id to Entity conversion is not working in Spring Boot 2.2.8 and higher

I tried to upgrade the Spring Boot version for my application and found a difference in behavior. When switching from 2.2.7 to 2.2.8 (and higher), the conversion from identifier to database entity stops working.
Application:
#SpringBootApplication
public class DomainClassConverterTestApplication {
public static void main(String[] args) {
SpringApplication.run(DomainClassConverterTestApplication.class, args);
}
#Bean
CommandLineRunner initialize(ModelRepository modelRepository) {
return args -> {
Stream.of("Model 1", "Model 2", "Model X").forEach(name -> {
Model model = new Model();
model.setName(name);
modelRepository.save(model);
});
};
}
}
Controller:
#RestController
public class ModelController {
private final ModelRepository repository;
public ModelController(ModelRepository repository) {
this.repository = repository;
}
#GetMapping("/models/{id}")
public Model getModel(#PathVariable("id") Model model) {
return model;
}
#GetMapping("/models")
public Page<Model> findAllModels(Pageable pageable) {
return repository.findAll(pageable);
}
}
Model:
#Entity
public class Model {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
public Model() {}
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; }
#Override
public String toString() { return "Model{id=" + id + ", name='" + name + "'}"; }
}
After investigation of this problem, I discovered that the root cause of this is in the DomainClassConverter class. I understand that the problem lies in the setApplicationContext method. The method uses lazy initialization, and it adds converters to СonversionService, but only after the first use. But this event never occurs because the converter is not registered in СonversionService. Here is the method:
public void setApplicationContext(ApplicationContext context) {
this.repositories = Lazy.of(() -> {
Repositories repositories = new Repositories(context);
this.toEntityConverter = Optional.of(new ToEntityConverter(repositories, conversionService));
this.toEntityConverter.ifPresent(it -> conversionService.addConverter(it));
this.toIdConverter = Optional.of(new ToIdConverter(repositories, conversionService));
this.toIdConverter.ifPresent(it -> conversionService.addConverter(it));
return repositories;
});
}
It is a bug DATACMNS-1743 and was fixed in 2.2.8, 2.3.2, and higher.

Spring boot H2 database application

I have created a sample project with following code. Even if i am not providing table create statement in the data.sql, it is creating the table. how to stop that. Sample code is present below
Can you please let me know what I am doing wrong? I have removed the import statements below as the post was not allowing to put so much code here.
package com.example.demo;
// Model class
#Entity
#Table(name="reservation")
public class Reservation {
#Id
private Long id;
#Column(name="user_id")
private Long userId;
#Column(name="party_size")
private int partySize;
#Column(name="restaurant_id")
private Long restaurantId;
#Column(name="date")
private LocalDateTime dt;
public Reservation() {}
public Reservation(Long id, Long userId, int partySize) {
this.id = id;
this.userId = userId;
this.partySize = partySize;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public int getPartySize() {
return partySize;
}
public void setPartySize(int partySize) {
this.partySize = partySize;
}
public Long getRestaurantId() {
return restaurantId;
}
public void setRestaurantId(Long restaurantId) {
this.restaurantId = restaurantId;
}
public LocalDateTime getDt() {
return dt;
}
public void setDt(LocalDateTime dt) {
this.dt = dt;
}
}
package com.example.demo;
#SpringBootApplication
public class ReservationApp {
public static void main(String[] args) {
SpringApplication.run(ReservationApp.class, args);
}
}
package com.example.demo;
#RestController
#RequestMapping("/v1")
public class ReservationController {
#Autowired
private ReservationService reservationService;
// ------------ Retrieve all reservations ------------
#RequestMapping(value = "/reservations", method = RequestMethod.GET)
public List getAllReservations() {
return reservationService.getAllReservations();
}
package com.example.demo;
import org.springframework.data.repository.CrudRepository;
public interface ReservationRepository extends CrudRepository<Reservation,String> {
}
package com.example.demo;
#Service
public class ReservationService {
#Autowired
private ReservationRepository reservationRepository;
// Retrieve all rows from table and populate list with objects
public List getAllReservations() {
List reservations = new ArrayList<>();
reservationRepository.findAll().forEach(reservations::add);
return reservations;
}
}
try to remove the spring boot hibernate configuration
spring.jpa.hibernate.ddl-auto = update
Which is able of creating/updating the database schema from entities
To disable automatic DDL generation, set the following property to false in application.properties:
spring.jpa.generate-ddl = false
For more information and fine-grained control, please see the documentation.
Set the ddl generation to none in the application.properties:
spring.jpa.hibernate.ddl-auto=none

Spring framework - Data not display in view page

no errors display in my view...but when it run it gives the value as '0'. my database table name is 'categories'.it has a value like 'category_l dummy' for the column .But in the view display as a 0...please help me to slove this...
This is my model class
#Entity
#Table(name = "categories")
public class CategoriesModel implements Serializable{
#Id
#Column
#GeneratedValue(strategy = GenerationType.AUTO) //for autonumber
private int id;
#Column
private String category1;
#Column
private String desccategory1;
public CategoriesModel() {
}
public CategoriesModel(
int id,
String category1, String desccategory1) {
super();
this.id = id;
this.category1 = category1;
this.desccategory1 = desccategory1;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCategory1() {
return category1;
}
public void setCategory1(String category1) {
this.category1 = category1;
}
public String getDesccategory1() {
return desccategory1;
}
public void setDesccategory1(String desccategory1) {
this.desccategory1 = desccategory1;
}
This is my Dao class
public interface CategoriesDao {
public void add(CategoriesModel categories);
public void edit(CategoriesModel categories);
public void delete(int id);
public CategoriesModel getCategoriesModel(int id);
public List getAllCategoriesModel();
}
This is my Dao impl class
#Repository
public class CategoriesDaoImpl implements CategoriesDao {
#Autowired
private SessionFactory session;
#Override
public void add(CategoriesModel categories) {
session.getCurrentSession().save(categories);
//this "categories" is a table name
}
#Override
public void edit(CategoriesModel categories) {
session.getCurrentSession().update(categories);
//this "categories" is a table name
}
#Override
public void delete(int id) {
session.getCurrentSession().delete(getCategoriesModel(id));
//this "id" is a feild in Model
}
#Override
public CategoriesModel getCategoriesModel(int id) {
return (CategoriesModel) session.getCurrentSession().get(CategoriesModel.class, id);
}
#Override
public List getAllCategoriesModel() {
return session.getCurrentSession().createQuery("from CategoriesModel").list();
//this "CategoriesModel" is a its model name
}
This is my service class
public void add(CategoriesModel categories);
public void edit(CategoriesModel categories);
public void delete(int id);
public CategoriesModel getCategoriesModel(int id);
public List getAllCategoriesModel();
This is my service impl class
#Service
public class CategoriesServiceImpl implements CategoriesService {
#Autowired
private CategoriesDao CategoriesDao;
#Transactional
public void add(CategoriesModel categories) {
CategoriesDao.add(categories);
}
#Transactional
public void edit(CategoriesModel categories) {
CategoriesDao.edit(categories);
}
#Transactional
public void delete(int id) {
CategoriesDao.delete(id);
}
#Transactional
public CategoriesModel getCategoriesModel(int id) {
return CategoriesDao.getCategoriesModel(id);
}
#Transactional
public List getAllCategoriesModel() {
return CategoriesDao.getAllCategoriesModel();
}
this is my controller class
#Autowired
private CategoriesService CategoriesService;
#RequestMapping("/")
public String setupForm(Map<String, Object> map) {
CategoriesModel categories = new CategoriesModel();
//Create a new object from details Model
map.put("category", categories);
//new created object is assign and view name
map.put("categoriesList", CategoriesService.getAllCategoriesModel());
//view feild assign list in view page
System.out.println(categories);
return "allcategories";
//return page(view name)
}
this is my view
<c:forEach items="${categoriesList}" var="category">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div id="category">
<div class="col-lg-2 col-md-2 col-sm-4 col-xs-6 ">
<a href="" target="_self"><img src="images/properties/cars.png" class="img-responsive">
<div class="link">
<p>${category.category1}</p>
</div>
</div>
#Autowired
private CategoriesService CategoriesService;
#RequestMapping("/")
public String setupForm(Model model) {
CategoriesModel categories = new CategoriesModel();
//Create a new object from details Model
model.addAttribute("category", categories);
//new created object is assign and view name
model.addAttribute("categoriesList", CategoriesService.getAllCategoriesModel());
//view feild assign list in view page
System.out.println(categories);
return "allcategories";
//return page(view name)
}

Axon Event Handler not Working

I am developing a small cqrs implementation and I am very new to it.
I want to segregate each handlers(Command and Event) from aggregate and
make sure all are working well. The command handler are getting triggered
from controller but from there event handlers are not triggered. Could
anyone Please help on this.
public class User extends AbstractAnnotatedAggregateRoot<String> {
/**
*
*/
private static final long serialVersionUID = 1L;
#AggregateIdentifier
private String userId;
private String userName;
private String age;
public User() {
}
public User(String userid) {
this.userId=userid;
}
#Override
public String getIdentifier() {
return this.userId;
}
public void createuserEvent(UserCommand command){
apply(new UserEvent(command.getUserId()));
}
#EventSourcingHandler
public void applyAccountCreation(UserEvent event) {
this.userId = event.getUserId();
}
}
public class UserCommand {
private final String userId;
public UserCommand(String userid) {
this.userId = userid;
}
public String getUserId() {
return userId;
}
}
#Component
public class UserCommandHandler {
#CommandHandler
public void userCreateCommand(UserCommand command) {
User user = new User(command.getUserId());
user.createuserEvent(command);
}
}
public class UserEvent {
private final String userId;
public UserEvent(String userid) {
this.userId = userid;
}
public String getUserId() {
return userId;
}
}
#Component
public class UserEventHandler {
#EventHandler
public void createUser(UserEvent userEvent) {
System.out.println("Event triggered");
}
}
#Configuration
#AnnotationDriven
public class AppConfiguration {
#Bean
public SimpleCommandBus commandBus() {
SimpleCommandBus simpleCommandBus = new SimpleCommandBus();
return simpleCommandBus;
}
#Bean
public Cluster normalCluster() {
SimpleCluster simpleCluster = new SimpleCluster("simpleCluster");
return simpleCluster;
}
#Bean
public ClusterSelector clusterSelector() {
Map<String, Cluster> clusterMap = new HashMap<>();
clusterMap.put("com.user.event.handler", normalCluster());
//clusterMap.put("exploringaxon.replay", replayCluster());
return new ClassNamePrefixClusterSelector(clusterMap);
}
#Bean
public EventBus clusteringEventBus() {
ClusteringEventBus clusteringEventBus = new ClusteringEventBus(clusterSelector(), terminal());
return clusteringEventBus;
}
#Bean
public EventBusTerminal terminal() {
return new EventBusTerminal() {
#Override
public void publish(EventMessage... events) {
normalCluster().publish(events);
}
#Override
public void onClusterCreated(Cluster cluster) {
}
};
}
#Bean
public DefaultCommandGateway commandGateway() {
return new DefaultCommandGateway(commandBus());
}
#Bean
public Repository<User> eventSourcingRepository() {
EventStore eventStore = new FileSystemEventStore(new SimpleEventFileResolver(new File("D://sevents.txt")));
EventSourcingRepository eventSourcingRepository = new EventSourcingRepository(User.class, eventStore);
eventSourcingRepository.setEventBus(clusteringEventBus());
AnnotationEventListenerAdapter.subscribe(new UserEventHandler(), clusteringEventBus());
return eventSourcingRepository;
}
}
As far as I can tell, the only thing missing is that you aren't adding the User Aggregate to a Repository. By adding it to the Repository, the User is persisted (either by storing the generated events, in the case of Event Sourcing, or its state otherwise) and all Events generated by the Command Handler (including the Aggregate) are published to the Event Bus.
Note that the Aggregate's #EventSourcingHandlers are invoked immediately, but any external #EventHandlers are only invoked after the command handler has been executed.

Resources