How to map a jpa result to json - java

I have this entity
package com.example.demo;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.sql.Timestamp;
import java.util.Objects;
#Entity
public class Scanlog {
private String docId;
private String userName;
private Timestamp scanDate;
private Integer scanPlaza;
private long conteo;
#Id
#Column(name = "DOC_ID", nullable = false, length = 12)
public String getDocId() {
return docId;
}
public void setDocId(String docId) {
this.docId = docId;
}
#Basic
#Column(name = "USER_NAME", nullable = false, length = 20)
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
#Basic
#Column(name = "SCAN_DATE", nullable = false)
public Timestamp getScanDate() {
return scanDate;
}
public void setScanDate(Timestamp scanDate) {
this.scanDate = scanDate;
}
#Basic
#Column(name = "SCAN_PLAZA", nullable = true)
public Integer getScanPlaza() {
return scanPlaza;
}
public void setScanPlaza(Integer scanPlaza) {
this.scanPlaza = scanPlaza;
}
public Scanlog() {
}
public Scanlog(String docId, String userName, Timestamp scanDate, Integer scanPlaza) {
this.docId = docId;
this.userName = userName;
this.scanDate = scanDate;
this.scanPlaza = scanPlaza;
}
public Scanlog(String userName, long conteo) {
this.userName = userName;
this.conteo = conteo;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Scanlog scanlog = (Scanlog) o;
return Objects.equals(docId, scanlog.docId) && Objects.equals(userName, scanlog.userName) && Objects.equals(scanDate, scanlog.scanDate) && Objects.equals(scanPlaza, scanlog.scanPlaza);
}
#Override
public int hashCode() {
return Objects.hash(docId, userName, scanDate, scanPlaza);
}
}
and I have a class called apiDAOImpl like this:
package com.example.demo.dao;
import com.example.demo.Scanlog;
import com.example.demo.util.Conexion;
import javax.persistence.Query;
import java.sql.Date;
import java.sql.Time;
import java.util.ArrayList;
import java.util.List;
public class apiDAOImpl implements apiDAOLocal {
Conexion conexion = new Conexion();
#Override
public List<Scanlog> listScanSummary() {
List<Scanlog> json = new ArrayList<>();
try {
conexion.abrir();
Query q = conexion.em.createQuery("SELECT s.userName, count(s) from Scanlog s where DATE(s.scanDate) = current_date group by s.userName");
json = q.getResultList();
} catch (Exception e) {
e.printStackTrace();
} finally {
conexion.cerrar();
}
return json;
}
#Override
public List<Scanlog> listScanSummaryTest() {
List<Scanlog> json = new ArrayList<>();
try {
conexion.abrir();
Query q = conexion.em.createQuery("SELECT s from Scanlog s where DATE(s.scanDate) = current_date");
json = q.getResultList();
} catch (Exception e) {
e.printStackTrace();
} finally {
conexion.cerrar();
}
return json;
}
}
When I call the function listScanSummaryTest from my controller, this function is executed
Query q = conexion.em.createQuery("SELECT s from Scanlog s where DATE(s.scanDate) = current_date");
and I get something like this:
[
{
"docId": "22R110041369",
"userName": "HLOPEZ",
"scanDate": 1647267784991,
"scanPlaza": 1
},
{
"docId": "22R110041370",
"userName": "HLOPEZ",
"scanDate": 1647267785944,
"scanPlaza": 1
}
]
But when I call the function listScanSummary from my controller, I want this query to be executed:
Query q = conexion.em.createQuery("SELECT s.userName, count(s) from Scanlog s where DATE(s.scanDate) = current_date group by s.userName");
And I get this:
[
[
"HGLOPEZ",
118
],
[
"HLOPEZ",
298
]
]
and i would like to have something like this:
[
{
"userName": "HLOPEZ",
"count": 118
},
{
"userName": "HLOPEZ",
"count": 298
}
]
this 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>1.0-SNAPSHOT</version>
<name>demo</name>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<junit.version>5.8.2</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0-PFD2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.1.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.5.Final</version>
</dependency>
<dependency>
<groupId>com.ibm.db2</groupId>
<artifactId>jcc</artifactId>
<version>11.5.7.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.13.1</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.1</version>
</plugin>
</plugins>
</build>
</project>
NOTE: i'm not using spring. Just javaee (1.8) and jpa
thanks for your help!!

