Failed to create query for method public abstract - spring-boot

Simple I want test my application to connect with database to insert
some record statically.
it properly work or not.but it throws this type of error that i
mentioned below;
I donot know where i make mistake,I define everything properly
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'turistRepo': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract com.main.ToursTravels.model.Turist com.main.ToursTravels.repo.TuristRepo.findByName(java.lang.String)! No property name found for type Turist!
turistrepo.java
package com.main.ToursTravels.repo;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.main.ToursTravels.model.Turist;
#Repository
public interface TuristRepo extends CrudRepository<Turist, Long> {
Turist findByName(String turistname);
}
vechiletyperepo.java
package com.main.ToursTravels.repo;
import java.util.List;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.main.ToursTravels.model.Turist;
import com.main.ToursTravels.model.VechileType;
#Repository
public interface VechileTypeRepo extends CrudRepository<VechileType, Long> {
List<VechileType> findByTurist(Turist turist , Sort sort);
}
mainclasss.java
package com.main.ToursTravels;
import java.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.main.ToursTravels.model.Turist;
import com.main.ToursTravels.model.VechileKind;
import com.main.ToursTravels.model.VechileType;
import com.main.ToursTravels.repo.TuristRepo;
import com.main.ToursTravels.repo.VechileTypeRepo;
#SpringBootApplication
public class ToursTravelsApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(ToursTravelsApplication.class, args);
}
#Autowired
TuristRepo trp;
#Autowired
VechileTypeRepo vtrp;
#Override
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
Turist trs = new Turist();
trs.setTuristname("NewsWels");
trs.setTravelkm(100);
trs.setTraveldate(LocalDate.of(2020, 20, 11));
trs.setDrivername("prabhka5r");
VechileType vtp= new VechileType();
vtp.setVechilekind(VechileKind.SEDAN);
vtp.setRateperkm(6);
vtp.setMinprice(2530.00);
trs.setVechileno("GJ05K2619");
trs.setTotalamount(15186.00);
trs.setBookingstatus(true);
trs.setVechiletype(vtp);
vtp.setTurist(trs);
trp.save(trs);
}
}
turist.java
package com.main.ToursTravels.model;
import java.math.BigDecimal;
import java.time.LocalDate;
import javax.persistence.CascadeType;
import javax.persistence.Column;
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.OneToOne;
import javax.persistence.Table;
import lombok.Data;
#Entity
#Table(name="turist")
#Data
public class Turist {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="truist_id")
private Long truistid;
#Column(name="turistname")
private String turistname;
#Column(name="travel_km")
private int travelkm;
#Column(name="travel_date")
private LocalDate traveldate;
#Column(name="drivername")
private String drivername;
#OneToOne(fetch=FetchType.LAZY,cascade=CascadeType.ALL)
#JoinColumn(name="booking_id")
private VechileType vechiletype;
#Column(name="vechileno")
private String vechileno;
#Column(name="total_amount")
private Double totalamount;
#Column(name="BOOKING_status")
private boolean bookingstatus;
public Turist(){}
public Turist(String turistname, int travelkm, LocalDate traveldate, String drivername, VechileType vechiletype,
String vechileno, Double totalamount, boolean bookingstatus) {
super();
this.turistname = turistname;
this.travelkm = travelkm;
this.traveldate = traveldate;
this.drivername = drivername;
this.vechiletype = vechiletype;
this.vechileno = vechileno;
this.totalamount = totalamount;
this.bookingstatus = bookingstatus;
}
}
VechileType.java
package com.main.ToursTravels.model;
import java.math.BigDecimal;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import lombok.Data;
#Entity
#Table(name="vechiletype")
#Data
public class VechileType {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="booking_id")
private Long bookingid;
#OneToOne(fetch=FetchType.LAZY,cascade=CascadeType.ALL,mappedBy="vechiletype")
private Turist turist;
#Enumerated(EnumType.STRING)
#Column(name="vechilekind")
private VechileKind vechilekind;
#Column(name="rate_per_km")
private int rateperkm;
#Column(name="miniprice")
private Double minprice;
public VechileType(){}
public VechileType(Turist turist, VechileKind vechilekind, int rateperkm, Double minprice) {
this.turist = turist;
this.vechilekind = vechilekind;
this.rateperkm = rateperkm;
this.minprice = minprice;
}
}

Your Repository method references a name field for your Turist class, but none exists. You have turistname available to query.
So your method name should be this:
Turist findByTuristname(String turistname);

Related

Validate input inside embedded lists using #DecimalMin and #Valid

