public class Post {
#Column(name="tags")
private String[] tags;
.
.
.
}
Post.Java
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1206-jdbc42</version>
<scope>runtime</scope>
</dependency>
POM.XML
#GetMapping("/posts")
public List<Post> getAllPosts() {
return postRepository.findAll();
}
Controller
#Repository
public interface PostRepository extends JpaRepository<Post, Long> {
}
Repository
spring.datasource.url= jdbc:postgresql://localhost:5432/arya2?useSSL=false
spring.datasource.username=****
spring.datasource.password=***
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults = false
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL9Dialect
Calling Rest Get Request, http://localhost:8081/posts
NOT SHOWING and this error
There was an unexpected error (type=Internal Server Error, status=500).
could not deserialize; nested exception is org.hibernate.type.SerializationException: could not deserialize
and
java.sql.SQLFeatureNotSupportedException: Method org.postgresql.jdbc42.Jdbc42Connection.createClob() is not yet implemented.
Related
Recently I was learning r2dbc and encountered a problem.
In order to test transactions in r2dbc, I wrote a small test project.
sample code github
You can see the correct code on the master branch and the wrong code on the zd/transactional-test branch
First of all, we have a mysql table like this:
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
`username` varchar(64) COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'username',
`password` varchar(32) COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'password',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT 'crete time',
PRIMARY KEY (`id`),
UNIQUE KEY `idx_username` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
When the code is as follows, the annotation #Transactionl works well
1.pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>webflux-transactional</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>14</maven.compiler.source>
<maven.compiler.target>14</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
<version>2.4.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-r2dbc</artifactId>
<version>2.4.4</version>
</dependency>
<dependency>
<groupId>io.r2dbc</groupId>
<artifactId>r2dbc-pool</artifactId>
<version>0.8.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.5</version>
</dependency>
<dependency>
<groupId>com.github.jasync-sql</groupId>
<artifactId>jasync-r2dbc-mysql</artifactId>
<version>1.1.6</version>
<exclusions>
<exclusion>
<groupId>io.netty</groupId>
<artifactId>netty-transport</artifactId>
</exclusion>
<exclusion>
<groupId>io.netty</groupId>
<artifactId>netty-handler</artifactId>
</exclusion>
<exclusion>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--test-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.4.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
<version>3.4.4</version>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<version>3.4.4</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
application.yaml
spring:
r2dbc:
url: r2dbc:pool:mysql://127.0.0.1:3306/webflux-r2dbc # r2dbc:mysql://127.0.0.1:3306/demo
username: root
password: 123456
pool:
initial-size: 5
max-size: 500
max-idle-time: 30m
validation-query: SELECT 1
server:
port: 8081
DemoApplication
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
entity class
#Table(value = "users")
public class User {
#Id
private Integer id;
private String username;
private String password;
//omit getter setter
}
UserRepository:
public interface UserRepository extends ReactiveCrudRepository<User, Integer> {
}
UserService
#Service
public class UserService {
private final static Logger LOGGER = LoggerFactory.getLogger(UserService.class);
#Resource
R2dbcEntityTemplate r2dbcEntityTemplate;
#Transactional(rollbackFor = Exception.class)
public Mono<Integer> add1(User queryUser) {
return this.r2dbcEntityTemplate.insert(User.class)
.using(queryUser)
.doOnSuccess(user -> {
if (!user.getUsername().contains("exception")) {
LOGGER.info("=====================add normal=================");
} else {
LOGGER.error("=====================add exception=================");
throw new RuntimeException("add1 exception test............");
}
})
.map(User::getId);
}
}
#RestController
#RequestMapping("/user")
public class UserController {
#Autowired
private UserService userService;
/**
* test Transactional
* #param user
* #return
*/
#PostMapping("/add1")
public Mono<Integer> add1(#RequestBody User user){
return userService.add1(user);
}
}
start test
When I execute the following request in intellij idea, as expected, an exception is thrown, and no record is inserted into the database.
POST http://localhost:8081/user/add1
Cache-Control: no-cache
Content-Type: application/json; charset=UTF-8
{
"username": "1exception11",
"password": "123456"
}
When I execute the following request in intellij idea, as expected, this record is inserted into the database.
POST http://localhost:8081/user/add1
Cache-Control: no-cache
Content-Type: application/json; charset=UTF-8
{
"username": "111",
"password": "123456"
}
The above code is the correct step, and it is the last version I debugged successfully. The following code is what I used at the beginning, but the result is not the same as I expected.
On the basis of the above code, add a class:
#Configuration
#EnableTransactionManagement
public class DatabaseConfiguration extends AbstractR2dbcConfiguration {
#NotNull
#Override
public ConnectionFactory connectionFactory() {
String url = "mysql://root:123456#127.0.0.1:3306/webflux-r2dbc";
return new JasyncConnectionFactory(new MySQLConnectionFactory(URLParser.INSTANCE.parseOrDie(url, StandardCharsets.UTF_8)));
}
#Bean
public ReactiveTransactionManager transactionManager() throws URISyntaxException {
return new R2dbcTransactionManager(this.connectionFactory());
}
}
and modify UserService.java -add method add2()
#Service
public class UserService {
private final static Logger LOGGER = LoggerFactory.getLogger(UserService.class);
private final static String EXCEPTION = "exception";
#Resource
R2dbcEntityTemplate r2dbcEntityTemplate;
#Resource
UserRepository userRepository;
#Transactional(rollbackFor = Exception.class)
public Mono<Integer> add1(User queryUser) {
return this.r2dbcEntityTemplate.insert(User.class)
.using(queryUser)
.doOnSuccess(user -> {
if (!user.getUsername().contains(EXCEPTION)) {
LOGGER.info("=====================add normal=================");
} else {
LOGGER.error("=====================add exception=================");
throw new RuntimeException("add1 exception test............");
}
})
.map(User::getId);
}
#Transactional(rollbackFor = Exception.class)
public Mono<Integer> add2(User queryUser) {
return userRepository.save(queryUser).flatMap((Function<User, Mono<Integer>>) user -> {
if (user.getUsername().contains(EXCEPTION)) {
LOGGER.error("=====================add2 exception=================");
throw new RuntimeException("test exception...");
}
return Mono.just(user.getId());
});
}
}
and modify UserController.java -add method add2()
#RestController
#RequestMapping("/user")
public class UserController {
#Autowired
private UserService userService;
/**
* transaction work
* #param user
* #return
*/
#PostMapping("/add1")
public Mono<Integer> add1(#RequestBody User user){
return userService.add1(user);
}
/**
* transaction not ork
* #param user
* #return
*/
#PostMapping("/add2")
public Mono<Integer> add2(#RequestBody User user){
return userService.add2(user);
}
}
Test:
When I execute the following request in intellij idea, as expected, this record is inserted into the database.
POST http://localhost:8081/user/add1
Cache-Control: no-cache
Content-Type: application/json; charset=UTF-8
{
"username": "222",
"password": "123456"
}
When I execute the following request in intellij idea, an exception is thrown, and this record is inserted into the database.
POST http://localhost:8081/user/add1
Cache-Control: no-cache
Content-Type: application/json; charset=UTF-8
{
"username": "222exception",
"password": "123456"
}
Why does this happen, can anyone explain it, thank you very much.
I had the same problem and was able to resolve this by registering a R2dbcEntityOperations bean as well as putting this bean to #EnableR2dbcRepositories=entityOperationsRef = "yourBeanName")
I am new to kafka, springboot and trying to integrate kafka and elastic search in my springboot application.
When I try to run the springboot app I see below error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'kafkaListenerContainerFactory' defined in class path resource [org/springframework/boot/autoconfigure/kafka/KafkaAnnotationDrivenConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory]: Factory method 'kafkaListenerContainerFactory' threw exception; nested exception is java.lang.NoSuchMethodError:org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory.getContainerProperties()Lorg/springframework/kafka/listener/config/ContainerProperties;
My pom.xml
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<version>2.2.3.RELEASE</version>
</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-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>4.1.0</version>
</dependency>
Application.yml
security:
enabled: true
spring:
resources:
chain:
enabled: true
kafka:
consumer:
bootstrap-servers: localhost:9092
group-id: group-id
auto-offset-reset: earliest
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
producer:
bootstrap-servers: localhost:9092
key-serializer: org.apache.kafka.common.serialization.StringSerializer
value-serializer: org.apache.kafka.common.serialization.StringDeserializer
Producer class
#Service
public class Producer {
private static final Logger logger = LoggerFactory.getLogger(Producer.class);
private static final String topic = "users";
#Autowired
private KafkaTemplate<String, String> kafkaTemplate;
public void sendMessage(History t){
logger.info("Inside send message to topic");
this.kafkaTemplate.send(topic,"HelloWorld");
}
}
Consumer.java
package com.springboot.kafka;
import com.springboot.model.History;
import com.springboot.repository.HistoryRepository;
import org.apache.kafka.common.protocol.types.Field;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
#Service
public class Consumer {
private static final Logger logger = LoggerFactory.getLogger(Consumer.class);
private static final String topic = "users";
#KafkaListener(topics = topic,groupId = "group-id")
public void consume (String t){
logger.info("Message read as " + t);
}
}
Application.properties:
logging.level.sql=info
logging.file = /var/tmp/SpringBootAppLog.log
spring.datasource.driver=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/test
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.hibernate.ddl-auto=update
spring.data.elasticsearch.cluster-name=my-application
spring.data.elasticsearch.cluster-nodes=localhost:9200
Any idea on what I am missing on. Any leads will be highly appreciated.
You should check your full error log (stacktrace). In my case the problem was caused by a java.io.FileNotFoundException further below.Often you find your 'real' problem at the end of the stacktrace.
Your value-serializer uses a StringDeserializer. I would assume this should be the StringSerializer. Therefore, a serialize method for the value missing.
I am creating a simple Spring WebMVC app with thymeleaf and now I want to add a service which provides a connection to a couchbase server.
I tried to create the couchbase service on basis of the following tutorial Couchbase with Spring-Boot and Spring Data
I have the following project structure:
src/main/java
com.project
config
MvcWebApplicationInitializer
MvcWebConfig
controller
IndexController
model
Area
Building
BuildingRepository
BuildingService
BuildingServiceImpl
When trying to autowire the service I get the exception that there is no bean named couchbaseRepositoryOperationsMapping which happens because my repository class extends CouchbasePagingAndSortingRepository which throws the exception.
I get the following exception:
[main] INFO org.springframework.web.servlet.DispatcherServlet -
Initializing Servlet 'dispatcher' [main] INFO
org.springframework.data.repository.config.RepositoryConfigurationDelegate
- Multiple Spring Data modules found, entering strict repository configuration mode! [main] INFO
org.springframework.data.repository.config.RepositoryConfigurationDelegate
- Bootstrapping Spring Data repositories in DEFAULT mode. [main] INFO org.springframework.data.repository.config.RepositoryConfigurationDelegate
- Finished Spring Data repository scanning in 64ms. Found 1 repository interfaces. [main] WARN
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
- Exception encountered during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'buildingServiceImpl': Unsatisfied
dependency expressed through field 'buildingRepository'; nested
exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'buildingRepository':
'buildingRepository' depends on missing bean
'couchbaseRepositoryOperationsMapping'; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
bean named 'couchbaseRepositoryOperationsMapping' available [main]
ERROR org.springframework.web.servlet.DispatcherServlet - Context
initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'buildingServiceImpl': Unsatisfied
dependency expressed through field 'buildingRepository'; nested
exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'buildingRepository':
'buildingRepository' depends on missing bean
'couchbaseRepositoryOperationsMapping'; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
bean named 'couchbaseRepositoryOperationsMapping' available
As far as I understand it is not working because there is no bean
named couchbaseRepositoryOperationsMapping.
My MvcWebConfig:
#Configuration
#EnableWebMvc
#ComponentScan("com.xplorg.controller")
#EnableCouchbaseRepositories(basePackages = {"com.xplorg.model"})
public class MvcWebConfig implements WebMvcConfigurer {
#Autowired
private ApplicationContext applicationContext;
#Bean
public SpringResourceTemplateResolver templateResolver() {
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setSuffix(".html");
return templateResolver;
}
#Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.setEnableSpringELCompiler(true);
return templateEngine;
}
public void configureViewResolvers(ViewResolverRegistry registry) {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
registry.viewResolver(viewResolver);
}
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}
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.project</groupId>
<artifactId>xplorg</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Project</name>
<properties>
<failOnMissingWebXml>false</failOnMissingWebXml>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.11.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.7-1</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-couchbase</artifactId>
<version>3.1.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.4.18.v20190429</version>
</plugin>
</plugins>
</build>
</project>
****Update****
Adding a CouchbaseConfig class fixed the problem with the couchbaseRepositoryOperationsMapping but I get now another error, that there is now named bean buildingRepository. All classes are based on the tutorial Couchbase with Spring-Boot and Spring Data. Do I miss an annotations and therefore spring can not autowire the class?
My repository class:
#N1qlPrimaryIndexed
#ViewIndexed(designDoc = "building")
public interface BuildingRepository extends CouchbasePagingAndSortingRepository<Building, String> {
List<Building> findByCompanyId(String companyId);
Page<Building> findByCompanyIdAndNameLikeOrderByName(String companyId, String name, Pageable pageable);
#Query("#{#n1ql.selectEntity} where #{#n1ql.filter} and companyId = $1 and $2 within #{#n1ql.bucket}")
Building findByCompanyAndAreaId(String companyId, String areaId);
#Query("#{#n1ql.selectEntity} where #{#n1ql.filter} AND ANY phone IN phoneNumbers SATISFIES phone = $1 END")
List<Building> findByPhoneNumber(String telephoneNumber);
#Query("SELECT COUNT(*) AS count FROM #{#n1ql.bucket} WHERE #{#n1ql.filter} and companyId = $1")
Long countBuildings(String companyId);
}
My service class:
#Service
public class BuildingServiceImpl implements BuildingService {
#Autowired
private BuildingRepository buildingRepository;
#Override
public List<Building> findByCompanyId(String companyId) {
return buildingRepository.findByCompanyId(companyId);
}
public List<Building> findByCompanyIdAndNameLike(String companyId, String name, int page) {
return buildingRepository.findByCompanyIdAndNameLikeOrderByName(companyId, name, new PageRequest(page, 20))
.getContent();
}
#Override
public Building findByCompanyAndAreaId(String companyId, String areaId) {
return buildingRepository.findByCompanyAndAreaId(companyId, areaId);
}
#Override
public List<Building> findByPhoneNumber(String telephoneNumber) {
return buildingRepository.findByPhoneNumber(telephoneNumber);
}
#Override
public Building findById(String buildingId) {
return buildingRepository.findById(buildingId).get();
}
#Override
public Building save(Building building) {
return buildingRepository.save(building);
}
#Override
public Long countBuildings(String companyId) {
return buildingRepository.countBuildings(companyId);
}
}
You missed the config class couchebase server
Create a dedicate config class extending the AbstractCouchbaseConfiguration for your couhcebase as below ( server # , user , pwd )
#Configuration
#EnableCouchbaseRepositories(basePackages = {"com.xplorg.model"})
public class CouchbaseConfig extends AbstractCouchbaseConfiguration {
#Override
protected List<String> getBootstrapHosts() {
return Arrays.asList("your server ip (like localhost in local)");
}
#Override
protected String getBucketName() {
return "username";
}
#Override
protected String getBucketPassword() {
return "passsword";
}
}
also change #ComponentScan("com.xplorg.controller") to #ComponentScan("com.xplorg") in your project config so your repositories interface and service should be scanned
When the object has another cutom object i get an error from swaggerUi:
Caused by: java.lang.NoSuchMethodError: io.swagger.models.properties.RefProperty.(Ljava/lang/String;Lio/swagger/models/refs/RefFormat;)V
Swagger version is 2.9.2 (https://mvnrepository.com/artifact/io.springfox/springfox-swagger2/2.9.2, https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui/2.9.2), java 11.
If i change object type of sender field to String it works fine, but i want it to work with custom object.
#Getter // lombok here
#Setter
#AllArgsConstructor
#XmlRootElement(name = "r")
#NoArgsConstructor
public class RDto {
private String id;
private String number;
private String status;
private String error;
}
#Data
#AllArgsConstructor
#NoArgsConstructor
#ToString
#XmlRootElement(name="TDto")
public class MDto {
RDto sender; // If changed to String -> works fine
}
#Component
public class CamelConfig extends RouteBuilder {
#Override
public void configure() throws Exception {
restConfiguration().component("servlet") // configure we want to use servlet as the component for the rest DSL
.bindingMode(RestBindingMode.json_xml) // enable json/xml binding mode
.dataFormatProperty("prettyPrint", "true") // output using pretty print
.contextPath("/con/api/")
.apiContextPath("/api-doc") // enable swagger api
.apiProperty("api.version", "2.0.0")
.apiProperty("api.title", "title")
.apiProperty("api.description", "descr")
.apiProperty("api.contact.name", "Aaa")
.apiProperty("cors", "true"); // enable CORS
// error handling to return custom HTTP status codes for the various exceptions
onException(TestMessageException.class)
.handled(true)
// use HTTP status 400 when input data is invalid
.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(400))
.setBody(simple("Invalid input data"));
rest()
.description("rest service provider")
.consumes("application/xml").produces("application/xml")
.post("/send").type(MDto.class)
.bindingMode(RestBindingMode.json_xml).description("test")
.route().routeId("REST test").log("Message send: \n ${body}")
.to("bean:MService?method=test")
.endRest();
}
}
I've changed depedencies (adding exclusions):
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
<exclusions>
<exclusion>
<artifactId>swagger-annotations</artifactId>
<groupId>io.swagger</groupId>
</exclusion>
<exclusion>
<artifactId>swagger-models</artifactId>
<groupId>io.swagger</groupId>
</exclusion>
</exclusions>
</dependency>
Cause also i'm using camel-swagger
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-spring-boot</artifactId>
<version>3.0.0-M2</version>
<!--<version>2.23.2</version>-->
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-swagger-java</artifactId>
<version>3.0.0-M2</version>
<!-- use the same version as your Camel core version -->
</dependency>
Here is my SOLR Data Model,
#SolrDocument(solrCoreName = "solrData")
public class SolrData {
#Id
#Indexed(name = "id", type = "string")
String id;
#Indexed(name = "name", type = "string")
String name;
This SOLR configuration,
#Configuration
#EnableSolrRepositories(basePackages={"com.ows.repository.solrRepository"}, multicoreSupport=true)
#ComponentScan
public class SolrConfig {
static final String SOLR_HOST = "http://localhost:8983/solr/";
#Bean
public SolrClient solrClient() {
return new HttpSolrClient.Builder(SOLR_HOST).build();
}
#Bean
public SolrTemplate solrTemplate(SolrClient solrClient) throws Exception {
return new SolrTemplate(solrClient);
}
}
The repository,
public interface SolrProductRepository extends SolrCrudRepository<SolrData, String> {
List<SolrData> findByName(String name);
}
The index controller,
#Autowired
SolrProductRepository solrProductRepository;
#RequestMapping("/solrindex")
public void solrIndex(Model model) {
SolrData solrData = new SolrData();
solrData.setName("You know Who");
solrProductRepository.save(solrData);
}
POM.xml
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-solr</artifactId>
<version>2.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-common</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-solrj</artifactId>
<version>6.6.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
With the above settings while I go for indexing using the index controller it says,
Updated complete error messages.
org.springframework.data.solr.UncategorizedSolrException: org.apache.solr.common.SolrInputDocument cannot be cast to java.util.Map; nested exception is java.lang.ClassCastException: org.apache.solr.common.SolrInputDocument cannot be cast to java.util.Map
at org.springframework.data.solr.core.SolrTemplate.execute(SolrTemplate.java:224)
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 org.springframework.data.solr.repository.support.SimpleSolrRepository.save(SimpleSolrRepository.java:149)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:504)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:489)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461)
Caused by: java.lang.ClassCastException: org.apache.solr.common.SolrInputDocument cannot be cast to java.util.Map
at org.springframework.data.solr.core.convert.MappingSolrConverter.write(MappingSolrConverter.java:62)
at org.springframework.data.solr.core.SolrTemplate.convertBeanToSolrInputDocument(SolrTemplate.java:1132)
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)
... 129 more
SOLVED
I solved the problem with below settings,
The sole configuration file is changed to below,
#Configuration
#EnableSolrRepositories(basePackages={"com.ows.rokomari.repository.solrRepository"}, multicoreSupport=true)
#ComponentScan
public class SolrConfig {
static final String SOLR_HOST = "http://localhost:8983/solr";
#Bean
public SolrClient solrClient() {
return new HttpSolrClient(SOLR_HOST);
}
#Bean
public SolrTemplate solrTemplate(SolrClient solrClient) throws Exception {
return new SolrTemplate(solrClient);
}
}
The pom.xml file is changed to below settings,
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-solr</artifactId>
<version>2.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-common</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
Now everything is quite fine.
I included solr-common because other than this the project throws error. Since my project is spring and running on version 4 with some other old dependencies. I guess the updated Solr related dependencies conflicts with existing dependencies, which is resolved by this one.
I used spring-data-solr which is bit different from using Solrj. Solrj implemation can be found here