As I said in my comment your query SELECT s.userName, count(s) from Scanlog s return a array of strings and in your test function you are selecting the entire object SELECT s from Scanlog s then the resutl is an array of object:
So if you want to return the expected result:
[
{
"userName": "HLOPEZ",
"count": 118
},
{
"userName": "HLOPEZ",
"count": 298
}
]
You have to create a model with userName and count attribut with a constructor which hold this fields.
Then in your query you can create an Object which took this fields.
For example :
Select new com.CustomObject(s.userName, count(s))

Related

No operations defined in spec!! and 404 error in postman. The spring boot don't show any error from my code. yet i can't establish the connection

This is a simple code that i got from youtube for practice. well i did the code correcly but i cant get the explicit mapping correclty, that what the 404 error in the postman says.
I don't know if its my Spring boot app problem or the code error. please have a look at this , Since spring boot is not giving a proper answer.
//CONTROLLER
#Slf4j
#RestController
#RequestMapping("/api/v1")
public class RestuController {
#Autowired
private RestuService restuService;
/////////////////////////////////////POST MAPPING//////////////////////////////////////////////////////////////////////
#PostMapping("/POST/save")
Restaurant addRestaurant(#RequestBody Restaurant restaurant) {
return restuService.saveRestu(restaurant);
}
#PostMapping("/POST/saves")
List<Restaurant> addRestaurants(#RequestBody List<Restaurant> restaurants) {
return restuService.saveRestaurants(restaurants);
}
#GetMapping("/GET/resturants")
List<Restaurant> findAllRestaurants(){
log.debug("reached /GET/resturants");
return restuService.getRestaurants();
}
#GetMapping("/GET/{id}")
Restaurant findRestaurantById(#PathVariable int id) {
log.debug("reached /GET/{id} :" + id);
return restuService.getRestaurantById(id);
}
#GetMapping("/GET/{name}")
Restaurant findRestaurantByName(#PathVariable String name) {
log.debug("reached /GET/{name}:" + name);
return restuService.getRestaurantByname(name);
}
#GetMapping("/GET/{dist}")
List<Restaurant> findRestaurantByDist(#PathVariable int distance) {
log.debug("reached /GET/{dist} :" + distance);
return restuService.getRestaurantbyDist(distance);
}
#GetMapping("/GET/{loc}")
List<Restaurant> findRestaurantByLocation(#PathVariable String location) {
log.debug("reached /GET/{loc} : " + location);
return restuService.getRestaurantbyLocation(location);
}
#GetMapping("/GET/{cuisine}")
List<Restaurant> findRestaurantByCuisine(#PathVariable String cuisine) {
log.debug("reached /GET/{cuisine} : " + cuisine);
return restuService.getRestaurantbyCuisine(cuisine);
}
#GetMapping("/GET/{budget}")
List<Restaurant> findRestaurantByBudget(#PathVariable int budget) {
log.debug("reached /GET/{Budget} : " + budget);
return restuService.getRestaurantbyBudget(budget);
}
}
//SERVICE
package SERVICE;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ENTITY.Restaurant;
import REPOSITORY.RestuRepository;
#Service
public class RestuService {
#Autowired
RestuRepository restuRepository;
///////////////////postmethods//////////////////////////////////////
public Restaurant saveRestu(Restaurant restaurant) {
return restuRepository.save(restaurant);
}
public List<Restaurant> saveRestaurants(List<Restaurant> restaurants) {
return restuRepository.saveAll(restaurants);
}
///////////////////////////////////////////////////////////////////////////////////////
//////////////////GET METHODS//////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////
public List<Restaurant> getRestaurants(){
return restuRepository.findAll();
}
public Restaurant getRestaurantById(int id){
return restuRepository.findById(id).orElse(null);
}
public Restaurant getRestaurantByname(String name){
return restuRepository.findByName(name);
}
public List<Restaurant> getRestaurantbyDist(int distance){
return restuRepository.findByDist(distance);
}
public List<Restaurant> getRestaurantbyLocation(String location){
return restuRepository.findByLocation(location);
}
public List<Restaurant> getRestaurantbyCuisine(String cuisine){
return restuRepository.findBycuisine(cuisine);
}
public List<Restaurant> getRestaurantbyBudget(int budget){
return restuRepository.findBybudget(budget);
}
}
//REPOSITORY
package REPOSITORY;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import ENTITY.Restaurant;
#Repository
public interface RestuRepository extends JpaRepository<Restaurant, Integer> {
Restaurant findByName(String name);
List<Restaurant> findByDist(int distance);
List<Restaurant> findByLocation(String location);
List<Restaurant> findBycuisine(String cuisine);
List<Restaurant> findBybudget(int budget);
}
//ENTITY OR MODEL CLASS
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
#Data
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name = "restaurant_tbl")
public class Restaurant {
#Id
#GeneratedValue
private int id;
private String name;
private String cuisine;
private String location;
private int distance;
private int budget;
}
//APPLICATION.PROPERTIES
server.port = 6282
spring.datasource.dbcp2.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url =jdbc:mysql://localhost:3306/restaurants
spring.datasource.username = root
spring.datasource.password = ****
spring.jpa.show-sql =true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
springdoc.api-docs.path=/api-docs
springdoc.swagger-ui.path=/swagger-ui.html
//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 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.7.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.sangamam</groupId>
<artifactId>RESTAURANT-SERVICE</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>RESTAURANT-SERVICE</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</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>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.6.4</version>
</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>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>