So what I am trying to do is to create embedded classes with validation in each class and then get the desired error message when I enter an illegal value. When I have embedded classes, validation suddenly stops working for some reason. I have extracted the core of the problem in the classes below
UserController Class:
// UserController.java
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
#RestController
public class UserController {
public void printUsers(#Valid List<User> users) {
System.out.println(users.get(0).getPeople().get(0).getAge());
}
#GetMapping("/")
public void getUser() {
List<User> users = new ArrayList<>();
Person person = new Person();
person.setAge(-10.0);
person.setFirstName("Test");
person.setLastName("Embedded Validation");
List<Person> persons = new ArrayList<>();
persons.add(person);
User user = new User(persons);
users.add(user);
printUsers(users);
}
}
User Class:
// User.java
package com.example.demo;
import lombok.Builder;
import lombok.Data;
import javax.validation.constraints.NotNull;
import java.util.List;
#Data
#Builder
public class User {
#NotNull
private List<Person> people;
}
Person Class:
// Person.java
package com.example.demo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.NotNull;
#Data
#Builder
#AllArgsConstructor
#NoArgsConstructor
public class Person {
#NotNull
#DecimalMin("0.0")
private double age;
#NotNull
private String firstName;
#NotNull
private String lastName;
}
If you run this it will print -10.0, but I have explicitly told the Person class to have a min DecimalVal of 0.0, so my assignment of person.setAge(-10.0); in the UserController class should not be allowed.
How come validation on embedded classes do not work?

Spring can't find repository bean

I'm using spring boot with spring data jdbc and I got trouble with run my app
I have StudentService class:
package ru.turnip.service;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import ru.turnip.model.Student;
import ru.turnip.repository.StudentRepository;
import ru.turnip.utils.student.BusyStudents;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
#Service
public class StudentService {
private final BusyStudents busyStudents;
private final StudentRepository studentRepository;
public StudentService(BusyStudents busyStudents, StudentRepository studentRepository) {
this.busyStudents = busyStudents;
this.studentRepository = studentRepository;
}
...
}
And StudentRepository interface:
package ru.turnip.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import ru.turnip.model.Student;
import java.util.UUID;
#Repository
public interface StudentRepository extends CrudRepository<Student, UUID> { }
So, when I try to run app, I get an eror, and I can't figure out where the problem is.
That my config class:
package ru.turnip;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.relational.core.mapping.event.BeforeSaveEvent;
import org.springframework.scheduling.annotation.EnableScheduling;
import ru.turnip.model.Student;
import java.time.Clock;
import java.util.UUID;
#ComponentScan
#Configuration
#EnableScheduling
public class ApplicationConfig {
#Bean
public Clock clock() {
return Clock.systemDefaultZone();
}
#Bean
public ApplicationListener<BeforeSaveEvent> idGenerator() {
return event -> {
var entity = event.getEntity();
if (entity instanceof Student) {
((Student) entity).setId(UUID.randomUUID());
}
};
}
}
And project structure:
I tried to explicitly set package to be scanned, and also moved the repository to the package with the config. Also I tried to annotate with #Autowired field and constructor in StudentService

No qualifying bean of type,expected at least 1 bean which qualifies as autowire, org.springframework.beans.factory.UnsatisfiedDependencyException:

I Created a simple Springboot Application with H2 DB. Not able to start the spring boot Application getting below error on startup. I have added all the necessary configurations.
Exception encountered during context initialization - cancelling
refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'studentController': Unsatisfied
dependency expressed through field 'studentService'; nested exception
is org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'com.example.test.serviceimpl.StudentServiceImpl' available: expected
at least 1 bean which qualifies as autowire candidate. Dependency
annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
Controller:
package com.example.test.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.example.test.serviceimpl.StudentServiceImpl;
import comm.example.test.model.Student;
#RestController
public class StudentController {
#Autowired(required=true)
private StudentServiceImpl studentService;
#GetMapping("/student")
private List<Student> getAllStudent() {
return studentService.getAllStudent();
}
#GetMapping("/student/{id}")
private Student getStudent(#PathVariable("id") Long id) {
return studentService.getStudentById(id);
}
}
Student Pojo class
package comm.example.test.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
#Getter
#Setter
#AllArgsConstructor
#Entity
#Table(name="student")
public class Student {
#Id
#Column
private Long id;
#Column
private String name;
#Column
private int age;
#Column
private String email;
}
StudentService Interface:
package com.example.test.service;
import java.util.List;
import comm.example.test.model.Student;
public interface StudentService {
List<Student> getAllStudent();
Student getStudentById(Long id);
}
StudentServiceImpl:
package com.example.test.serviceimpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.test.repository.serviceimpl.StudentRepositoryServiceImpl;
import com.example.test.service.StudentService;
import comm.example.test.model.Student;
public class StudentServiceImpl implements StudentService {
#Autowired
private StudentRepositoryServiceImpl serviceImpl;
#Override
public List<Student> getAllStudent() {
return serviceImpl.getAllStudent();
}
#Override
public Student getStudentById(Long id) {
return serviceImpl.getStudentById(id);
}
}
RepositoryService:
package com.example.test.repository.serviceimpl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.test.repository.StudentRepository;
import comm.example.test.model.Student;
#Service
public class StudentRepositoryServiceImpl {
#Autowired
private StudentRepository repo;
public List<Student> getAllStudent() {
List<Student> students = new ArrayList<Student>();
repo.findAll().forEach(student -> students.add(student));
return students;
}
public Student getStudentById(Long id) {
return repo.findById(id).get();
}
}
Repository:
package com.example.test.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import comm.example.test.model.Student;
#Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
}
Your StudentServiceImpl needs a #Service annotation to be injected.

