I have checked many other questions about it but I cannot find the solution, where am I missing ?
Here is the controller method:
package com.nishberkay.nishcustomer.controller;
import com.nishberkay.nishcustomer.dto.request.CustomerAddRequestDto;
import com.nishberkay.nishcustomer.dto.request.CustomerUpdateRequestDto;
import com.nishberkay.nishcustomer.dto.response.CustomerDto;
import com.nishberkay.nishcustomer.entity.mysqlentity.Customer;
import com.nishberkay.nishcustomer.exception.InvalidRequestException;
import com.nishberkay.nishcustomer.service.CustomerService;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
#RestController
#RequestMapping("/customer")
#Validated
public class CustomerController {
private CustomerService customerService;
private ModelMapper modelMapper;
#Autowired
public CustomerController(CustomerService customerService, ModelMapper modelMapper) {
this.customerService = customerService;
this.modelMapper = modelMapper;
}
#PutMapping
public CustomerDto updateCustomer(#Valid #RequestBody CustomerUpdateRequestDto customerDto,
BindingResult bindingResult) throws Exception {
if (bindingResult.hasErrors()) {
String errorMessage = bindingResult.getAllErrors().get(0).getDefaultMessage();
throw new InvalidRequestException(errorMessage);
}
Customer customer = modelMapper.map(customerDto, Customer.class);
return modelMapper.map(customerService.update(customer), CustomerDto.class);
}
}
And my dto is:
import javax.validation.constraints.NotNull;
#Data
public class CustomerUpdateRequestDto {
#NotNull
private int id;
#NotNull
private String firstName;
#NotNull
private String lastName;
}
My problem is (maybe #Valid is actually working I am not sure), when I debug it with the postman request:
{
"firstName" : "berkayaaasd",
"lastName" : "dada"
}
I am expecting some kind of message like "Id cannot be null" but id field is coming as 0 so thats why I think maybe #Valid is working but something else is wrong.
And here is the pom dependencies:
<dependencies>
<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.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</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-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.3.8</version>
</dependency>
</dependencies>
The issue here is that you defined your id as a primitive type, which can never be null.
If you chose a boxed type (Integer in this case) this should work.
So in your DTO:
import javax.validation.constraints.NotNull;
#Data
public class CustomerUpdateRequestDto {
#NotNull
private Integer id;
...
}
Related
I am getting the below error even though such a bean does exist and *is in the same package as the Application and Controller
Field profilesRepository in com.test.ProfilesController required a bean of type 'com.test.ProfilesRepository' that could not be found.
What could be causing this?
My file structure:
src
main
java
com.test
TestApplication.java (class)
Profiles (class)
ProfilesController (class)
ProfilesRepository (interface)
Profiles.java:
package com.test;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "Profiles")
public class Profiles {
#Id
#Column(name = "ID")
public int id;
#Column(name = "Username")
public String username;
#Column(name = "Name")
public String name;
#Column(name = "EmailAddress")
public String emailAddress;
#Column(name = "HomeAddress")
public String homeAddress;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getHomeAddress() {
return homeAddress;
}
public void setHomeAddress(String homeAddress) {
this.homeAddress = homeAddress;
}
}
ProfilesController.java:
package com.test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#RestController
public class ProfilesController {
#Autowired
public ProfilesRepository profilesRepository;
#GetMapping("/getAllProfiles")
public List<Profiles> getAllProfiles() {
return profilesRepository.findAll();
}
#GetMapping("/helloWorld")
public String helloWorld(){
return "Hello World!";
}
}
ProfilesRepository.java:
package com.test;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public interface ProfilesRepository extends CrudRepository<Profiles, Integer> {
List<Profiles> findAll();
}
TestApplication.java:
package com.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication(scanBasePackages = {"com.test"})
#EnableJpaRepositories(basePackages = {"com.test"})
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.Test</groupId>
<version>0.0.1-SNAPSHOT</version>
<name>test</name>
<properties>
<java.version>19</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-data-rest</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>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
The error:
Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
2023-02-15T21:21:47.035-05:00 ERROR 32878 --- \[ restartedMain\] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field profilesRepository in com.test.ProfilesController required a bean of type 'com.test.ProfilesRepository' that could not be found.
The injection point has the following annotations:
\- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.Group3.GeekText.ProfilesRepository' in your configuration.
I fixed this by updating my imports from
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
to
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
During the walkthrough I have added the specified model, controller and repo. I have added all the required dependencies through spring boot (I beleive) as well as creating the DB through the MySql shell.
The db is the same as the example as well as the basic root user until I can get this to work then will add another user.
Any help would be appreciated as I have had this same issue every single time I have tried to set up a db.
My model
package com.avorion.dndwiki.Model;
import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id;
#Entity // This tells Hibernate to make a table out of this class public class User {
#Id
#GeneratedValue(strategy=GenerationType.AUTO) private Integer id;
private String name;
private String email;
public Integer getId() { return id;
}
public void setId(Integer id) { this.id = id;
}
public String getName() { return name;
}
public void setName(String name) { this.name = name;
}
public String getEmail() { return email;
}
public void setEmail(String email) { this.email = email;
} }
My Controller
package com.avorion.dndwiki.Controller;
import com.avorion.dndwiki.Model.User; import com.avorion.dndwiki.Repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody;
#Controller // This means that this class is a Controller #RequestMapping(path="/demo") // This means URL's start with /demo (after Application path) public class MainController {
#Autowired // This means to get the bean called userRepository Which is auto-generated by Spring, we will use it to handle the data private UserRepository userRepository;
#PostMapping(path="/add") // Map ONLY POST Requests public #ResponseBody String addNewUser (#RequestParam String name
, #RequestParam String email) {
// #ResponseBody means the returned String is the response, not a view name
// #RequestParam means it is a parameter from the GET or POST request
User n = new User(); n.setName(name); n.setEmail(email); userRepository.save(n); return "Saved";
}
#GetMapping(path="/all") public #ResponseBody Iterable<User> getAllUsers() { This returns a JSON or XML with the users return userRepository.findAll();
} }
My Repo
package com.avorion.dndwiki.Repository;
import com.avorion.dndwiki.Model.User; import org.springframework.data.repository.CrudRepository;
//This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository CRUD refers Create, Read, Update, Delete
public interface UserRepository extends CrudRepository<User, Integer> {
}
My application properties
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example
spring.datasource.username=root#localhost
spring.datasource.password=thisIsntMyActualPassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#spring.jpa.show-sql: true
My Pom(Theres a lot here,im just practicing)
<?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>3.0.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.Avorion</groupId>
<artifactId>DnDWiki</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>DnDWiki</name>
<description>DnDWiki</description>
<properties>
<java.version>17</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-data-rest</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-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka-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>
I have tried to set up a number of db with diffrent users and naming conventions. I have reset MySql as well as asking other software engineers.
I am new to Spring Boot and working on database connectivity. All the related classes are here only main class having run method is not posted.
It is giving me the error of no converter found for ArrayList.
Please help me if I am doing anything wrong.
//Customer.java
package springbootfirstapp.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="id")
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(int id, String name, String phone) {
super();
this.id = id;
this.name = name;
this.phone = phone;
}
public Customer() {
super();
}
}
//CustomerController.java
package springbootfirstapp.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import springbootfirstapp.domain.Customer;
import springbootfirstapp.repo.CustomerRepo;
#RestController
#RequestMapping("/customer")
public class CustomerController {
#Autowired
CustomerRepo rp;
#RequestMapping("/findall")
#ResponseBody
public List<Customer> findall()
{
return rp.findAll();
}
}
//CustomerRepo.java
package springbootfirstapp.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import springbootfirstapp.domain.Customer;
public interface CustomerRepo extends JpaRepository<Customer, Integer> {
}
//pom.xml
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>SpringBootFirstApp</groupId>
<artifactId>springbootfirstapp</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.5.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEndoing>UTF- 8</project.reporting.outputEndoing>
<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>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
STACKTRACE:
Generic Guidelines for such an error is to check for :
No Args Constructor
Getters & Setters
Jackson dependencies
Since first two aren't a problem, Please try adding the below two dependencies and let us know if its working.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.3</version>
</dependency>
Add this dependency in pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.1</version>
</dependency>
If I correctly understand your question, you need to add jackson mapper in pom.
Can you try that once and see your converter issue is resolved.
Thankyou everyone for the help...
Issue is resolved by adding Jackson Mapper dependency
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.5.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.5.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jaxb-annotations</artifactId>
<version>2.5.2</version>
</dependency>
I use spring-data-solr (2.1.3) and solr (6.5.1), but when I use solrTemplate.saveBean(Command), an exception is thrown:
java.lang.NoSuchMethodError: org.apache.solr.common.SolrInputDocument: method ()V not found
This is my pom.xml
<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>com.catcher92.demo</groupId>
<artifactId>solr</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>${artifactId}</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<maven.compiler.plugin.version>2.3.2</maven.compiler.plugin.version>
<solr.version>6.5.1</solr.version>
<spring.data.solr.version>2.1.3.RELEASE</spring.data.solr.version>
<fastjson.version>1.2.32</fastjson.version>
<junit.version>4.12</junit.version>
<spring.version>4.3.8.RELEASE</spring.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-solrj</artifactId>
<version>${solr.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-solr</artifactId>
<version>${spring.data.solr.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-solrj</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-solr</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven.compiler.plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
This is my entity
package com.catcher92.demo.solr.bean;
import org.apache.solr.client.solrj.beans.Field;
import java.io.Serializable;
import java.util.List;
/**
* Created by catcher92 on 2017/6/7.
*/
public class Command implements Serializable{
#Field
private String id;
#Field
private String command;
#Field
private String description;
#Field
private List<String> contents;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<String> getContents() {
return contents;
}
public void setContents(List<String> contents) {
this.contents = contents;
}
#Override
public String toString() {
return "Command{" +
"id=" + id +
", command='" + command + '\'' +
", description='" + description + '\'' +
", contents=" + contents +
'}';
}
}
This is my solr config
package com.catcher92.demo.solr.spring.config;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.solr.core.SolrTemplate;
import org.springframework.data.solr.repository.config.EnableSolrRepositories;
import javax.annotation.Resource;
/**
* Created by catcher92 on 2017/6/7.
*/
#Configuration
#EnableSolrRepositories()
#PropertySource("classpath:solr.properties")
public class SolrConfig {
static final String SOLR_HOST = "solr.host";
#Resource
private Environment environment;
#Bean
public HttpSolrClient solrClient() {
String solrHost = environment.getRequiredProperty(SOLR_HOST);
return new HttpSolrClient.Builder(solrHost).build();
}
#Bean
public SolrTemplate solrTemplate() {
return new SolrTemplate(solrClient());
}
}
This is my test code
package com.catcher92.demo;
import com.catcher92.demo.solr.bean.Command;
import com.catcher92.demo.solr.spring.config.SpringConfig;
import org.apache.solr.common.SolrInputDocument;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.solr.core.SolrTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Arrays;
/**
* Created by catcher92 on 2017/6/7.
*/
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {SpringConfig.class})
public class SpringDataSolrTest {
#Autowired
private SolrTemplate solrTemplate;
#Test
public void testAdd() {
Command command = new Command();
command.setId("110");
command.setCommand("template测试精彩");
command.setDescription("spring data solr template测试精彩描述");
command.setContents(Arrays.asList("测试精彩1", "2精彩测试"));
solrTemplate.saveBean(command);
solrTemplate.commit();
}
#Test
public void testDel() {
solrTemplate.deleteById("110");
solrTemplate.commit();
}
}
When I test the method testAdd() the error message like this:
java.lang.NoSuchMethodError: org.apache.solr.common.SolrInputDocument: method <init>()V not found
at org.springframework.data.solr.core.SolrTemplate.convertBeanToSolrInputDocument(SolrTemplate.java:1131)
at org.springframework.data.solr.core.SolrTemplate$4.doInSolr(SolrTemplate.java:335)
at org.springframework.data.solr.core.SolrTemplate$4.doInSolr(SolrTemplate.java:330)
at org.springframework.data.solr.core.SolrTemplate.execute(SolrTemplate.java:220)
at org.springframework.data.solr.core.SolrTemplate.saveBean(SolrTemplate.java:330)
at org.springframework.data.solr.core.SolrTemplate.saveBean(SolrTemplate.java:318)
at org.springframework.data.solr.core.SolrTemplate.saveBean(SolrTemplate.java:300)
at com.catcher92.demo.SpringDataSolrTest.testAdd(SpringDataSolrTest.java:39)
spring-data-solr and solr-solrj have such a compatibility table:
spring-data-solr | solr-solrj
-----------------------------
2.1.15 | 5.5.0
3.0.10 | 6.5.0
4.0.0 | 7.4.0
So one must use corresponding versions of both jars.
for example with maven:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-solr</artifactId>
<version>4.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-solrj</artifactId>
<version>7.4.0</version>
</dependency>
I faced the same issue. It is because in Sorj 6.x default constructor without parameters of SolrInputDocument() was removed. In my case I used a workaround: converting my entity to SolrInputDocument and then calling saveBean() method.
I've searched everywhere but I didn't found a good answer.
I am developping a maven application using Hibernate + Spring + Mysql.
Here is my application-context.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http:...">
<bean id='dataSource' class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost/university"/>
<property name="username" value="root"/>
<property name="password" value="admin"/>
</bean>
<bean id='sessionFactory' class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="annotatedClasses">
<list>
<value>com.university.entities.Course</value>
<value>com.university.entities.Student</value>
<value>com.university.entities.Teacher</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
</props>
</property>
</bean>
<bean id='transactionManager' class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref='sessionFactory'/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<context:annotation-config/>
<context:component-scan base-package="com.university.dao"></context:component-scan>
</beans>
and Here is my pom.xml :
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>3.2.4.RELEASE</spring.version>
<hibernate.version>3.6.7.Final</hibernate.version>
<jsf.version>2.2.4</jsf.version>
<slf4j.version>1.7.1</slf4j.version>
<primefaces.version>4.0</primefaces.version>
</properties>
<dependencies>
<!-- Tests unitaires avec junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<!-- antlr -->
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr</artifactId>
<version>3.5.1</version>
</dependency>
<!-- Package entities -->
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0-rev-1</version>
<scope>provided</scope>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
<scope>runtime</scope>
</dependency>
<!-- JSF dependencies -->
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>${jsf.version}</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>${jsf.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Primefaces dependency -->
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>${primefaces.version}</version>
</dependency>
<!-- slf4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- commons -->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.5.4</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.8.3</version>
</dependency>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
</dependency>
<!-- javassist -->
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit47</artifactId>
<version>2.16</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
But when I try to test a simple DAO as :
package com.university.dao.test;
import java.util.List;
import junit.framework.TestCase;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.university.dao.StudentDAO;
import com.university.entities.Student;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:application-context.xml" })
public class StudentDAOTest extends TestCase {
private static Log LOG = LogFactory.getLog(StudentDAOTest.class);
#Autowired
private StudentDAO studentDAO;
#Test
public void testFindAll() {
List<Student> listStudent = studentDAO.findAll();
LOG.debug(listStudent);
assertNotNull(listStudent);
}
#Test
public void testCreateOrUpdate() {
Student newStudent = new Student("Abderrahmen ISSA", "07701607");
studentDAO.createOrUpdate(newStudent);
assertNotNull(newStudent.getId());
}
#Test
public void testFindById() {
Integer id = 2;
Student student = studentDAO.findById(id);
assertNotNull(student);
}
#Test
public void testRemove() {
Student userToRemove = new Student("User To Test Remove", "11111111");
studentDAO.createOrUpdate(userToRemove);
Integer id = userToRemove.getId();
studentDAO.remove(userToRemove);
Student student = studentDAO.findById(id);
assertNull(student);
}
}
The Student class is :
package com.university.entities;
// Generated 20 oct. 2013 20:53:03 by Hibernate Tools 3.4.0.CR1
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* Student generated by hbm2java
*/
#Entity
#Table(name = "student", catalog = "university")
public class Student implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private String mail;
private Date birthDate;
private String birthPlace;
private String cin;
private Integer mobile;
private Set<Course> courses = new HashSet<Course>(0);
public Student() {
}
public Student(String mail, String cin) {
this.mail = mail;
this.cin = cin;
}
public Student(String name, String mail, Date birthDate, String birthPlace,
String cin, Integer mobile, Set<Course> courses) {
this.name = name;
this.mail = mail;
this.birthDate = birthDate;
this.birthPlace = birthPlace;
this.cin = cin;
this.mobile = mobile;
this.courses = courses;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "name", length = 45)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "mail", nullable = false, length = 45)
public String getMail() {
return this.mail;
}
public void setMail(String mail) {
this.mail = mail;
}
#Temporal(TemporalType.DATE)
#Column(name = "birthDate", length = 10)
public Date getBirthDate() {
return this.birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
#Column(name = "birthPlace", length = 45)
public String getBirthPlace() {
return this.birthPlace;
}
public void setBirthPlace(String birthPlace) {
this.birthPlace = birthPlace;
}
#Column(name = "cin", nullable = false, length = 45)
public String getCin() {
return this.cin;
}
public void setCin(String cin) {
this.cin = cin;
}
#Column(name = "mobile")
public Integer getMobile() {
return this.mobile;
}
public void setMobile(Integer mobile) {
this.mobile = mobile;
}
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(name = "course_has_student", catalog = "university", joinColumns = { #JoinColumn(name = "Student_id", nullable = false, updatable = false) }, inverseJoinColumns = { #JoinColumn(name = "Course_id", nullable = false, updatable = false) })
public Set<Course> getCourses() {
return this.courses;
}
public void setCourses(Set<Course> courses) {
this.courses = courses;
}
#Override
public String toString() {
return "Student [name=" + name + ", mail=" + mail + ", cin=" + cin
+ "]";
}
}
The StudentDAOImpl :
package com.university.dao.impl;
import org.springframework.stereotype.Repository;
import com.university.dao.StudentDAO;
import com.university.entities.Student;
#Repository("studentDAO")
public class StudentDAOImpl extends GenericDAOImpl<Student> implements
StudentDAO {
}
The GenericDAOImpl :
package com.university.dao.impl;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.university.dao.GenericDAO;
#Transactional
public abstract class GenericDAOImpl<T> implements GenericDAO<T> {
#Autowired
protected SessionFactory sessionFactory;
/**
* Unit.
*/
private final Class<T> entityBeanType;
/**
* Instantiates a new GenericServiceImpl.
*/
#SuppressWarnings("unchecked")
public GenericDAOImpl() {
this.entityBeanType = (Class<T>) ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
protected final Session getCurrentSession() {
if (sessionFactory == null) {
throw new IllegalStateException(
"Session Factory has not been set on DAO before usage");
}
return sessionFactory.getCurrentSession();
}
/**
* Gets the entity bean type.
*
* #return the entity bean type
*/
public final Class<T> getEntityBeanType() {
return entityBeanType;
}
public void createOrUpdate(T entity) {
getCurrentSession().saveOrUpdate(entity);
}
#SuppressWarnings("unchecked")
public List<T> findAll() {
return getCurrentSession().createQuery(
"from " + getEntityBeanType().getName()).list();
}
#SuppressWarnings("unchecked")
public T findById(Integer id) {
T entity = (T) getCurrentSession().get(getEntityBeanType(), id);
return entity;
}
public void remove(T entity) {
getCurrentSession().delete(entity);
}
}
I can run the DAOTest on eclipse well but with mvn test I get :
org.springframework.beans.factory.BeanCreationEception : Error
creating bean with name 'sessionFactory' defined in class path
resource [application-context.xml] : Invocation of init method failed;
nested exception is java.lang.NoSuchMethodError :
javax.persistence.OneToMany.orphanRemoval<>Z.
Help please !
You have a library conflict. Have you set this up as Hibernate project in Eclipse so that Eclipse added necessary JARs to the classpath? This would explain why it works in Eclipse but not in the Maven build.
Anyway, ensure the Hibernate library versions match e.g 4.1.8.Final and remove the javax.persistence-api dependency.
This all you should need in your POM regarding Hibernate. Everything else will be resolved transitively by Maven.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>