Error creating bean with name 'orderController'

I am studying Spring Boot and I want to create a Rest Controller, and using a sql database, but there is a problem when I start the project :
Error:
(the error text is great I will leave the link)
And code:
OrderController.java
package ***;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.Optional;
#RestController
public class OrderController {
#Autowired
private OrderRepository orderRep;
#GetMapping("/")
public List<Order> index(){
return (List<Order>) orderRep.findAll();
}
#GetMapping("/{id}")
public Order show(#PathVariable int id){
Optional<Order> orderId= orderRep.findById(id);
Order order = orderId.get();
return order;
}
#PostMapping("/search")
public List<Order> search(#RequestBody Map<String, String> body){
String searchItem = body.get("item");
return orderRep.findByTitleContainingOrContentContaining(searchItem);
}
#PostMapping("/")
public Order create(#RequestBody Map<String, String> body){
String item = body.get("item");
int price = Integer.parseInt(body.get("price"));
int quantity = Integer.parseInt(body.get("quantity"));
return orderRep.save(new Order(item, price,quantity));
}
#PutMapping("/{id}")
public Order update(#PathVariable String id, #RequestBody Map<String, String> body){
int orderId = Integer.parseInt(id);
// getting blog
Optional<Order> order = orderRep.findById(orderId);
order.get().setItem(body.get("item"));
order.get().setPrice(Integer.parseInt(body.get("price")));
order.get().setQuantity(Integer.parseInt("quantity"));
return orderRep.save(order.get());
}
#DeleteMapping("/{id}")
public boolean delete(#PathVariable int id){
//int orderId = Integer.parseInt(id);
orderRep.deleteById(id);
return true;
}
}
Order.java
package ***;
import javax.persistence.*;
#Entity
#Table(name = "orders")
public class Order {
//Fields
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column(name = "item")
private String item;
#Column(name = "price")
private int price;
#Column(name = "quantity")
private int quantity;
//Constructors
public Order() { }
public Order(String item, int price, int quantity) {
this.setItem(item);
this.setPrice(price);
this.setQuantity(quantity);
}
public Order(int id, String item, int price, int quantity) {
this.setId(id);
this.setItem(item);
this.setPrice(price);
this.setQuantity(quantity);
}
//Object to string data
#Override
public String toString() {
return "Order{" +
"id=" + getId() +
", item='" + getItem() + '\'' +
", price='" + getPrice() + '\'' +
", price='" + getQuantity() + '\'' +
'}';
}
//Getters & Setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
OrderRepository.java
package ***;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public interface OrderRepository extends CrudRepository<Order, Integer> {
// custom query to search to blog post by title or content
List<Order> findByTitleContainingOrContentContaining(String item);
}
application.properties
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/testvoy?useUnicode=true&serverTimezone=UTC&useSSL=true&verifyServerCertificate=false
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name =com.mysql.jdbc.Driver
#spring.jpa.show-sql: true
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 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.5.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.test</groupId>
<artifactId>project</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>project</name>
<description>project</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<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-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-mockmvc</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<version>1.5.8</version>
<executions>
<execution>
<id>generate-docs</id>
<phase>prepare-package</phase>
<goals>
<goal>process-asciidoc</goal>
</goals>
<configuration>
<backend>html</backend>
<doctype>book</doctype>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-asciidoctor</artifactId>
<version>${spring-restdocs.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
I would be grateful for any help, thanks in advance
If you check the error, you can see that it comes from there:
List<Order> findByTitleContainingOrContentContaining(String item);
and if you read more closely to the error, you will see:
No property title found for type Order!;
inside here:
Caused by: org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.util.List com.test.project.OrderRepository.findByTitleContainingOrContentContaining(java.lang.String)! Reason: Failed to create query for method public abstract java.util.List com.test.project.OrderRepository.findByTitleContainingOrContentContaining(java.lang.String)! No property title found for type Order!; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List com.test.project.OrderRepository.findByTitleContainingOrContentContaining(java.lang.String)! No property title found for type Order!
Infact, if you check your model, there is no title property

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.

q classes are not generated in querydsl

I am developping a java/jee application using spring boot as framework and i want to filter entity application,so i tried to use querydsl and now i am trying to generate Q classes of querydsl.But when i make mvn install Q classes are not generated.i am using eclipse neon as ide and and java home is configured to JDK 8.
I am using jpa 2 and hibernate 5.
This is my code:
package biz.picosoft.entities;
import java.io.Serializable;
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.OrderColumn;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name = "application",uniqueConstraints = {#UniqueConstraint(columnNames = "reference")})
public class Application implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
#Column(name = "reference")
private String reference;
#Column(name = "creationDate")
private Date creationDate;
#Column(name = "status")
private String status;
#Column(name = "deadLine")
private Date deadLine;
#Column(name = "appType")
private String appType;
#Column(name = "projectId")
private Long projectId;
#OrderColumn(name = "listePiecesJointes")
private String[] listePiecesJointes;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Date getDeadLine() {
return deadLine;
}
public void setDeadLine(Date deadLine) {
this.deadLine = deadLine;
}
public String getAppType() {
return appType;
}
public void setAppType(String appType) {
this.appType = appType;
}
public Application() {
super();
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public Long getProjectId() {
return projectId;
}
public void setProjectId(Long projectId) {
this.projectId = projectId;
}
public String[] getListePiecesJointes() {
return listePiecesJointes;
}
public void setListePiecesJointes(String[] listePiecesJointes) {
this.listePiecesJointes = listePiecesJointes;
}
public Application(String reference, Date creationDate, String status, Date deadLine, String appType,String[] listePiecesJointes,Long projectId) {
super();
this.reference = reference;
this.creationDate = creationDate;
this.status = status;
this.deadLine = deadLine;
this.appType = appType;
this.projectId=projectId;
this.listePiecesJointes=listePiecesJointes;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((appType == null) ? 0 : appType.hashCode());
result = prime * result + ((creationDate == null) ? 0 : creationDate.hashCode());
result = prime * result + ((deadLine == null) ? 0 : deadLine.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((projectId == null) ? 0 : projectId.hashCode());
result = prime * result + ((reference == null) ? 0 : reference.hashCode());
result = prime * result + ((status == null) ? 0 : status.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Application other = (Application) obj;
if (appType == null) {
if (other.appType != null)
return false;
} else if (!appType.equals(other.appType))
return false;
if (creationDate == null) {
if (other.creationDate != null)
return false;
} else if (!creationDate.equals(other.creationDate))
return false;
if (deadLine == null) {
if (other.deadLine != null)
return false;
} else if (!deadLine.equals(other.deadLine))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (projectId == null) {
if (other.projectId != null)
return false;
} else if (!projectId.equals(other.projectId))
return false;
if (reference == null) {
if (other.reference != null)
return false;
} else if (!reference.equals(other.reference))
return false;
if (status == null) {
if (other.status != null)
return false;
} else if (!status.equals(other.status))
return false;
return true;
}
#Override
public String toString() {
return "Application [id=" + id + ", reference=" + reference + ", creationDate=" + creationDate + ", status="
+ status + ", deadLine=" + deadLine + ", appType=" + appType + ", projectId=" + projectId + "]";
}
}
this is my maven file
<?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>biz.picosoft</groupId>
<artifactId>gestionprojetback</artifactId>
<version>0.0.1</version>
<packaging>war</packaging>
<name>gestionprojetback</name>
<description>gestion de projet</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<start-class>biz.picosoft.ApplictationBoot</start-class>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<org.mysqlconnector-version>5.1.6</org.mysqlconnector-version>
<querydsl.version>4.1.4</querydsl.version>
<apt-maven-plugin.version>1.1.3</apt-maven-plugin.version>
</properties>
<dependencies>
<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-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${org.mysqlconnector-version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-test -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<version>4.0.0.RELEASE</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180130</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.5</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/com.mysema.querydsl/querydsl-apt -->
<!-- https://mvnrepository.com/artifact/com.mysema.querydsl/querydsl-apt -->
<!-- https://mvnrepository.com/artifact/com.querydsl/querydsl-apt -->
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>4.1.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
<version>4.1.4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>com.mysema.maven</groupId>
<artifactId>apt-maven-plugin</artifactId>
<version>1.1.3</version>
<executions>
<execution>
<goals>
<goal>process</goal>
</goals>
<configuration>
<outputDirectory>target/generated-sources</outputDirectory>
<processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
Your configuration seems right.
Try this from Querydsl's documentation
If you use Eclipse, run mvn eclipse:eclipse to update your Eclipse project to include target/generated-sources/java as a source folder.
Now you are able to construct JPA query instances and instances of the query domain model.
You may also try Patrick's solution.

Java Spring Data Hibernate Search Engine

error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'searchController' method
public java.lang.String softuniBlog.controller.SearchController.search(java.lang.String,org.springframework.ui.Model)
to {[/search]}: There is already 'searchController' bean method
public java.lang.String softuniBlog.controller.SearchController.index() mapped.
**I`m trying to build search engine for my blog and have 3 questions.
1) Why In application properties last 3 rows are "can not resolve"
2) How can I fix the error I have, app is working but when try url /search?q=someText it trows exception:
[Handler dispatch failed; nested exception is java.lang.NoSuchMethodError: org.hibernate.engine.spi.SessionDelegatorBaseImpl.(Lorg/hibernate/engine/spi/SessionImplementor;)V] with root cause
java.lang.NoSuchMethodError: org.hibernate.engine.spi.SessionDelegatorBaseImpl.(Lorg/hibernate/engine/spi/SessionImplementor;)V
3) How can take search query from input form instead from url
please check the code:
search input box
<div id="wrap">
<form action="" autocomplete="on">
<input id="search" name="search" type="text" placeholder="What're we looking for ?"></input>
<input id="search_submit" value="Rechercher" type="submit"></input>
</form>
</div>
Article controller
package softuniBlog.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import softuniBlog.bindingModel.ArticleBindingModel;
import softuniBlog.entity.Article;
import softuniBlog.entity.User;
import softuniBlog.repository.ArticleRepository;
import softuniBlog.repository.UserRepository;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
#Controller
public class ArticleConstroller {
#Autowired
private ArticleRepository articleRepository;
#Autowired
private UserRepository userRepository;
#GetMapping("/article/create")
#PreAuthorize("isAuthenticated()")
public String create(Model model){
model.addAttribute("view", "/article/create");
return "base-layout";
}
#PostMapping("/article/create")
#PreAuthorize("isAuthenticated()")
public String createProcess(ArticleBindingModel articleBindingModel){
UserDetails user = (UserDetails) SecurityContextHolder
.getContext()
.getAuthentication()
.getPrincipal();
User userEntity = this.userRepository.findByEmail(user.getUsername());
String databasePathImage = null;
String[] allowedContentTypes = {
"image/png",
"image/jpg",
"image/jpeg"
};
boolean isContentTypeAllowed =
Arrays.asList(allowedContentTypes)
.contains(articleBindingModel.getImage().getContentType());
if(isContentTypeAllowed){
String imagesPath = "\\src\\main\\resources\\static\\img\\";
String imagePathRoot = System.getProperty("user.dir");
String imageSaveDirectory = imagePathRoot + imagesPath;
String fileName = articleBindingModel.getImage().getOriginalFilename();
String savePath = imageSaveDirectory + fileName;
File imageFile = new File(savePath);
try {
articleBindingModel.getImage().transferTo(imageFile);
databasePathImage = "/img/" + fileName;
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
Article articleEntity = new Article(
articleBindingModel.getTitle(),
articleBindingModel.getContent(),
userEntity,
databasePathImage
);
this.articleRepository.saveAndFlush(articleEntity);
return "redirect:/";
}
#GetMapping("/article/edit/{id}")
#PreAuthorize("isAuthenticated()")
public String edit(#PathVariable Integer id, Model model){
if(!this.articleRepository.exists(id)){
return "redirect:/";
}
Article article = this.articleRepository.findOne(id);
if(!this.isUserAuthorOrAdmin(article)){
return "redirect:/";
}
model.addAttribute("view", "article/edit");
model.addAttribute("article", article);
return "base-layout";
}
#GetMapping("/article/{id}")
public String details(Model model, #PathVariable Integer id) {
if(!this.articleRepository.exists(id)){
return "redirect:/";
}
if(!(SecurityContextHolder.getContext().getAuthentication()
instanceof AnonymousAuthenticationToken)){
UserDetails principal = (UserDetails) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal();
User entityUser = this.userRepository.findByEmail(principal.getUsername());
model.addAttribute("user", entityUser);
}
Article article = this.articleRepository.findOne(id);
model.addAttribute("view", "article/details");
model.addAttribute("article", article);
return "base-layout";
}
#PostMapping("/article/edit/{id}")
#PreAuthorize("isAuthenticated()")
public String editProcess(#PathVariable Integer id, ArticleBindingModel articleBindingModel) {
if(!this.articleRepository.exists(id)){
return "redirect:/";
}
Article article = this.articleRepository.findOne(id);
if(!this.isUserAuthorOrAdmin(article)){
return "redirect:/";
}
article.setTitle(articleBindingModel.getTitle());
article.setContent(articleBindingModel.getContent());
this.articleRepository.saveAndFlush(article);
return "redirect:/article/" + article.getId();
}
#GetMapping("/article/delete/{id}")
#PreAuthorize("isAuthenticated()")
public String delete(#PathVariable Integer id, Model model){
if(!this.articleRepository.exists(id)){
return "redirect:/";
}
Article article = this.articleRepository.findOne(id);
if(!this.isUserAuthorOrAdmin(article)){
return "redirect:/";
}
model.addAttribute("article", article);
model.addAttribute("view", "article/delete");
return "base-layout";
}
#PostMapping("/article/delete/{id}")
#PreAuthorize("isAuthenticated()")
public String deleteProcess(#PathVariable Integer id) {
if(!this.articleRepository.exists(id)){
return "redirect:/";
}
Article article = this.articleRepository.findOne(id);
if(!this.isUserAuthorOrAdmin(article)){
return "redirect:/";
}
this.articleRepository.delete(article);
return "redirect:/";
}
private boolean isUserAuthorOrAdmin(Article article){
UserDetails user = (UserDetails) SecurityContextHolder
.getContext()
.getAuthentication()
.getPrincipal();
User userEntity = this.userRepository.findByEmail(user.getUsername());
return userEntity.isAdmin() || userEntity.isAuthor(article);
}
}
Article model
import javax.validation.constraints.NotNull;
import javax.persistence.*;
import java.util.Date;
#Entity
#Indexed
#Table(name = "articles")
public class Article {
private Integer id;
#Field(index = Index.YES, analyze = Analyze.YES, store = Store.NO)
#NotNull
private String title;
#Field(index = Index.YES, analyze = Analyze.YES, store = Store.NO)
#NotNull
private String content;
private Date date;
private User author;
private String imagePath;
public Article(String title, String content, User author, String imagePath) {
this.title = title;
this.content = content;
this.author = author;
this.imagePath = imagePath;
this.date = new Date();
}
public Article(){
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "title", nullable = false)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Column(name = "content", nullable = false, columnDefinition = "text")
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
#Column(name = "date", nullable = true)
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
#ManyToOne()
#JoinColumn(nullable = false, name = "authorId")
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
#Transient
public String getSummary(){
return this.getContent().substring(0, this.getContent().length()/2) + "...";
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
}
Application properties
# Database connection with the given database name
spring.datasource.url = jdbc:mysql://localhost:3306/javablog
# Username and password
spring.datasource.username = root
spring.datasource.password =
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update): with "update" the database
# schema will be automatically updated accordingly to java entities found in
# the project
# Using "create" will delete and recreate the tables every time the project is started
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
spring.jpa.hibernate.naming.strategy = org.hibernate.cfg.ImprovedNamingStrategy
# Allows Hibernate to generate SQL optimized for a particular DBMS
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.properties.hibernate.search.default.directory_provider = filesystem
# Using the filesystem DirectoryProvider you also have to specify the default
# base directory for all indexes (make sure that the application have write
# permissions on such directory)
spring.jpa.properties.hibernate.search.default.indexBase = ../java/softuniBlog/lucene/indexes
#Turn off Thymeleaf cache
spring.thymeleaf.cache = false
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>softuni.blog</groupId>
<artifactId>blog</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Blog</name>
<description>Blog Project from the Software Technologies Course</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.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-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>2.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-orm</artifactId>
<version>5.7.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-infinispan</artifactId>
<version>5.7.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-elasticsearch</artifactId>
<version>5.7.0.Final</version>
</dependency>
<dependency>
<groupId>org.infinispan</groupId>
<artifactId>infinispan-directory-provider</artifactId>
<version>8.2.4.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.0.Alpha2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>`enter code here`
</project>
I honestly don't understand you other questions (and you probably should ask them separately), but for question 2 I can tell you that a NoSuchMethodError is very likely to be caused by your using an incompatible version of Hibernate ORM with Hibernate Search.
To sum up:
Hibernate Search 5.7.0 and later should be used with Hibernate ORM 5.2.3 or later.
Hibernate Search 5.6.x and earlier should be used with Hibernate ORM 5.1.x or earlier.
EDIT: Your pom appears to contain a dependency to hibernate-entitymanager, and you didn't set the version for this dependency, so I suspect you're getting some older version. hibernate-entitymanager isn't required to use JPA starting with Hibernate ORM 5.2, so you should try to remove it.

Categories

Resources