I created a chat on spring boot. Where several people can correspond. So I created a database and there I store all messages from users. So I want, if a new user enters the chat, then he should see only the last 10 messages. The problem is that the program does not take the last 10 messages from the database, it takes them from the server, this is not correct. I want him to take the last 10 messages from the database.
My code
Rest Controller
#SpringComponent
#org.springframework.web.bind.annotation.RestController
public class RestController {
private List<Message> store;
public RestController() {
store = new ArrayList<>();
}
#PutMapping("/api/save")
public void saveMessage(#RequestBody String chatMessage) {
store.add(new Gson().fromJson(chatMessage, Message.class));
if (store.size() > 10)
store.remove(0);
}
#GetMapping("/api/last")
public String getLasts() {
return new Gson().toJson(store);
}
}
Message class
#Entity
#Table(name = "chatMessages")
public class Message {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String fromV;
private String messageV;
private Timestamp time;
public Timestamp getTime() {
return time;
}
public void setTime(Timestamp time) {
this.time = time;
}
public Message() { }
public String getFromV() {
return fromV;
}
public void setFromV(String fromV) {
this.fromV = fromV;
}
public String getMessageV() {
return messageV;
}
public void setMessageV(String messageV) {
this.messageV = messageV;
}
public Message(String from, String message) {
this.fromV = from;
this.messageV = message;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFrom() {
return fromV;
}
public void setFrom(String from) {
this.fromV = from;
}
public String getMessage() {
return messageV;
}
public void setMessage(String message) {
this.messageV = message;
}
}
MessageRepository
#Repository
public interface MessageRepository extends JpaRepository<Message, Long> {
}
MessageService
public interface MessageService {
void add(Message message);
List<Message> getAllMessages();
}
MessageServiceImpl
#Service
#Transactional
public class MessageServiceImpl implements MessageService {
private final MessageRepository repository;
#Autowired
public MessageServiceImpl(MessageRepository repository) {
this.repository = repository;
}
#Override
public void add(Message message) {
message.setTime(new Timestamp(new Date().getTime()));
repository.saveAndFlush(message);
}
#Override
public List<Message> getAllMessages() {
return repository.findAll();
}
}
MessageList
public MessageList() {
addClassName("message-list");
}
#Override
public void add(Component... components) {
super.add(components);
components[components.length-1]
.getElement()
.callFunction("scrollIntoView");
}
}
Application Controller
server.port=8080
# This is a workaround for https://github.com/vaadin/spring/issues/381
spring.servlet.multipart.enabled = false
spring.datasource.url=jdbc:mysql://localhost:3306/chat?createDatabaseIfNotExist=true&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
To be frankly,i don't understand the purpose of the object store in your controller. If you want to query the last 10 messages.You can just implement a method in repository and invoke it in your controller.
MessageRepository
#Repository
public interface MessageRepository extends JpaRepository<Message, Long> {
List<Message> findTop10ByOrderByTimeDesc();
}
Related
Is it possible to fetch Data from 3 tables in hibernate where the controller is of a different model.
codeAModel.Java
#Entity
#Table(name="demo")
//#NamedQuery(name="Demo.findAll", query="SELECT m FROM Demo m")
public class AModel implements Serializable {
#Column(name="demo_loc")
private String location;
#Column(name="name")
private String name;
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
BModel.Java
#Entity
#Table(name="location")
//#NamedQuery(name="City.findAll", query="SELECT c FROM City c")
public class BModel implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="locationNoid")
private int locationNoId;
#Column(name="Code")
private int Code;
public int getLocationNoId() {
return locationNoId;
}
public void setLocationNoId(int locationNoId) {
this.locationNoId = locationNoId;
}
public int getCode() {
return Code;
}
public void setCode(int code) {
Code = code;
}
}
CModel.java
#Entity
#Table(name="offers")
public class CModel implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int OfferShopid;
#Column(name="offerCount")
private int offerCount;
#Column(name="foodCount")
private int foodCount;
public int getOfferShopid() {
return OfferShopid;
}
public void setOfferShopid(int offerShopid) {
OfferShopid = offerShopid;
}
public int getOfferCount() {
return offerCount;
}
public void setOfferCount(int offerCount) {
this.offerCount = offerCount;
}
public int getFoodCount() {
return foodCount;
}
public void setFoodCount(int foodCount) {
this.foodCount = foodCount;
}
}
DemoDTO.java
public class LocationDTO {
private int demoId;
private String name;
private int Code;
private int foodCount;
public int getDemoId() {
return demoId;
}
public void setDemoId(int demoId) {
this.demoId = demoId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCode() {
return Code;
}
public void setCode(int code) {
Code = code;
}
public int getFoodCount() {
return foodCount;
}
public void setFoodCount(int foodCount) {
this.foodCount = foodCount;
}
}
DemoController.java
#RestController
#RequestMapping("/api/abcService")
#Api(description = "REST API to list details")
public class DemoController {
#Autowired
private DemoService DemoService;
#RequestMapping(value = "/list/v1/{user_id}/uid/{locationNoId}/location",
method = RequestMethod.GET)
#ResponseBody
#ApiOperation(value = "Get all Lists", notes = "Get all Address related
information")
public ResponseEntity<?> getAll(#PathVariable("user_id") int userId,
#PathVariable("locationNoId") int locationNoId)
{
try {
ModelMapper modelMapper = new ModelMapper();
Type listType = new TypeToken<List<DemoDTO>>() {
}.getType();
List<DemoDTO> listAll=DemoService.ListAll(userId,locationNoId);
return new ResponseEntity<>(listAll, HttpStatus.OK);
}catch (Exception ex){
String errorMessage;
errorMessage = ex.getMessage();
return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST);
}
}
}
DemoDAOImpl
#Component
#Repository
#Transactional
public class DemoDAOImpl implements DemoDAO {
#PersistenceContext
private EntityManager entityManager;
#Autowired
private AService aService;
AModel aModel;
#Override
public #ResponseBody List<DemoDTO> ListAll(int User_id, int locationNoId) {
// TODO Auto-generated method stub
List<DemoDTO> listDemo=new ArrayList<>();
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<AModel> query =
criteriaBuilder.createQuery(AModel.class); Root<AModel> root =
query.from(AModel.class); query.select(root); CriteriaQuery<AModel>
select = query.select(root); TypedQuery<AModel> typedQuery =
entityManager.createQuery(select); List<AModel> AllLists =
typedQuery.getResultList();
for(AModel listofAll :AllLists ) {
System.out.println(listofAll.getid());
System.out.println(listofAll.getname());
System.out.println(listofAll.getlocation());
System.out.println(listofAll.getid());
System.out.println(listofAll.getRating());
listMalls.(AllLists);
return listMalls;
}
Base DemoController you have already a DemoService that you can reuse between other controlers. So if you have
#RestController
#RequestMapping("/api/abcServiceA")
public class DemoControllerA {
#Autowired
private DemoServiceA demoServiceA;
#RestController
#RequestMapping("/api/abcServiceB")
public class DemoControllerB {
#Autowired
private DemoServiceB demoServiceB;
You can create controler:
#RestController
#RequestMapping("/api/abcServiceB")
public class DemoControllerD {
#Autowired
private DemoServiceA demoServiceA;
#Autowired
private DemoServiceB demoServiceB;
Use this two services in one method:
#RequestMapping(value = "/list/v1/{user_id}/uid/{locationNoId}/location",method = RequestMethod.GET)
#ResponseBody
#ApiOperation(value = "Get all Lists", notes = "Get all Address related information")
public ResponseEntity<?>getAll(#PathVariable("user_id")int userId,
#PathVariable("locationNoId")int locationNoId) {
try {
ModelMapper modelMapper = new ModelMapper();
Type listType = new TypeToken<List<DemoDTO>>() {}.getType();
List<DemoDTO> listAllFromA = aemoServiceA.ListAll(userId, locationNoId);
List<DemoDTO> listAllFromB = aemoServiceB.ListAll(userId, locationNoId);
// do something with listAllFromA and listAllFromB
return new ResponseEntity<>(listAll, HttpStatus.OK);
} catch (Exception ex) {
String errorMessage;
errorMessage = ex.getMessage();
return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST);
}
}
I have created a spring boot project with mongodb , when i insert data into collection it get inserted but when i try to fetch from findOne by id the inserted value based on id it always returns null, I have given my model class and inserting method below,please tell me whats wrong
Account.java
#Document(collection = "account")
public class Account {
#Id
private long _id;
#Field("account_name")
private String accountName;
#Field("connector_type")
private String connectorType;
#Field("xsiURI1")
private String xsiURI1;
#Field("xsiURI2")
private String xsiURI2;
#Field("oci1")
private String OCI1;
#Field("oci2")
private String OCI2;
#Field("telcomadmin_username")
private String telcomadminUsername;
#Field("telcomadmin_password")
private String telcomadminPassword;
#Field("password_expdays")
private String passwordExpdays;
#Field("account_email_address")
private String accountEmailAddress;
#DateTimeFormat(iso = ISO.DATE_TIME)
#Field("inserted_date")
private Date insertedDate;
#DateTimeFormat(iso = ISO.DATE_TIME)
#Field("updated_date")
private Date updatedDate;
#Field("isActive")
private Boolean isActive;
public long get_id() {
return _id;
}
public void set_id(long _id) {
this._id = _id;
}
public String getXsiURI1() {
return xsiURI1;
}
public void setXsiURI1(String xsiURI1) {
this.xsiURI1 = xsiURI1;
}
public String getXsiURI2() {
return xsiURI2;
}
public void setXsiURI2(String xsiURI2) {
this.xsiURI2 = xsiURI2;
}
public String getOCI1() {
return OCI1;
}
public void setOCI1(String oCI1) {
OCI1 = oCI1;
}
public String getOCI2() {
return OCI2;
}
public void setOCI2(String oCI2) {
OCI2 = oCI2;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public String getConnectorType() {
return connectorType;
}
public void setConnectorType(String connectorType) {
this.connectorType = connectorType;
}
public String getTelcomadminUsername() {
return telcomadminUsername;
}
public void setTelcomadminUsername(String telcomadminUsername) {
this.telcomadminUsername = telcomadminUsername;
}
public String getTelcomadminPassword() {
return telcomadminPassword;
}
public void setTelcomadminPassword(String telcomadminPassword) {
this.telcomadminPassword = telcomadminPassword;
}
public String getPasswordExpdays() {
return passwordExpdays;
}
public void setPasswordExpdays(String passwordExpdays) {
this.passwordExpdays = passwordExpdays;
}
public String getAccountEmailAddress() {
return accountEmailAddress;
}
public void setAccountEmailAddress(String accountEmailAddress) {
this.accountEmailAddress = accountEmailAddress;
}
public Date getInsertedDate() {
return insertedDate;
}
public void setInsertedDate(Date insertedDate) {
this.insertedDate = insertedDate;
}
public Date getUpdatedDate() {
return updatedDate;
}
public void setUpdatedDate(Date updatedDate) {
this.updatedDate = updatedDate;
}
public Boolean getIsActive() {
return isActive;
}
public void setIsActive(Boolean isActive) {
this.isActive = isActive;
}
}
AccountsController.java
#RestController
#RequestMapping("/accounts")
#CrossOrigin("*")
public class AccountsController {
#Autowired
AccountsRepository accountsRepository;
#Autowired
SequenceRepository sequenceRepository;
private static final String ACCOUNT_SEQ_KEY = "accountsequence";
#PostMapping("/create")
public Account createAccount(#Valid #RequestBody Account account) {
account.set_id(sequenceRepository.getNextSequenceId(ACCOUNT_SEQ_KEY));
account.setIsActive(true);
return accountsRepository.save(account);
}
#GetMapping(value = "/findByID/{id}")
public ResponseEntity<Account> getAccountById(#PathVariable("id") String id) {
Account account = accountsRepository.findOne(id);
if (account == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
} else {
return new ResponseEntity<>(account, HttpStatus.OK);
}
}
}
AccountsRepository
public interface AccountsRepository {
List<Account> findAll(Sort sortByCreatedAtDesc);
Account save(Account account);
Account findOne(String id);
void delete(String id);
}
AccountsRepositoryIMPL
#Repository
public class AccountsRepositoryImpl implements AccountsRepository {
DBOperations dbOperations = new DBOperations();
#Override
public List<Account> findAll(Sort sortByCreatedAtDesc) {
Query q = new Query().with(new Sort(Sort.Direction.ASC, "inserted_date"));
List<Account> accountList = dbOperations.getMongoOpertion().findAllAndRemove(q, Account.class);
return accountList;
}
#Override
public Account save(Account account) {
try {
dbOperations.getMongoOpertion().save(account);
} catch (Exception e) {
e.printStackTrace();
}
return account;
}
#Override
public Account fin**strong text**dOne(String id) {
Account account = dbOperations.getMongoOpertion().findOne(Query.query(Criteria.where("_id").is(id)),
Account.class, "account");
return account;
}
#Override
public void delete(String id) {
Query query = new Query();
query.addCriteria(Criteria.where("id").is(id));
Account account = dbOperations.getMongoOpertion().findOne(query, Account.class);
dbOperations.getMongoOpertion().remove(account);
}
}
DBOperations.java
public class DBOperations {
ApplicationContext ctx = new GenericXmlApplicationContext("SpringConfig.xml");
public MongoOperations getMongoOpertion() {
MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");
return mongoOperation;
}
}
Look at your code.
You have declared _id as Long type.
#Id
private long _id;
But in your below methods you are passing String id to match the criteria.
So it is not working.
#Override
public Account findOne(String id) {
Account account = dbOperations.getMongoOpertion().findOne(Query.query(Criteria.where("_id").is(id)),
Account.class, "account");
return account;
}
#Override
public void delete(String id) {
Query query = new Query();
query.addCriteria(Criteria.where("id").is(id));
Account account = dbOperations.getMongoOpertion().findOne(query, Account.class);
dbOperations.getMongoOpertion().remove(account);
}
This is my model class for my reminds
public class Remind extends RealmObject {
#Required
private String descripcion;
#Required
private String fecha;
#Required
private String hora;
#Required
private String titulo;
#PrimaryKey
private String id;
public Remind() {}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getFecha() {
return fecha;
}
public void setFecha(String fecha) {
this.fecha = fecha;
}
public String getHora() {
return hora;
}
public void setHora(String hora) {
this.hora = hora;
}
}
this is my config class for obtain context 'cause i don't know what is the
problem with this class :(
public class RemindMe extends Application {
#RealmModule(classes = {Remind.class})
public class SimpleRealmModule {}
private static RemindMe instance;
#Override
public void onCreate() {
super.onCreate();
RealmConfiguration config = new RealmConfiguration.Builder(this).name("RemindMe.DB").build();
Realm.setDefaultConfiguration(config);
}
and this is a part of mi DAO for add some reminds
//this is so problematic class 'cause the Realm object don't find the
database context
public class RemindsDAO {
static boolean flag = false;
public boolean agregarRecordatorio(final Remind remind){
final Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
Remind rem = realm.createObject(Remind.class);
rem.setId(UUID.randomUUID().toString());
rem.setTitulo(remind.getTitulo());
rem.setDescripcion(remind.getDescripcion());
rem.setHora(remind.getHora());
rem.setFecha(remind.getFecha());
}
}, new Realm.Transaction.Callback() {
#Override
public void onSuccess() {
realm.commitTransaction();
RemindsDAO.flag = true;
}
#Override
public void onError(Exception e) {
flag = false;
}
});
return flag;
}
}
You need to register your Application class in the Manifest:
<application
android:name=".RemindMe">
your activities go here...
</application>
Once done you should be able to use Realm.getDefaultInstance() throughout the app with no hassle.
I want to create a spring batch application.
The skelethon is like:
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
#Configuration
#EnableBatchProcessing
public class CrawlerBatchConfiguration {
#Bean
public Job job(JobBuilderFactory jobs, Step step) {
return jobs.get("myJob").start(step).build();
}
#Bean
protected Step step(StepBuilderFactory steps) {
return steps.get("step")
.<Product, Product>chunk(11)
.reader(reader())
.processor(processor())
.writer(writer())
.build();
}
protected Step runCrawlerStep (StepBuilderFactory steps){
return steps.get("runCrawlerStep").tasklet(tasklet()).build();
}
private Tasklet tasklet() {
return new RunCrawlerTasklet();
}
public ItemProcessor<Product, Product> processor() {
return new ItemProcessor<Product, Product>() {
#Override
public Product process(Product product) throws Exception {
return new Product();
}
};
}
#Bean
public ItemReader<Product> reader() {
return new ProductItemReader();
}
#Bean
public ItemWriter<Product> writer() {
return new ItemWriter<Product>() {
#Override
public void write(List<? extends Product> list) throws Exception {
list.forEach(p -> System.out.println(p));
}
};
}
}
So I have this product class:
#Entity
#Table(name = "tb_produtos")
public class Product implements Serializable {
public Product() {
}
#Id
#GeneratedValue
private Integer id;
#ManyToOne
#JoinColumn(name = "ID_FABRICANTE")
private Manufacturer manufacturer;
#Column(name = "DESCRICAO")
private String description;
#Column(name = "URL")
private String url;
#Embedded
private Ean13 ean;
#Transient
private Keywords keywords;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public void setEan(Ean13 ean) {
this.ean = ean;
}
public Manufacturer getManufacturer() {
return manufacturer;
}
public void setManufacturer(Manufacturer manufacturer) {
this.manufacturer = manufacturer;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Keywords getKeywords() {
return keywords;
}
public void setKeywords(Keywords keywords) {
this.keywords = keywords;
}
}
That holds information that is extracted by a web crawler program. This crawler is a class that run in background to extract all product from a website. When a product is extracted, it fire an event that can be captured by listeners.
The crawler life cycle and the batch is finite, when all product is extract, the app can stop. But the process of grab and store (by batch) is asynchronous.
As I said, I have to create a batch program that should start this crawler (step1) and listen to this crawler to read data from it, process the data and write in a database (step2).
I worked a bit with spring batch, but not very solid way, I'm
struggling to mount this batch. More precisely in knowing how to make the crawler running in the background and as he gathers information, run the process of reading, processing and writing of the batch.
i'm trying to configure spring boot in order to have tomcat connection pool to my production database.
My application is NOT web (i have also some difficult to tell that to spring).
I have a Startup class and 3 more classes
the code
#Configuration
#EnableAutoConfiguration(exclude = DataSourceAutoConfiguration.class)
public class Starter {
private static Logger logger;
#Autowired
private static MyController controller;
public static void main(String[] args) {
// SpringApplication.setWebEnvironment(false);
SpringApplication.run(Starter.class, args);
LogbackConfigLoader lcl = new LogbackConfigLoader();
if (lcl.init()) {
logger = LoggerFactory.getLogger(Starter.class);
logger.debug("Initialized....");
}
else{
logger = LoggerFactory.getLogger(Starter.class);
}
logger.info(controller.getProva());
}
}
here is the configuration
`
#Configuration
#ConfigurationProperties(prefix="datasource.NIS")
public class NISDBConfiguration {
private String jdbcInterceptors;
private long validationInterval = 30000;
private org.apache.tomcat.jdbc.pool.DataSource pool;
#Value("${driver-class-name}")
private String driverClassName;
#Value("${url}")
private String url;
#Value("${username}")
private String username;
#Value("${password}")
private String password;
#Value("${maxActive}")
private int maxActive = 30;
#Value("${maxIdle}")
private int maxIdle = 8;
#Value("${minIdle}")
private int minIdle = 8;
#Value("${initialSize}")
private int initialSize = 10;
private String validationQuery;
private boolean testOnBorrow;
private boolean testOnReturn;
private boolean testWhileIdle;
private Integer timeBetweenEvictionRunsMillis;
private Integer minEvictableIdleTimeMillis;
private Integer maxWaitMillis;
public String getJdbcInterceptors() {
return jdbcInterceptors;
}
public void setJdbcInterceptors(String jdbcInterceptors) {
this.jdbcInterceptors = jdbcInterceptors;
}
public long getValidationInterval() {
return validationInterval;
}
public void setValidationInterval(long validationInterval) {
this.validationInterval = validationInterval;
}
public org.apache.tomcat.jdbc.pool.DataSource getPool() {
return pool;
}
public void setPool(org.apache.tomcat.jdbc.pool.DataSource pool) {
this.pool = pool;
}
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getMaxActive() {
return maxActive;
}
public void setMaxActive(int maxActive) {
this.maxActive = maxActive;
}
public int getMaxIdle() {
return maxIdle;
}
public void setMaxIdle(int maxIdle) {
this.maxIdle = maxIdle;
}
public int getMinIdle() {
return minIdle;
}
public void setMinIdle(int minIdle) {
this.minIdle = minIdle;
}
public int getInitialSize() {
return initialSize;
}
public void setInitialSize(int initialSize) {
this.initialSize = initialSize;
}
public String getValidationQuery() {
return validationQuery;
}
public void setValidationQuery(String validationQuery) {
this.validationQuery = validationQuery;
}
public boolean isTestOnBorrow() {
return testOnBorrow;
}
public void setTestOnBorrow(boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow;
}
public boolean isTestOnReturn() {
return testOnReturn;
}
public void setTestOnReturn(boolean testOnReturn) {
this.testOnReturn = testOnReturn;
}
public boolean isTestWhileIdle() {
return testWhileIdle;
}
public void setTestWhileIdle(boolean testWhileIdle) {
this.testWhileIdle = testWhileIdle;
}
public Integer getTimeBetweenEvictionRunsMillis() {
return timeBetweenEvictionRunsMillis;
}
public void setTimeBetweenEvictionRunsMillis(
Integer timeBetweenEvictionRunsMillis) {
this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
}
public Integer getMinEvictableIdleTimeMillis() {
return minEvictableIdleTimeMillis;
}
public void setMinEvictableIdleTimeMillis(Integer minEvictableIdleTimeMillis) {
this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
public Integer getMaxWaitMillis() {
return maxWaitMillis;
}
public void setMaxWaitMillis(Integer maxWaitMillis) {
this.maxWaitMillis = maxWaitMillis;
}
#Bean(name = "dsNIS")
public DataSource dataSource() {
this.pool = new org.apache.tomcat.jdbc.pool.DataSource();
this.pool.setDriverClassName(getDriverClassName());
this.pool.setUrl(getUrl());
this.pool.setUsername(getUsername());
this.pool.setPassword(getPassword());
this.pool.setInitialSize(getInitialSize());
this.pool.setMaxActive(getMaxActive());
this.pool.setMaxIdle(getMaxIdle());
this.pool.setMinIdle(getMinIdle());
this.pool.setTestOnBorrow(isTestOnBorrow());
this.pool.setTestOnReturn(isTestOnReturn());
this.pool.setTestWhileIdle(isTestWhileIdle());
if (getTimeBetweenEvictionRunsMillis() != null) {
this.pool
.setTimeBetweenEvictionRunsMillis(getTimeBetweenEvictionRunsMillis());
}
if (getMinEvictableIdleTimeMillis() != null) {
this.pool.setMinEvictableIdleTimeMillis(getMinEvictableIdleTimeMillis());
}
this.pool.setValidationQuery(getValidationQuery());
this.pool.setValidationInterval(this.validationInterval);
if (getMaxWaitMillis() != null) {
this.pool.setMaxWait(getMaxWaitMillis());
}
if (this.jdbcInterceptors != null) {
this.pool.setJdbcInterceptors(this.jdbcInterceptors);
}
return this.pool;
}
#PreDestroy
public void close() {
if (this.pool != null) {
this.pool.close();
}
}
#Bean(name = "jdbcNIS")
public JdbcTemplate jdbcTemplate(DataSource dsNIS) {
return new JdbcTemplate(dsNIS);
}
}
`
the repository
package org.hp.data;
#Repository
public class NisRepository {
protected final Logger log = LoggerFactory.getLogger(getClass());
#Autowired
#Qualifier("jdbcNIS")
protected JdbcTemplate jdbc;
public String getItem(long id) {
return jdbc.queryForObject("SELECT * FROM sb_item WHERE id=?", itemMapper, id);
}
private static final RowMapper<String> itemMapper = new RowMapper<String>() {
#Override
public String mapRow(ResultSet rs, int rowNum) throws SQLException {
String item = rs.getString("title");
return item;
}
};
public JdbcTemplate getJdbc() {
return jdbc;
}
public void setJdbc(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
}
the controller
#Controller
public class MyController {
#Autowired
private NisRepository items;
public NisRepository getItems() {
return items;
}
public void setItems(NisRepository items) {
this.items = items;
}
public String getProva(){
return items.getItem(10);
}
}
But i always get exception when running the application of NullPointerException because MyController is not autowired and is always null.
I also try to create a new instance with new (but i believe that this is not correct because of the spring mvc pattern).
What is the problem here?
Thanks in advance
You are using Spring Boot but are trying very hard not to use it. You also state you aren't using a web application but then why do you have a #Controller?
To fix your problem remove the configuration of the DataSource and JdbcTemplate Spring Boot will configure those for you. This basically means remove your NISDBConfiguration class. Just add the correct properties to the application.properties file.
spring.datasource.driver-class-name=<your-driver-here>
spring.datasource.url=<your-url>
spring.datasource.username=<your-username>
spring.datasource.password=<your-password>
And of course the other properties you need, check the reference guide for more properties.
Remove the #Qualifier from the JdbcTemplate property in your repository and you also don't need the getter and setter. I would suggest using constructor based injection.
package org.hp.data;
#Repository
public class NisRepository {
protected final Logger log = LoggerFactory.getLogger(getClass());
protected final JdbcTemplate jdbc;
#Autowired
public NisRepository(JdbcTemplate jbc) {
this.jdbc=jdbc;
}
public String getItem(long id) {
return jdbc.queryForObject("SELECT * FROM sb_item WHERE id=?", itemMapper, id);
}
private static final RowMapper<String> itemMapper = new RowMapper<String>() {
#Override
public String mapRow(ResultSet rs, int rowNum) throws SQLException {
String item = rs.getString("title");
return item;
}
};
}
If you don't have a web application replace #Controller with #Service.
Then rewrite your starter class.
#SpringBootApplication
public class Starter {
private static Logger logger;
public static void main(String[] args) {
// SpringApplication.setWebEnvironment(false);
ApplicationContext ctx = SpringApplication.run(Starter.class, args);
LogbackConfigLoader lcl = new LogbackConfigLoader();
if (lcl.init()) {
logger = LoggerFactory.getLogger(Starter.class);
logger.debug("Initialized....");
}
else{
logger = LoggerFactory.getLogger(Starter.class);
}
MyController controller = ctx.getBean(MyController.class);
logger.info(controller.getProva());
}
}
Looks like you are also trying to circument spring boots config loading here? Try to work with the framework not against it.
If you don't have a web application don't include the spring-boot-starter-web in your dependencies and also make sure you don't have any other web related things in there. Spring Boot auto detects the web environment and tries to bootstrap classes for that, if those aren't there it will just run as a plain java application.