What does 'Propagation.NEVER Executes non-transactionally' mean in Spring?

In the code below, the save operation in createDevice method inside DeviceService class will not be executed inside a transaction, what does it mean that this operation is not executed inside a transaction?
Is it possible to execute an operation on the database without a transaction?
package controller;
import model.Device;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import service.DeviceService;
#RestController
public class DeviceController {
#Autowired
private DeviceService deviceService;
#PostMapping("/devices")
#ResponseStatus(HttpStatus.CREATED)
public void createDevice(#RequestBody Device device) {
deviceService.createDevice(device);
}
}
--
package service;
import model.Device;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import repository.DeviceRepository;
#Service
public class DeviceService {
#Autowired
private DeviceRepository deviceRepository;
#Transactional(propagation = Propagation.NEVER)
public void createDevice(Device device) {
deviceRepository.save(device);
}
}
--
package repository;
import model.Device;
import org.springframework.data.jpa.repository.JpaRepository;
public interface DeviceRepository extends JpaRepository<Device, Integer> {
}
--
package model;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Device {
#Id
private Integer id;
private String name;
}
Edit
I'm using MySQL database.
The Operation gets executed successfully.
Any details on how this gets executed without a transaction? What is being done behinde the scene?
What is the difference between executing an operation inside a transaction and without a transaction?

getting below mention Exception while executing the query(Spring Boot+JPA+Hibernate)

This is the error received when try to execute the sample query. Please help me to get out of this.
org.hibernate.hql.internal.ast.QuerySyntaxException: Transaction is not mapped
below is the entity class with mapping
Transaction.java
package org.npst.mb.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.stereotype.Component;
#Entity
#Table(name="transaction")
public class Transaction implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="transactionid")
private int transactionid;
#Column(name="appid")
private int appid;
public int getTransactionid() {
return transactionid;
}
public void setTransactionid(int transactionid) {
this.transactionid = transactionid;
}
public int getAppid() {
return appid;
}
public void setAppid(int appid) {
this.appid = appid;
}
}
Install .java(Spring Boot App Stater)
package org.npst.mb.install;
import org.npst.mb.controller.JobLauncherController;
import org.npst.mb.dao.TransactionDao;
import org.npst.mb.service.TransactionService;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource;
#SpringBootApplication
#EnableBatchProcessing
#ImportResource("classpath:batchjob.xml")
#ComponentScan(basePackages ={"org.npst.mb.entity.*"},basePackageClasses= {TransactionService.class,TransactionDao.class,JobLauncherController.class})
public class Install {
public static void main(String[] args) {
SpringApplication.run(Install.class, args);
}
}
DAOIMPL(Query to interact with DB)
package org.npst.mb.dao.impl;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.npst.mb.dao.TransactionDao;
import org.npst.mb.entity.Transaction;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
#Transactional
#Repository
public class TransactionDaoImpl implements TransactionDao {
#PersistenceContext
private EntityManager entityManager;
#Override
public boolean addTransaction(Transaction txndata) {
return true;
}
#Override
public long getMaxTid() {
try {
System.out.println("maxtxnid::");
String hql="from Transaction where transactionid > 0";
entityManager.createQuery(hql).getMaxResults();
return 0;
}
catch(Exception sql) {
System.out.println(sql.getMessage());
sql.printStackTrace();
return 0;
}
}
}
application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/test1
spring.datasource.username=root
spring.datasource.password=naveen123
spring.datasource.tomcat.max-wait=20000
spring.datasource.tomcat.max-active=50
spring.datasource.tomcat.max-idle=20
spring.datasource.tomcat.min-idle=15
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect
spring.jpa.properties.hibernate.id.new_generator_mappings = false
spring.jpa.properties.hibernate.format_sql = true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create
spring.data.jpa.repositories.enabled=true
spring.jpa.open-in-view=true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
As I understand, #ComponentScan scans and creates beans for the classes annotated #Component, #Service, #Controller,#Repository.
#EntityScan annotation is used to identify JPA entities(persistent classes).
Can you try by adding #EntityScan("org.npst.mb.entity")?

Resources