spring boot repository throws an exception - java

I am new to spring boot.
I have created my web application as below.
SampleApplication.java
#SpringBootApplication
public class SampleApplication implements CommandLineRunner {
#Autowired
DataSource dataSource;
#Autowired
private UserRepository userRepository;
Logger logger = LoggerFactory.getLogger(SampleApplication.class);
public static void main(String[] args) {
SpringApplication.run(SampleApplication.class, args);
}
#Transactional(readOnly = true)
#Override
public void run(String... args) throws Exception {
UserLoginController userLoginController = new UserLoginController();
System.out.println("DATASOURCE = " + dataSource);
logger.debug("\nUser: "+userRepository.findByName("user").getName());
logger.debug(userLoginController.getUserInfo("user","pword"));
}
}
UserRepository.java
#EnableJpaRepositories
#Repository
public interface UserRepository extends CrudRepository<User,Long> {
User findByName(String name);
}
User.java
#Entity
#Table(name="USER")
public class User
implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
#SequenceGenerator(name="USER_ID_GENERATOR", sequenceName="USER_SEQ")
#GeneratedValue(strategy=GenerationType.AUTO, generator="USER_ID_GENERATOR")
private Long id;
#Column(name="NAME")
private String name;
#Column(name="PASSWORD")
private Long password;
public Long getId()
{
return this.id;
}
public void setId(Long id)
{
this.id = id;
}
public String getName()
{
return this.name;
}
public void setName(String name)
{
this.name = name;
}
public String getPassword()
{
return this.password;
}
public void setPassword(String password)
{
this.password = password;
}
UserLoginController.java
#Controller
public class UserLoginController {
Logger logger = LoggerFactory.getLogger(UserLoginController.class);
#RequestMapping(value = "/userLogin**", method = RequestMethod.POST)
public #ResponseBody String getUserInfo(#RequestParam("mobile") String uName, #RequestParam("pin") String pWord){
logger.debug("UserLoginController | uName: " + uName + " pWord: " + pWord);
UserLoginService userLoginService = new UserLoginService();
String user = null;
try {
logger.debug("UserLoginController | Validate user. uName: " + uName + " pWord: " + pWord);
user = userLoginService.validateSysUser(uName, pWord);
} catch (Exception e) {
logger.debug("UserLoginController | Validate user Exception: " + e.getMessage()+", "+e.getStackTrace());
}
if (user != null) {
logger.debug("UserLoginController | Returning aircash user");
return user;
} else {
logger.debug("UserLoginController | Returning NULL");
return null;
}
}
}
UserLoginService .java
public class UserLoginService {
Logger logger = LoggerFactory.getLogger(UserLoginService.class);
#Autowired
DataSource dataSource;
#Autowired
private UserRepository userRepository;
public String validateSysUser(String uName, String pWord) throws Exception{
logger.debug("UserLoginService | uName: "+uName+" pWord: "+pWord);
User user = new User();
String auser = userRepository.findByName(uName).getName();
if ((auser != null) && (validatePword(user.getPassword(),pWord)){
logger.debug("UserLoginService | User found: "+user.getName());
return auser;
}else {
logger.debug("UserLoginService | User not found");
return null;
}
}
public static boolean validatePword(String pWord,String pWord2){
return BCrypt.checkpw(pWord2,pWord);
}
}
Problem is, When I run the application,This part give me the intended response
logger.debug("\nUser: "+userRepository.findByName("user").getContactNo());
But, next line throws an exception. I also tried calling the controller using the postman too. But the same exception comes.
logger.debug(userLoginController.getUserInfo("user","pword"));
The exception is thrown from the UserLoginService.java class. The exception message is shown as null
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>robicash</groupId>
<artifactId>distributorcommision</artifactId>
<version>1.0</version>
<name>distributorcommission</name>
<description>commision for distributors</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mindrot</groupId>
<artifactId>jbcrypt</artifactId>
<version>0.3m</version>
</dependency>
<!--<dependency>-->
<!--<groupId>com.oracle</groupId>-->
<!--<artifactId>ojdbc8</artifactId>-->
<!--<version>11.2.0.4</version>-->
<!--</dependency>-->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc7</artifactId>
<version>12.1.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
I don't understand why the same repository give two results when called.
Can you please tell me how to get it working.

You cannot instantiate the UserLoginService userLoginService = new UserLoginService();
You have to inject it into the controller:
#Autowired
UserLoginService userLoginService;
Spring will only manage your service if it's instantiated by Spring and then injected.
And yes Kes is partially right. You must add #Service or #Component annotation in UserLoginService:
#Service
public class UserLoginService {

Related

Spring boot ERROR "Field trepository in TrainerController required a bean of type TrainerRepo that could not be found." ."

Im making a Spring boot project and when running it says:
"Field trepository in com.example.trainerplanner.trainerController.TrainerController required a bean of type 'com.example.trainerplanner.model.domain.TrainerRepository' that could not be found."
I already cleaned the .m2 directory and tried to add/delete many different dependencies.
package com.example.trainerplanner;
#ComponentScan({"com.example.trainerplanner.model.domain"})
#EnableAutoConfiguration
#EnableJpaRepositories(basePackageClasses = {TrainerRepository.class, CategoryRepository.class})
#SpringBootApplication
public class TrainerplannerApplication {
private static final Logger log = LoggerFactory.getLogger(TrainerplannerApplication.class);
public static void main(String[] args) {
SpringApplication.run(TrainerplannerApplication.class, args);
}
#Bean
public CommandLineRunner trainerDemo(CategoryRepository crepository, TrainerRepository trepository) {
return (args) -> {
log.info("Save some exercises");
//Tässä kohdassa tehdään uudet kategoriat "c repositoryyn".
//Ensiksi on yläkropan päälihakset ja sitten alakropan
crepository.save(new Category("Biceps")); //Hauikset
crepository.save(new Category("Triceps")); //Ojentajat
crepository.save(new Category("Chest")); //Rinta
crepository.save(new Category("Shoulders")); //Olkapäät
crepository.save(new Category("Back")); //Selkä
crepository.save(new Category("Quadriceps")); //Etureidet
crepository.save(new Category("Hamstrings")); //Takareidet
crepository.save(new Category("Calves")); //Pohkeet
crepository.save(new Category("Glutes")); //Pakarat
trepository.save(new Trainer("Bicep curl", 8, 3, crepository.findByName("Biceps").get(0)));
trepository.save(new Trainer("Tricep extension", 8, 3, crepository.findByName("Triceps").get(0)));
trepository.save(new Trainer("Squat", 8, 3, crepository.findByName("Quadriceps").get(0)));
User userYksi = new User("user", "$2y$12$4iGWyQs5hC6ibe5Pq7ochekppUZcSfeIV.tjgZIuSobVA8B5vOhXK", "USER");
//Molemmat salasanat hashattu BCryptillä, roundit oli 12 ja 9
User userKaksi = new User("admin", "$2y$06$K9UJzObPGyroQKlkTzWWz.BlUurpYCMFelyvM/2AVYSbzogvd3.zq", "ADMIN");
urepository.save(userYksi);
urepository.save(userKaksi);
log.info("fetch all exercises");
for (Trainer trainer : trepository.findAll()) {
log.info(trainer.toString());
};
};}
This is the springbootapp
#Controller
#Component
#EnableJpaRepositories
public class TrainerController {
#Autowired
private TrainerRepository trepository;
#Autowired
private CategoryRepository crepository;
//Req. mappingeissä nähdään mikä menee urlin loppuun. esim. localhost:8080/trainerlist palauttaa trainerlist thymeleafsivun
//Metodit eri toiminnoille, esim lisää, poista, lista, tallenna.
#RequestMapping(value= {"/", "/trainerlist"})
public String trainerList(Model model) {
model.addAttribute("trainers", trepository.findAll());
return "trainerlist";
}
#RequestMapping(value = "/add")
public String addTrainer(Model model){
model.addAttribute("trainer", new Trainer());
model.addAttribute("category", crepository.findAll());
return "addtrainer";
}
#RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(Trainer trainer){
trepository.save(trainer);
return "redirect:trainerlist";
}
//Poistaa ID:n avulla trainerin ja palauttaa //trainerlist-sivun
#RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
public String deleteTrainer(#PathVariable("id") Long trainerId, Model model) {
trepository.deleteById(trainerId);
return "redirect:../trainerlist";
}
}
Controller class
#Repository
public interface CategoryRepository extends CrudRepository<Category, Long> {
List<Category> findByName(String name);
}
CategoryRepo, TrainerREpo is same but with different name.
#Component
public class TrainerModel {
public String Trainer(#RequestParam(value="name")String name, Integer reps, Integer sets, Model model) {
model.addAttribute("name", name);
model.addAttribute("reps", reps);
model.addAttribute("sets", sets);
return "index";
}
}
This is the TrainerModel class
#Component
#Entity
public class Trainer {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;
private String name;
private Integer reps, sets;
#ManyToOne
#JoinColumn(name = "categoryid")
#JsonManagedReference
private Category category;
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public Trainer() {
//Tyhjä
}
public Trainer(String name, Integer reps, Integer sets, Category category) {
super();
this.name = name;
this.reps = reps;
this.sets = sets;
this.category =category;
}
//Asetetaan getterit ja setterit Traineriin.
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;
}
public Integer getReps() {
return reps;
}
public void setReps(Integer reps) {
this.reps = reps;
}
public Integer getSets() {
return sets;
}
public void setSets(Integer sets) {
this.sets = sets;
}
#Override
public String toString() { //Jos kategoria tyhjä niin palautetaan ensimmäinen kohta, muuten else-kohta.
if (this.category != null)
return "Trainer [id=" + id + ", name=" + name + ", reps=" + reps + ", =" + sets + " sets =" + this.getCategory() + "]";
else
return "Trainer [id=" + id + ", name=" + name + ", reps=" + reps + ", sets=" + sets + "]";
}
}
And This is the Trainer class
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>trainerplanner</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>trainerplanner</name>
<description>Trainer planner for exercising</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Pom xml, re did the whole project with spring initialzr but no effect.

findAll() is not working in SpringBoot Rest MySql CRUD operations application

I am trying to perform CRUD operations using spring boot+REST+MySQL
along crudrepository interface,when i try to get data from database,i
am getting empty list back.I found that findAll() method in my application is not working as expected.
My Application class
#SpringBootApplication
public class Blog {
public static void main(String[] args) {
SpringApplication.run(Blog.class, args);
System.out.println("Application Started");
}}
My Entity class
#Entity
#Table(name="posts")
public class Post {
#Id
#Column(name="id")
int postId;
#Column(name="title")
String title;
#Column(name="body")
String body;
public Post() {}
public Post(int postId, String title, String body) {
this.postId = postId;
this.title = title;
this.body = body;
} //getters and setters and toString()
Controller Class
#RestController
public class PostsController {
#Autowired
private PostsService service;
#RequestMapping("/posts")
public List<Post> getPosts(){
return service.getPosts();
}
#RequestMapping("/posts/{id}")
public Post getPost(#PathVariable int id) {
return service.getPost(id);
}
#RequestMapping(method=RequestMethod.POST, value="/posts")
public void addPost(#RequestBody Post listElement) {
service.addPost(listElement);
}
#RequestMapping(method=RequestMethod.PUT, value="/posts/{id}")
public void updatePost(#RequestBody Post post) {
service.updatePost(post);
}
#RequestMapping(method=RequestMethod.DELETE, value="/posts/{id}")
public void deletePost(#PathVariable int id) {
service.deletePost(id);
}
Service Classs
#Service
public class PostsService {
#Autowired
private PostRepository repo;
public List<Post> getPosts(){
List<Post> list = new ArrayList<>();
System.out.println("at Service");
for(Post post: repo.findAll()) {
System.out.println("in for loop");
list.add(post);
}
return list;
}
public Post getPost(int id) {
return repo.findById(id).get();
}
public void addPost(Post listElement) {
repo.save(listElement);
}
public void updatePost(Post post) {
repo.save(post);
}
public void deletePost(int id) {
repo.deleteById(id);
}
}
Repository Interface
public interface PostRepository extends CrudRepository<Post, Integer>
{ }
Application.properties file
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/blog?useSSL=false&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.studyeasy</groupId>
<artifactId>06.01-RestfulMicroserviceWithDB</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>06.01-RestfulMicroserviceWithDB</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Outputs
when i perform get operation, out put was "[]"
when i perform get operation by id , out put was
{
"timestamp": "2019-03-29T02:44:00.768+0000",
"status": 500,
"error": "Internal Server Error",
"message": "No value present",
"path": "/posts/3" }
java.util.NoSuchElementException: No value present
when i perform delete operation ,i got this output
"org.springframework.dao.EmptyResultDataAccessException: No class org.studyeasy.entity.Post entity with id 3 exists!" in console and
output in postman was
{ "timestamp": "2019-03-29T02:48:51.423+0000",
"status": 500,
"error": "Internal Server Error",
"message": "No class org.studyeasy.entity.Post entity with id
3 exists!",
"path": "/posts/3" }
Do as follows :
PostController.java
#RestController
public class PostController {
#Autowired
private PostsService service;
#RequestMapping("/posts")
public List<Post> getPosts(){
return service.getPosts();
}
#RequestMapping("/posts/{id}")
public Post getPost(#PathVariable int id) {
return service.getPost(id);
}
#RequestMapping(method=RequestMethod.POST, value="/posts")
public void addPost(#RequestBody Post listElement) {
service.addPost(listElement);
}
#RequestMapping(method=RequestMethod.PUT, value="/posts/{id}")
public void updatePost(#RequestBody Post post) {
service.updatePost(post);
}
#RequestMapping(method=RequestMethod.DELETE, value="/posts/{id}")
public void deletePost(#PathVariable int id) {
service.deletePost(id);
}
}
PostService.java
#Service
public class PostsService {
#Autowired
private PostRepository repo;
public List<Post> getPosts(){
return (List<Post>) repo.findAll();
}
public Post getPost(int id) {
return repo.findById(id).get();
}
public void addPost(Post listElement) {
repo.save(listElement);
}
public void updatePost(Post post) {
repo.save(post);
}
public void deletePost(int id) {
repo.deleteById(id);
}
}
PostRepository.java
#Repository
public interface PostRepository extends CrudRepository<Post, Integer>{
}
Post.java
#Entity
#Table(name="posts")
public class Post implements Serializable{
#Id
#Column(name="id")
int postId;
#Column(name="title")
String title;
#Column(name="body")
String body;
public Post() {}
public Post(int postId, String title, String body) {
this.postId = postId;
this.title = title;
this.body = body;
}
//gettters & setters
}
You can also refer Best Practice to send response for other stuffs. . .
Issue was you have missed #ResponseBody annotation. So here i have used #RestController
Output:

Can't create table with jpa+spring boot

I'm trying to generate table using JPA. but i can't create it. There is no error in the code, but it seems that there is configuration error. but i can't find it, i tried many configurations but nothing happen.
Thanks a lot.
This is application.property:
spring.datasource.url=jdbc:mysql://localhost:3306/springapp
spring.datasource.username= root
spring.datasource.password= me
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=create
this is my class:
#Entity
public class Customer {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;
private String phone;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Customer(String name, String phone) {
super();
this.name = name;
this.phone = phone;
}
public Customer() {
super();
}
}
This is the application:
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
And this is the controller:
#RestController
#RequestMapping("/customer")
public class CustomerController {
#Autowired
CustomerRepository customerRepository;
#RequestMapping("/findall")
#ResponseBody
public List<Customer> findAll() {
return customerRepository.findAll();
}
}
Pom.xml
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>GStock-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>GStock-3</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Try to add #EntityScan
#EntityScan("<package with entities>")
#SpringBootApplication
public class Application { ... }
With the current information I have a couple of suggestions / Questions that might help you allong:
Does the "springapp" database exist with the correct user (root) and password (me) assigned to it in MySQL
Has MySQL been started?
I see no #Repository definition in your code e.g.
#Repository
public interface CustomerRepository extends JpaRepository{}
execute following on your mysql:
mysql> create database db_example; -- Create the new database
mysql> create user 'springuser'#'localhost' identified by 'ThePassword'; -- Creates the user
mysql> grant all on db_example.* to 'springuser'#'localhost'; -- Gives all the privileges to the new user on the newly created database
and add into application.xml:
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=ThePassword
OR
you can go through this link

Use JPA Spring boot with SQL Server

I want to use JPA in Spring boot with SQL Server by STS
This is my table:
MAVEN
<dependencies>
<dependency>
<groupId>com.hynnet</groupId>
<artifactId>sqljdbc-chs</artifactId>
<version>4.0.2206.100</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
application.properties
spring.datasource.driver-class- name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.url=jdbc:sqlserver://localhost:1433;databaseName=quanlybanhang
spring.datasource.username=sa
spring.datasource.password=1
spring.jpa.hibernate.ddl-auto=create
spring.datasource.initialize=true
spring.jpa.database=SQL_SERVER
Model.Account.class
#Entity
#Table(name="taikhoan",uniqueConstraints=#UniqueConstraint(columnNames = { "tendangnhap" }) )
public class Account {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#NotNull
private String tendangnhap;
#NotNull
private String matkhau;
public Account(String tendangnhap, String matkhau) {
super();
this.tendangnhap = tendangnhap;
this.matkhau = matkhau;
}
public Account() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTendangnhap() {
return tendangnhap;
}
public void setTendangnhap(String tendangnhap) {
this.tendangnhap = tendangnhap;
}
public String getMatkhau() {
return matkhau;
}
public void setMatkhau(String matkhau) {
this.matkhau = matkhau;
}
}
interface AccountDAO
public interface AccountDAO extends JpaRepository<Account, Integer>{
}
ServiceAccount.class
#Service
public class ServerAccount {
#Autowired
AccountDAO server;
public void them(Account acc){
server.save(acc);
}
public List<Account> lietke(){
return server.findAll();
}
}
ServicesAccount.class
#Service
public class ServerAccount {
#Autowired
AccountDAO server;
Account acc=new Account("khang", "1");
public void addAccount(){
server.save(acc);
}
public List<Account> lietke(){
return server.findAll();
}
}
I called method addAccount() in Controller and this is Exception I got
"java.lang.NoClassDefFoundError: org/springframework/orm/jpa/support/PersistenceAnnotationBeanPostProcessor"
"Caused by: java.lang.ClassNotFoundException: org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"
Please help me fix this exception. Thanks!!!
From your dependencies you missed (check you java version you use):
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.5.2.jre8-preview</version>
<scope>test</scope>
</dependency>
and into the application properties correct this line:
spring.datasource.driver-class- name=com.microsoft.sqlserver.jdbc.SQLServerDriver
to
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect

Getting the error : Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException

I am new to spring and I wanted to communicate with mongodb via spring. I tried and tested the following code on SPRING TOOL SUITE but I am getting the following error:
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [hello.PersonRepository] is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:371)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:331)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:968)
at hello.Runhere.main(Runhere.java:19)
Kindly tell me where is the problem.
Here is Person.java class
package hello;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document
public class Person {
#Id
private String personId;
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getPersonId() {
return personId;
}
public void setPersonId(final String personId) {
this.personId = personId;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(final int age) {
this.age = age;
}
#Override
public String toString() {
return "Person [id=" + personId + ", name=" + name + ", age=" + age
+ "]";
}
}
Here is my PersonRepository.java file
package hello;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;
#Repository
public class PersonRepository {
#Autowired
MongoTemplate mongoTemplate;
public void countUnderAge() {
List<Person> results = null;
Query query = new Query();
Criteria criteria = new Criteria();
criteria = criteria.and("age").lte(21);
query.addCriteria(criteria);
results = mongoTemplate.find(query, Person.class);
System.out.println(results.size());
}
public void countAllPersons() {
List<Person> results = mongoTemplate.findAll(Person.class);
System.out.println("The total number of players " + results.size());
}
public void insertPersonWithNameAayushAndRandomAge() {
double age = Math.ceil(Math.random() * 100);
Person p = new Person("Aayush", (int) age);
mongoTemplate.insert(p);
}
public void createPersonCollection() {
if (!mongoTemplate.collectionExists(Person.class)) {
mongoTemplate.createCollection(Person.class);
}
}
public void dropPersonCollection() {
if (mongoTemplate.collectionExists(Person.class)) {
mongoTemplate.dropCollection(Person.class);
}
}
}
Here is my springconfig.java file:
package hello;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;
import com.mongodb.Mongo;
#Configuration
#EnableMongoRepositories
#Import(RepositoryRestMvcConfiguration.class)
#EnableAutoConfiguration
public class springconfig extends AbstractMongoConfiguration {
#Override
protected String getDatabaseName() {
return "demo";
}
#SuppressWarnings("deprecation")
#Override
public Mongo mongo() throws Exception {
return new Mongo();
}
}
Here is my class which contains the main method :
package hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Runhere {
public static void main(String[] args) {
#SuppressWarnings("resource")
ApplicationContext context = new AnnotationConfigApplicationContext(springconfig.class);
PersonRepository personRepository = context.getBean(PersonRepository.class);
personRepository.dropPersonCollection();
personRepository.createPersonCollection();
for (int i = 0; i < 10000; i++) {
personRepository.insertPersonWithNameAayushAndRandomAge();
}
personRepository.countAllPersons();
personRepository.countUnderAge();
}
}
And finally here is my pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.test</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>integration_with_mongo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.1.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<start-class>demo.IntegrationWithMongoApplication</start-class>
<java.version>1.7</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-repository</artifactId>
<version>1.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.webflow</groupId>
<artifactId>spring-webflow</artifactId>
<version>2.4.1.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
try to add bean in the application config.xml
<mvc:resources mapping="" location="" />
<bean id="PersonRepository" class="(complete package path)hello.PersonRepository" />
SpringBoot - In hope it will help any SpringBoot developer
This error mostly hits when the bean you are calling from another package.
Specifically for Spring boot, you can try an annotation for it, to scan the component you want to get bean of it.
#ComponentScan("your package")
place the #Componentscan annotation in the main class where you are getting the bean.
Example
#ComponentScan("com.spring.crud.controller")
public class SpringCrudApplication {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(SpringCrudApplication.class, args);
HomeController bean1 = context.getBean(HomeController.class);
System.out.println(bean1.HomePage());
}
}
so, in the above example I am taking controller bean which I created in the package of com.spring.crud.controller
if you are interested in explanation see this article:
https://baidar-sabaoon.medium.com/how-to-handle-nosuchbeandefinitionexception-in-spring-boot-7255170d702c

Categories

Resources