So i want to save the data with the help of JPA repository but when i autowired it is giving me null. I don't know what else to do in here I have also tried with @EnableJPARepository annotation still no help. So here are the classes i am using. I want to save the data that is published by kafka so is it best to create a seperate function or can i put save to db function in consume json?
Repository
package com.prateek.addaKafka.addaKafka.kafkaConsumer;
import org.springframework.data.repository.CrudRepository;
public interface KafkaRepository extends CrudRepository<KafkaEntity,Long> {
}
KafkaEntityClass
package com.prateek.addaKafka.addaKafka.kafkaConsumer;
import javax.persistence.*;
@Entity
@Table(name = "messages")
public class KafkaEntity {
@Id
@GeneratedValue
private Long id;
@Column(nullable = false)
private String userName;
@Column(nullable = false)
private String userMessage;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserMessage() {
return userMessage;
}
public void setUserMessage(String userMessage) {
this.userMessage = userMessage;
}
}
ServiceClass
package com.prateek.addaKafka.addaKafka.kafkaConsumer;
import com.prateek.addaKafka.addaKafka.model.UserPublishModel;
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
@Service
public class KafkaListenerService {
@Autowired
KafkaRepository kafkaRepository;
@KafkaListener(topics = "NewTopic",groupId = "group_json",
containerFactory = "userKafkaListenerFactory")
public UserPublishModel consumeJson(UserPublishModel userPublishModel) {
return userPublishModel;
}
public void saveToDB(UserPublishModel userPublishModel){
ModelMapper modelMapper=new ModelMapper();
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
KafkaEntity kafkaEntity=modelMapper.map(userPublishModel, KafkaEntity.class);
kafkaRepository.save(kafkaEntity);
}
}
MainClass
package com.prateek.addaKafka.addaKafka;
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
public class AddaKafkaApplication {
public static void main(String[] args) {
SpringApplication.run(AddaKafkaApplication.class, args);
}
}