Spring boot JSR303 Bean validation for non spring managed beans - java

Is it possible to implement JSR303 Bean validation with a plain spring-boot-starter project, Below are the source code I have failed to get working.
Does it require a Validation Bean to be configured if so it I can get it to do the validation using afterPropertiesSet but how to get it to work even when the properties are modified after the instance is created and how to get it to work for non Spring beans without using the Validator instance(to get the validation happen automatically whenever the annotations are encountered in a class)
pom.xml snippet
<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>
<name>jsr303</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.5.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
....
</project>
Source code
#Service
public class ProfileService {
public void createProfile( #Valid #NotEmpty String name, #Valid #NotEmpty String email) {
new Profile(
new EmailAddress(
"somasundarams#newemail.com"
),
"Somasundaram S"
);
}
}
Profile.java
public class Profile {
private EmailAddress emailAddress;
private String name;
public Profile(#Valid #NotNull EmailAddress emailAddress, #Valid #NotEmpty String name) {
this.emailAddress = emailAddress;
this.name = name;
}
.....
}
EmailAddress.java
public class EmailAddress {
private String email;
public EmailAddress(#Email String email) {
this.email = email;
}
.....
}
Jsr303Application.java
#SpringBootApplication
public class Jsr303Application {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(Jsr303Application.class, args);
ProfileService profileService = context.getBean(ProfileService.class);
profileService.createProfile(null, "Somasundaram S");
}
}

Related

how to fix "Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled."

I'm getting this error when trying to run my Java code with Maven using Intellij:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-06-29 23:39:33.179 ERROR 4068 --- [ main] o.s.boot.SpringApplication : Application run failed
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.server.app</groupId>
<artifactId>rest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>RestAPI</name>
<description>Demo project for Spring Boot</description>
<properties>
<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>
<!--> mysql on my computer version, the version should be true<-->
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
RestApi.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class RestApiApplication {
public static void main(String[] args) {
SpringApplication.run(RestApiApplication.class, args);
}
}
User.java
package com.server.app.rest.Models;
import javax.persistence.*;
// mysql columns, connection
#Entity
public class User {
// id is primary key
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column
private String firstName;
#Column
private String lastName;
#Column
private String job;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
}
UserRepo.java
import com.server.app.rest.Models.User;
import org.springframework.data.jpa.repository.JpaRepository;
//userrepo get features from jpa.
public interface UserRepo extends JpaRepository<User, Long> {
}
properies
spring.datasource.url=jdbc:mysql://localhost:3306/crudusers?allowPublicKeyRetrieval=true&useSSL=false
spring.datasource.username=username
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
ApiControllers.java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class ApiControllers {
// first connect the page, except this- / - get error
#GetMapping(value = "/")
public String getPage(){
return "Welcome";
}
}
Finally i solved the problem. The problem was the wrong password. I wrote the right password, then fixed the error.

when I use spring boot maven project mysql-connector and insert data into database as a post request , but not save data in database

