I'm busing developing an application (Hibernate Spring Vaadin Postgres Liferay).
I did all of the configurations for the project (Hibernate, Spring, Postgres) and
I generated a database, but when I do a dynamic formulaire I have a problem integrating the controller with the form.
This is the article.java:
package com.bd.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="Articlet")
public class Article {
int id;
String nom;
String type;
int qte;
public Article() {
super();
// TODO Auto-generated constructor stub
}
#Id
#GeneratedValue
#Column(name="ID")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name="Nom")
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
#Column(name="Type")
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
#Column(name="Qunatite")
public int getQte() {
return qte;
}
public void setQte(int qte) {
this.qte = qte;
}
}
This is articledaoimpl.java:
package com.bd.dao;
import java.util.Collection;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.bd.entity.Article;
#Repository
#Configuration
#Transactional
public class ArticleDaoImp implements ArticleDao {
#Autowired
SessionFactory sessionFactory;
#SuppressWarnings("unchecked")
#Transactional(readOnly = true)
public List<Article> getAll() {
return sessionFactory.getCurrentSession().createQuery("from Article")
.list();
}
#Transactional(readOnly = true)
public Article getById(int articleId) {
return (Article) sessionFactory.getCurrentSession().get(Article.class,
articleId);
}
#Override
public void save(Article article) {
sessionFactory.getCurrentSession().merge(article);
}
#Override
public void delete(Article article) {
sessionFactory.getCurrentSession().delete(article);
}
}
This is articleserviceimpl.java:
package com.bd.service;
import java.util.Collection;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import com.bd.dao.ArticleDao;
import com.bd.entity.Article;
#Service
#Configuration
#ComponentScan("com.bd.dao")
public class ArticleServiceImp implements ArticleService {
#Autowired
private ArticleDao articledao;
#Override
public Article getArticleById(int articleId) {
// TODO Auto-generated method stub
return articledao.getById(articleId);
}
#Override
public void saveArticle(Article article) {
// TODO Auto-generated method stub
articledao.save(article);
}
#Override
public void deleteArticle(Article article) {
// TODO Auto-generated method stub
articledao.delete(article);
}
#Override
public List<Article> getAllArticles() {
// TODO Auto-generated method stub
return articledao.getAll();
}
}
This is the article controleur:
package com.bd.controleur;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import com.bd.entity.Article;
import com.bd.service.ArticleService;
#Controller
#Configuration
#ComponentScan("com.bd.service")
public class ArticleControleur {
#Autowired
ArticleService articleService;
public void addarticle(Article article){
articleService.saveArticle(article);
}
}
This the form:
package achrefliferay;
import org.springframework.beans.factory.annotation.Autowired;
import com.bd.entity.Article;
import com.bd.service.ArticleService;
import com.vaadin.Application;
import com.vaadin.ui.Button;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import com.vaadin.ui.Button.ClickEvent;
public class AchrefliferayApplication extends Application {
#Autowired
ArticleService articleService;
public void init() {
Article article;
Window w = new Window("Subscribe Newsletter");
setMainWindow(w);
w.setContent(new VerticalLayout());
TextField name = new TextField("Name");
TextField type = new TextField("Type");
TextField qte = new TextField("Quantité");
Button subscribeBtn = new Button("saisi");
w.addComponent(name);
w.addComponent(type);
w.addComponent(qte);
w.addComponent(subscribeBtn);
subscribeBtn.addListener(new Button.ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
articleService.saveArticle();
}
});
}
}
You'll have to create a BeanItem and set it as the data source for your form. I don't know Spring that well, but once you know how to bind a bean to the form, you should be able to integrate the controller with the form by using the appropriate listeners.
Example:
// Create a form and use FormLayout as its layout.
final Form form = new Form();
// Set form caption text
form.setCaption("Subscribe Newsletter");
// Create a bean item that is bound to the bean.
final BeanItem item = new BeanItem(new Article());
// Bind the bean item as the data source for the form.
form.setItemDataSource(item);
// Add the subscribe button
HorizontalLayout formFooter = new HorizontalLayout();
Button subscribeButton = new Button("saisi");
subscribeButton.addListener(new Button.ClickListener() {
void buttonClick(Button.ClickEvent event) {
form.commit();
controller.addArticle(item.getBean());
}
});
formFooter.addComponent(subscribeButton);
form.setFooter(formFooter);
This means you don't have to explicitly create every form field like you did in your AchrefliferayApplication's init() method.
See Binding Form to Data in Book of Vaadin.
ps. If anyone actual Vaadin expert reads this: feel free to correct my answer to follow the best practices :)
Related
I'm trying to build an API with Spring Boot, but I keep getting an error when dealing with #OneToMany entities. The Bean seem to not be able to get an entity I'm referencing by ID through the JSON from the database and constructing it to insert into the other entity. Sounds complicated, so here's the code for everything and the error. I googled and googled and couldn't find a fitting answer to my specific situation.
Entity Turma:
package com.residencia.academia.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "turma")
public class Turma {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id_turma")
private Integer idTurma;
#Column(name = "horario")
private Date horarioTurma;
#Column(name = "duracao")
private Integer duracaoTurma;
#Column(name = "data_inicio")
private Date dataInicioTurma;
#Column(name = "data_fim")
private Date dataFimTurma;
#ManyToOne
#JoinColumn(name = "id_instrutor", referencedColumnName = "id_instrutor")
private Instrutor instrutor;
public Integer getIdTurma() {
return idTurma;
}
public void setIdTurma(Integer idTurma) {
this.idTurma = idTurma;
}
public Date getHorarioTurma() {
return horarioTurma;
}
public void setHorarioTurma(Date horarioTurma) {
this.horarioTurma = horarioTurma;
}
public Integer getDuracaoTurma() {
return duracaoTurma;
}
public void setDuracaoTurma(Integer duracaoTurma) {
this.duracaoTurma = duracaoTurma;
}
public Date getDataInicioTurma() {
return dataInicioTurma;
}
public void setDataInicioTurma(Date dataInicioTurma) {
this.dataInicioTurma = dataInicioTurma;
}
public Date getDataFimTurma() {
return dataFimTurma;
}
public void setDataFimTurma(Date dataFimTurma) {
this.dataFimTurma = dataFimTurma;
}
public Instrutor getInstrutor() {
return instrutor;
}
public void setInstrutor(Instrutor instrutor) {
this.instrutor = instrutor;
}
}
Turma's Controller:
package com.residencia.academia.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.residencia.academia.entity.Turma;
import com.residencia.academia.service.TurmaService;
#RestController
#RequestMapping("/turma")
public class TurmaController {
#Autowired
private TurmaService turmaService;
#GetMapping
public ResponseEntity<List<Turma>> findAll() {
return ResponseEntity.ok().body(turmaService.findAllTurma());
}
#GetMapping("/{id}")
public ResponseEntity<Turma> findById(#PathVariable Integer id) {
return ResponseEntity.ok().body(turmaService.findByIdTurma(id));
}
#PostMapping
public Turma save(#RequestBody Turma turma) {
return turmaService.saveTurma(turma);
}
#PutMapping
public Turma update(#RequestBody Turma turma) {
return turmaService.updateTurma(turma);
}
#DeleteMapping("/{id}")
public void delete(#PathVariable Integer id) {
turmaService.deleteTurma(id);
}
}
Turma's Service:
package com.residencia.academia.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.residencia.academia.entity.Turma;
import com.residencia.academia.repository.TurmaRepository;
#Service
public class TurmaService {
#Autowired
private TurmaRepository turmaRepository;
public List<Turma> findAllTurma() {
return turmaRepository.findAll();
}
public Turma findByIdTurma(Integer id) {
return turmaRepository.findById(id).get();
}
public Turma saveTurma(Turma turma) {
return turmaRepository.save(turma);
}
public Turma updateTurma(Turma turma) {
return turmaRepository.save(turma);
}
public void deleteTurma(Integer id) {
turmaRepository.deleteById(id);
}
public void deleteTurma(Turma turma) {
turmaRepository.delete(turma);
}
}
Turma's Repository:
package com.residencia.academia.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.residencia.academia.entity.Turma;
public interface TurmaRepository extends JpaRepository<Turma, Integer> {
}
Entity Instrutor:
package com.residencia.academia.entity;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "instrutor")
public class Instrutor {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id_instrutor")
private Integer idInstrutor;
#Column(name = "rg")
private Integer rgInstrutor;
#Column(name = "nome")
private String nomeInstrutor;
#Column(name = "nascimento")
private Date dataNascimentoInstrutor;
#Column(name = "titulacao")
private Integer titulacaoInstrutor;
#OneToMany(mappedBy = "instrutor")
private List<Turma> turmaList;
public Integer getIdInstrutor() {
return idInstrutor;
}
public void setIdInstrutor(Integer idInstrutor) {
this.idInstrutor = idInstrutor;
}
public Integer getRgInstrutor() {
return rgInstrutor;
}
public void setRgInstrutor(Integer rgInstrutor) {
this.rgInstrutor = rgInstrutor;
}
public String getNomeInstrutor() {
return nomeInstrutor;
}
public void setNomeInstrutor(String nomeInstrutor) {
this.nomeInstrutor = nomeInstrutor;
}
public Date getDataNascimentoInstrutor() {
return dataNascimentoInstrutor;
}
public void setDataNascimentoInstrutor(Date dataNascimentoInstrutor) {
this.dataNascimentoInstrutor = dataNascimentoInstrutor;
}
public Integer getTitulacaoInstrutor() {
return titulacaoInstrutor;
}
public void setTitulacaoInstrutor(Integer titulacaoInstrutor) {
this.titulacaoInstrutor = titulacaoInstrutor;
}
public List<Turma> getTurmaList() {
return turmaList;
}
public void setTurmaList(List<Turma> turmaList) {
this.turmaList = turmaList;
}
}
Instrutor's Controller:
package com.residencia.academia.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.residencia.academia.entity.Instrutor;
import com.residencia.academia.service.InstrutorService;
#RestController
#RequestMapping("/instrutor")
public class InstrutorController {
#Autowired
private InstrutorService instrutorService;
#GetMapping
public ResponseEntity<List<Instrutor>> findAll() {
return ResponseEntity.ok().body(instrutorService.findAllInstrutor());
}
#GetMapping("/{id}")
public ResponseEntity<Instrutor> findById(#PathVariable Integer id) {
return ResponseEntity.ok().body(instrutorService.findByIdInstrutor(id));
}
#PostMapping
public Instrutor save(#RequestBody Instrutor instrutor) {
return instrutorService.saveInstrutor(instrutor);
}
#PutMapping
public Instrutor update(#RequestBody Instrutor instrutor) {
return instrutorService.updateInstrutor(instrutor);
}
#DeleteMapping("/{id}")
public void delete(#PathVariable Integer id) {
instrutorService.deleteInstrutor(id);
}
}
Instrutor's Service:
package com.residencia.academia.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.residencia.academia.entity.Instrutor;
import com.residencia.academia.repository.InstrutorRepository;
#Service
public class InstrutorService {
#Autowired
private InstrutorRepository instrutorRepository;
public List<Instrutor> findAllInstrutor() {
return instrutorRepository.findAll();
}
public Instrutor findByIdInstrutor(Integer id) {
return instrutorRepository.findById(id).get();
}
public Instrutor saveInstrutor(Instrutor instrutor) {
return instrutorRepository.save(instrutor);
}
public Instrutor updateInstrutor(Instrutor instrutor) {
return instrutorRepository.save(instrutor);
}
public void deleteInstrutor(Integer id) {
instrutorRepository.deleteById(id);
}
public void deleteInstrutor(Instrutor instrutor) {
instrutorRepository.delete(instrutor);
}
}
Instrutor's Repository:
package com.residencia.academia.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.residencia.academia.entity.Instrutor;
public interface InstrutorRepository extends JpaRepository<Instrutor, Integer> {
}
JSON Structure:
{
"horarioTurma": "2022-06-29T18:00:00",
"duracaoTurma": 60,
"dataInicioTurma": "2022-06-29",
"dataFimTurma": "2022-07-29",
"instrutor": 1
}
HTTP Response:
400 Bad Request
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `com.residencia.academia.entity.Instrutor` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (1)
Any help is appreciated!
I tried to add One To Many Annotation to my spring boot project, but when I run my project I get "Failed to execute CommandLineRunner " error.
I wanted users in the user's table to have more than one city. So, I tried to add OneToMany Annotation.
You can see the error at the attachment.
User Class
package io.javabrains.springsecurity.jpa.models;
import com.spring.weather.*;
import java.util.*;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="app_user")
public class User {
#Id
#GeneratedValue(strategy =GenerationType.AUTO)
private int id;
private String userName;
private String password;
private boolean active;
private String role;
private String city;
#OneToMany(targetEntity = UserCity.class,cascade = CascadeType.ALL)
#JoinTable(name="USER_CITY",joinColumns=#JoinColumn(name="m_user_id"),
inverseJoinColumns=#JoinColumn(name="cityId"))
private List<UserCity> usercity;
public User() {
super();
// TODO Auto-generated constructor stub
}
public List<UserCity> getUsercity() {
return usercity;
}
public void setUsercity(List<UserCity> usercity) {
this.usercity = usercity;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
User City Class
package io.javabrains.springsecurity.jpa.models;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name="user_city")
public class UserCity {
#Id
#GeneratedValue(strategy =GenerationType.AUTO)
private int cityId;
private String cityName;
public UserCity() {
super();
// TODO Auto-generated constructor stub
}
public UserCity(int cityId, String cityName, User mUser) {
super();
this.cityId = cityId;
this.cityName = cityName;
this.mUser = mUser;
}
#ManyToOne
private User mUser;
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public User getmUser() {
return mUser;
}
public void setmUser(User mUser) {
this.mUser = mUser;
}
}
User Repository
package io.javabrains.springsecurity.jpa;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import io.javabrains.springsecurity.jpa.models.User;
public interface UserRepository extends JpaRepository<User, Integer> {
Optional<User> findByUserName(String userName);
}
User City Repository
package io.javabrains.springsecurity.jpa;
import org.springframework.data.jpa.repository.JpaRepository;
import io.javabrains.springsecurity.jpa.models.User;
import io.javabrains.springsecurity.jpa.models.UserCity;
public interface CityRepository extends JpaRepository<UserCity,id>{
}
Spring Application Class
package io.javabrains.springsecurity.jpa;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import com.spring.weather.WeatherService;
import io.javabrains.springsecurity.jpa.models.User;
import io.javabrains.springsecurity.jpa.models.UserCity;
#SpringBootApplication
#EnableJpaRepositories(basePackageClasses = UserRepository.class)
public class SpringsecurityApplication implements CommandLineRunner{
#Bean
public WeatherService ws() {
return new WeatherService ();
}
#Autowired
UserRepository userRepository;
CityRepository cityRepository;
public static void main(String[] args) {
SpringApplication.run(SpringsecurityApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
System.out.println("Application Running.");
User adminUser= new User();
UserCity ucity=new UserCity();
UserCity ucity2=new UserCity();
ucity.setCityName("amsterdam");
adminUser.setUserName("Admin");
adminUser.setPassword(new BCryptPasswordEncoder().encode("pass"));
adminUser.setRole("ROLE_ADMIN");
adminUser.setActive(true);
adminUser.setCity("bologna");
ucity.setmUser(adminUser);
userRepository.save(adminUser);
cityRepository.save(ucity);
User newUser= new User();
newUser.setUserName("User");
newUser.setPassword(new BCryptPasswordEncoder().encode("pass"));
newUser.setRole("ROLE_USER");
newUser.setActive(true);
newUser.setCity("maribor");
ucity2.setmUser(newUser);
userRepository.save(newUser);
cityRepository.save(ucity2);
}
}
The problem you are encountering, more specifically the NullPointerException at line 54 of your main application, is caused by the fact that the cityRepository is not
instantiated.
Looking through your configuration, I see that you only register the UserRepository with the #EnableJpaRepositories annotation.
Try adding also the CityRepository to the #EnableJpaRepositories, and also specify this bean as a candidate for autowiring( also add #Autowired to this bean, as you did for UserRepository)
For a good practice, following the MVC structure, it would be nice is all your spring repositories, the beans responsible for all CRUD operations with the database to be under the same package
I am a new beginner in Spring boot...I encounter a problem When I run my controller,
Description:
Field todoService in com.springboot.todoController.TodoController
required a bean of type 'com.springboot.todo.TodoService' that could
not be found.
Action:
Consider defining a bean of type 'com.springboot.todo.TodoService' in
your configuration.
below is my code
Todo.java
package com.springboot.todoBean;
import java.util.Date;
public class Todo {
private int id;
private String user;
private String desc;
private Date targetDate;
private boolean isDone;
public Todo() {}
public Todo(int id, String user, String desc, Date targetDate, boolean isDone) {
super();
this.id = id;
this.user = user;
this.desc = desc;
this.targetDate = targetDate;
this.isDone = isDone;
}
public int getId() {
return id;
}
public String getUser() {
return user;
}
public String getDesc() {
return desc;
}
public Date getTargetDate() {
return targetDate;
}
public boolean isDone() {
return isDone;
}
}
TodoService.java
package com.springboot.todo;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Service;
import com.springboot.todoBean.Todo;
#Service
public class TodoService {
private static List<Todo> todos = new ArrayList<Todo>();
private static int todoCount = 3;
static {
todos.add(new Todo(1, "Jack", "Learn Spring MVC", new Date(), false));
todos.add(new Todo(2, "Jack", "Learn Struts", new Date(), false));
todos.add(new Todo(3, "Jill", "Learn hibernate", new Date(), false));
}
public List<Todo> retrieveTodos(String user){
List<Todo> filteredTodos = new ArrayList<Todo>();
for (Todo todo : todos) {
if(todo.getUser().equals(user))
filteredTodos.add(todo);
}
return filteredTodos;
}
public Todo addTodo(String name, String desc,
Date targetDate, boolean isDone) {
Todo todo = new Todo(++todoCount, name, desc, targetDate, isDone);
todos.add(todo);
return todo;
}
public Todo retrievedTodo(int id) {
for(Todo todo: todos) {
if(todo.getId() == id)
return todo;
}
return null;
}
}
TodoController.java
package com.springboot.todoController;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.springboot.todo.TodoService;
import com.springboot.todoBean.Todo;
#RestController
public class TodoController {
#Autowired
private TodoService todoService;
#GetMapping("/users/{name}/todos")
public List<Todo> retrieveTodo(#PathVariable String name){
return todoService.retrieveTodos(name);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(TodoController.class, args);
}
}
I have added the annotation #Service to the TodoService to tell spring boot it is a bean, but it still cannot recognise, could anyone tell me how to solve this problem? thanks
Create a separate class as below for start the spring boot application. Also, please note that below class should be placed in higher level in the package hierarchy than other controller, service, etc classes.
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Your error is generated because your application is not scanning TodoService.
The mentioned code has several problems:
please make all packages lower case - java convention
please move the main in another class and annotate it with #SpringBootApplication
ex.
#SpringBootApplication
public class Application{
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
3. by default the spring boot application will scan beans contained in the package where the class from 2 is defined. You can put the class from 2 in the common package for both service and controller.
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
}
}
I have web written in Spring. I use Hibernate for JPA. I need to find entity in database, I get ID from user.
Problem is if ID is not in database - I get a NullPointerException.
Now I have:
People p;
try {
p = peopleManager.findById(id);
if (p != null) {
model.addAttribute("message", "user exist, do any action");
} else {
model.addAttribute("message", "user NOT exist");
}
} catch (NullPointerException e) {
model.addAttribute("message", "user NOT exist");
}
but it looks terrible. How can I do it right?
There is complete example code:
package com.example.test.entity;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
public class People {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name="name")
private String name;
#Column(name="age")
private int age;
}
/* ---------------------------------------------------- */
package com.example.test.dao;
import java.util.List;
import com.example.test.entity.People;
public interface PeopleDao {
public void save(People people);
public void delete(People people);
public void update(People people);
public List<People> findAll();
public People findById(int id);
}
/* ---------------------------------------------------- */
package com.example.test.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.example.test.entity.People;
#Repository
public class PeopleDaoImpl implements PeopleDao {
#Autowired
private SessionFactory sessionFactory;
#Override
public void save(People people) {
this.sessionFactory.getCurrentSession().save(people);
}
#Override
public void delete(People people) {
this.sessionFactory.getCurrentSession().delete(people);
}
#Override
public void update(People people) {
this.sessionFactory.getCurrentSession().update(people);
}
#Override
public List<People> findAll() {
return this.sessionFactory.getCurrentSession().createQuery("from People ORDER BY age").list();
}
#Override
public People findById(int id) {
return (People) this.sessionFactory.getCurrentSession().get(People.class, id);
}
}
/* ---------------------------------------------------- */
package com.example.test.service;
import java.util.List;
import com.example.test.entity.People;
public interface PeopleManager {
public void save(People people);
public void delete(People people);
public void update(People people);
public List<People> findAll();
public People findById(int id);
}
/* ---------------------------------------------------- */
package com.example.test.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.example.test.dao.PeopleDao;
import com.example.test.entity.People;
#Service
#Transactional
public class PeopleManagerImpl implements PeopleManager {
#Autowired
private PeopleDao peopleDao;
#Override
public void save(People people) {
peopleDao.save(people);
}
#Override
public void delete(People people) {
peopleDao.delete(people);
}
#Override
public void update(People people) {
peopleDao.update(people);
}
#Override
public List<People> findAll() {
return peopleDao.findAll();
}
#Override
public People findById(int id) {
return peopleDao.findById(id);
}
/* ---------------------------------------------------- */
package com.example.test.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.example.test.entity.People;
import com.example.test.service.PeopleManager;
#Controller
public class PeopleController {
#Autowired
private PeopleManager peopleManager;
#RequestMapping(value = "/people/{id}", method = RequestMethod.GET)
public String home(Model model, #PathVariable("id") String id) {
People p;
try {
p = peopleManager.findById(Integer.parseInt(id));
if (p != null) {
model.addAttribute("message", "user exist, do any action");
} else {
model.addAttribute("message", "user NOT exist");
}
} catch (NullPointerException e) {
model.addAttribute("message", "user NOT exist");
}
return "people";
}
}
/* ---------------------------------------------------- */
Refactor the null check out of your controller. Controllers shouldn't have any business logic in them. The correct place for this is inside your service class.
#Override
#Transactional
public People findById(int id) throws ObjectNotFoundException{
People people = null;
people = peopleDao.findById(id);
if(people == null){
throw new ObjectNotFoundException("Couldn't find a People object with id " + id);
}
return people;
}
I would write a custom exception that extends RuntimeException that is thrown if your People object is null.
This is best practice as you can reuse your ObjectNotFoundException in all your service layers. Then make all your controller methods throw Exception and investigate global error handling for controllers.
Also, it is best practice to not annotate your entire service class as #Transactional, mark the individual methods. That way if you need to add additional methods to your services you can choose if you want them to run in a transactional context.