I got this error
2021-02-04 10:31:48.341 WARN 6496 --- [nio-8080-exec-8]
.w.s.m.s.DefaultHandlerExceptionResolver : Resolved
[org.springframework.http.converter.HttpMessageNotReadableException:
JSON parse error: Cannot construct instance of
com.sun.org.apache.xpath.internal.operations.String (although at
least one Creator exists): no String-argument constructor/factory
method to deserialize from String value ('springboot#gmail.com');
nested exception is
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot
construct instance of
com.sun.org.apache.xpath.internal.operations.String (although at
least one Creator exists): no String-argument constructor/factory
method to deserialize from String value ('springboot#gmail.com') at
[Source: (PushbackInputStream); line: 5, column: 13] (through
reference chain: com.sample.springbootdemo.domain.UserDTO["email"])
my code is,
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.sample</groupId>
<artifactId>springboot-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
my domain is,
package com.sample.springbootdemo.domain;
import com.sun.org.apache.xpath.internal.operations.String;
import javax.persistence.*;
#Entity // This tells Hibernate to make a table out of this class
#Table(name = "user")
public class UserDTO {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name = "user_id" )
private Integer id;
#Column(name = "first_name",columnDefinition = "varchar(255)")
private String firstName;
#Column(name = "last_name",columnDefinition = "varchar(255)")
private String lastName;
#Column(name = "age")
private Integer age;
#Column(name = "email",columnDefinition = "varchar(255)")
private String email;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
** my controller is,**
package com.sample.springbootdemo.controllers;
import com.sample.springbootdemo.domain.UserDTO;
import com.sample.springbootdemo.services.UserServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
#RequestMapping(path="/user")
public class User {
#Autowired
private UserServices userServices;
#GetMapping("/all")
public List<UserDTO> allUsers(){
return userServices.findAllUsers();
}
#PostMapping(path = "/add")
public String addUser(#RequestBody UserDTO Userdata){
return userServices.saveUser(Userdata);
}
}
please help me to fix this error.
"String" should come with java natively. Do not use the import "com.sun.org.apache.xpath.internal.operations.String" Remove that line from your UserDTO.

Field topicRepository in api.dataBase.basic.apiDatabase.Models.TopicService required a bean of type

I am in the process of learning Java spring Boot from the tutorial found here
I keep getting the "Field topicRepository in api.dataBase.basic.apiDatabase.Models.TopicService required a bean of type 'api.dataBase.basic.apiDatabase.Interface.TopicRepository' that could not be found."
I read that this error can occur because of componentScan is failing for poor annotation of the class or poor package layout.
Layout of my java packages
lay out of my project
My classes are the following;
package api.dataBase.basic.apiDatabase;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication ()
public class ApiDatabaseApplication {
public static void main(String[] args) {
SpringApplication.run(ApiDatabaseApplication.class, args);
}
}
Topic.java
package api.dataBase.basic.apiDatabase.Models;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Topic {
#Id
private String id;
private String name;
private String description;
//private Address address;
public Topic(final String id, final String name, final String description) {
this.id = id;
this.name = name;
this.description = description;
}
public Topic() {
}
#Id
public String getId() {
return id;
}
public void setId(final String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(final String description) {
this.description = description;
}
}
TopicRepository.java
package api.dataBase.basic.apiDatabase.Interface;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import api.dataBase.basic.apiDatabase.Models.Topic;
#Repository
public interface TopicRepository extends CrudRepository <Topic, String>{
}
TopicService.java
package api.dataBase.basic.apiDatabase.Models;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import api.dataBase.basic.apiDatabase.Interface.TopicRepository;
#Service
public class TopicService {
#Autowired
private TopicRepository topicRepository;
private List<Topic> Oldtopics = new ArrayList<>(Arrays.asList(
new Topic("1001", "test", "hello 1"),
new Topic("1002", "hello", "hello 2")
));
public List<Topic> getTopics() {
List<Topic> topics = new ArrayList<>();
topicRepository.findAll().forEach(topics::add);
return topics;
}
public Topic getTopic(String id) {
return Oldtopics.stream().filter(t -> t.getId().equals(id)).findFirst().get();
}
public void addTopic(final Topic topic) {
topicRepository.save(topic);
}
public void updateTopic(final Topic topic, final String id) {
for (int i = 0; i < Oldtopics.size(); i++) {
if (Oldtopics.get(i).getId().equals(id)) {
Oldtopics.set(i, topic);
return;
}
}
}
public void deleteTopic(String id) {
Oldtopics.removeIf(t -> t.getId().equals(id));
}
public void deleteTopic(final String[] id) {
for (int i = 0; i < Oldtopics.size(); i++) {
for (String ids : id) {
if (Oldtopics.get(i).getId().equals(ids)) {
Oldtopics.remove(i);
}
}
}
}
}
Any help will be appreciated.
Full Stack Trace.
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-11-21 19:18:05.350 ERROR 4192 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field topicRepository in api.dataBase.basic.apiDatabase.Models.TopicService required a bean of type 'api.dataBase.basic.apiDatabase.Interface.TopicRepository' 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 'api.dataBase.basic.apiDatabase.Interface.TopicRepository' in your configuration.
POM:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>api.dataBase.basic</groupId>
<artifactId>apiDatabase</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>apiDatabase</name>
<description>API project with JPA database</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
This can be the case for missed configuration and thus messed component scan.
I'd suggest that you should add 'Config.java' with following content to your source root (src/main/java)
#Configuration
#EnableJpaRepositories
class Config {
}

Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javassist/bytecode/ClassFile

I am try to access data mysql in Spring Boot.when i run application.I got this error
Error creating bean with name 'entityManagerFactory' defined in class path resource[org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javassist/bytecode/ClassFile
my code is
Controller
#GetMapping(path="/add")
public #ResponseBody String addNewUser (#RequestParam String name
, #RequestParam String email) {
UserPojo n = new UserPojo();
n.setName(name);
n.setEmail(email);
userRepository.save(n);
return "Saved";
}
Service is
#Service("service")
#Transactional
public class UserService {
#Autowired
private User user;
public void addUser(UserPojo pojo) {
UserEntity userEntity = new UserEntity();
userEntity.setCustomerName(pojo.getCustomerName());
userEntity.setEmail(pojo.getEmail());
user.save(userEntity);
}
}
Dao is
public interface User extends CrudRepository<UserEntity, Integer> {
}
Entity is-
package com.example.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "customer")
public class UserEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Column
private String customerName;
#Column
private String email;
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
My Pojo
public class UserPojo {
private String customerName;
private String email;
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
My pom.xml
<?xml version="1.0" encoding="UTF-8"?>
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
<groupId>com.example</groupId>
<artifactId>Test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Test</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- JPA Data (We are going to use Repositories, Entities, Hibernate, etc...) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Use MySQL Connector-J -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
application.properties
spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp
server.port=8085
server.servlet.context-path=/finance
# Database
spring.datasource.url=jdbc:mysql://localhost:3306/test?
autoReconnect=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# Hibernate
hibernate.dialect: org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql: true
hibernate.hbm2ddl.auto: create
I have implemented your project. Everything going fine. I am describing step by step. I wrote my pom.xml like this
<?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.avijit</groupId>
<artifactId>bootproject</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</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>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Then I wrote my main class and created a bean for jsp page.
#SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
#Bean
public ViewResolver getViewResolver(){
InternalResourceViewResolver resolver = new
InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}
After this i wrote Controller class like
#Autowired
UserService userService;
#RequestMapping(value="/sample", method= RequestMethod.GET)
public String sample()
{
return "sample";
}
#RequestMapping(value="/sample", method= RequestMethod.POST)
public String dosave(#RequestParam String name, #RequestParam String email)
{
UserPojo n = new UserPojo();
n.setCustomerName(name);
n.setEmail(email);
userService.addUser(n);
return "sample";
}
And edited service class
#Autowired
private User user;
public void addUser(UserPojo pojo) {
UserEntity userEntity = new UserEntity();
userEntity.setCustomerName(pojo.getCustomerName());
userEntity.setEmail(pojo.getEmail());
user.save(userEntity);
}
While copying your code I found that in controller class you made an error n.setName(name); it would be n.setCustomerName(name). And in my property file I wrote like this.
spring.datasource.url =jdbc:mysql://127.0.0.1:3306/InternDatabase
spring.datasource.username = root
spring.datasource.password = 123456
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto = update
Check updated code and let us know.

Spring Tool Suite(3.6.3.SR1) starter project cannot connect to mongoldb

I have a very strange problem with my spring starter project:
I am using STS, the version of it is 3.6.3.SR1. I also install mongodb, the version of it is 2.6.7.
I want to use STS to connect to mongodb. So, I tried the project from the tutorial:
File -> new -> Import Spring Getting Started Content. Then I choose "Accessing Data Mongodb". Then I run the gs-accessing-data-mongodb-complete, it worked perfectly. The tutorial is here [enter link description here][1]
However, when I created a spring starter project, the Dependencies I choose MongoDB, Rest Repositories. I copy exactly the same code from above but it doesn't work.
Can anyone help me?
Pom.xml
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
<groupId>org.test</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<start-class>demo.DemoApplication</start-class>
<java.version>1.7</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</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-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
package demo;
import org.springframework.data.annotation.Id;
public class Customer {
#Id
private String id;
private String firstName;
private String lastName;
public Customer() {}
public Customer(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
#Override
public String toString() {
return String.format(
"Customer[id=%s, firstName='%s', lastName='%s']",
id, firstName, lastName);
}
}
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface CustomerRepository extends MongoRepository {
public Customer findByFirstName(String firstName);
public List<Customer> findByLastName(String lastName);
}
public class DemoApplication implements CommandLineRunner {
#Autowired
private CustomerRepository repository;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
repository.deleteAll();
// save a couple of customers
repository.save(new Customer("Alice", "Smith"));
repository.save(new Customer("Bob", "Smith"));
// fetch all customers
System.out.println("Customers found with findAll():");
System.out.println("-------------------------------");
for (Customer customer : repository.findAll()) {
System.out.println(customer);
}
System.out.println();
// fetch an individual customer
System.out.println("Customer found with findByFirstName('Alice'):");
System.out.println("--------------------------------");
System.out.println(repository.findByFirstName("Alice"));
System.out.println("Customers found with findByLastName('Smith'):");
System.out.println("--------------------------------");
for (Customer customer : repository.findByLastName("Smith")) {
System.out.println(customer);
}
}
}

Categories