SpringBoot Rest api - java

I want to make a simple java application and I want to use CRUDREPOSITORY and my own repository. I have this:
#RestController
#Transactional
#ExposesResourceFor(Person.class)
#RequestMapping("/prueba")
public class PersonController {
#RequestMapping(value="/prueba", method=RequestMethod.GET)
public String person(#RequestParam(value="id", defaultValue="1") int id) {
return "hola"+id;
}
}
this:
#RepositoryRestResource
public interface IClientRepository extends CrudRepository<Client, Long> {
}
The problem is that the CRUD works well, but I canĀ“t call my localhost:8080/prueba/prueba because it gives a 404 error. I have try all and I cant access it, please help me!!

By default, Spring Data REST serves up REST resources at the root URI, "/". There are multiple ways to change the base path.
With Spring Boot 1.2+, add below to application.properties:
spring.data.rest.basePath=/api
In your case:
spring.data.rest.basePath=/prueba/prueba
, assuming there is no override for server.contextPath in application.properties
Reference:
http://docs.spring.io/spring-data/rest/docs/current/reference/html/

Related

How to hide only one mapping from swagger ui documentation if I more than one mapping for method in Spring boot

I've one spring boot rest controller method which is mapped to multiple mappings. Please find the example code below.
#RestController
public class HomeController {
#RequestMapping( {"/", "/home"} )
public String home() {
return "Hello, World!";
}
}
I want to hide /home mapping from swagger documentation.
Can someone please help me to achieve this.
I also searched for a way to hide certain URLs from multi mapping methods. Unfortunately, I don't think it's possible when multi mapping it's defined like this #RequestMapping( {url1, url2} )
There are 2 alternative ways to do it:
Split your method into 2 methods that call the same function and annotate the one you want to hide with #Operation(hidden=true)
Define exceptions in your swagger config (for swagger 3 which uses open API):
#Configuration
public class SwaggerConfig {
#Bean
public GroupedOpenApi myApi()
{
return GroupedOpenApi.builder()
.pathsToMatch("/**")
.pathsToExclude("/home")
.build();
}
}

issue with springboot project : org.thymeleaf.exceptions.TemplateInputException

hey guys i have a problem in my java spring boot application
i've built a simple application and connected it with a database
but when i try to make a POST or GET on the data base my program access the database and do any thing i did but show an error
org.thymeleaf.exceptions.TemplateInputException: Error resolving template "Students", template might not exist or might not be accessible by any of the configured Template Resolvers
when i make GET i check the Iterable list and it's already get the data from database
but doesn't show the data on the localhost
it's give me that exception
is there any solution for that ?
this is my code in controller
#Path("Students")
#Controller
public class studentsController {
#AutoWired
StudentServices st;
#RequestMapping(method = RequestMethod.GET)
public Iterable<Students> getAllStudents() {
Iterable<Students> list = st.getAllStudents();
return list
}
With #Controller you are defining a Model-View-Controller (MVC) endpoint for returning your view templates. So with Iterable<Students> Spring is looking for a Students template in your src/main/resources/templates folder because it is interpreted as a View name.
If you want to create a REST endpoint which returns a list of Student objects you should use #RestController at your class which adds the Spring annotation #RequestBody automatically.
Furthermore #Path("XYZ") should be replaced with #RequestMapping("XYZ") in Spring and #AutoWired with #Autowired.
An working example could look like the following:
#RequestMapping("/students")
#RestController
public class StudentsController {
#Autowired
StudentServices st;
#RequestMapping(value="/", method = RequestMethod.GET)
public Iterable<Students> getAllStudents() {
Iterable<Students> list = st.getAllStudents();
return list
}

How to expose custom implementation of Spring Data Rest endpoint

I have a following problem. I made an application which uses spring-data and exposes it as a REST service using spring-data-rest. Everything went smooth till I wanted to have a custom implementation. I've created a CustomSomethingRepository and SomethingRepositoryImpl with one additional method. Spring data repository interface extended CustomSomethingRepository and everything was fine, I was able to execute my method from test directly, custom implementation was executed as well. Then I tried to get it through REST api and here I was surprised that this method is not available through /somethings/search . I'm almost hundred percent sure that it worked fine in spring boot 1.3.x and JpaRepositories. Now I'm using boot 1.5.x and MongoRepository. Please take a look at my example code:
#RepositoryRestResource
public interface SomethingRepository extends CrudRepository<Something>, CustomSomethingRepository {
//this one is available in /search
#RestResource(exported = true)
List<Something> findByEmail(String email);
}
and custom interface
public interface CustomSomethingRepository {
//this one will not be available in /search which is my problem :(
List<Something> findBySomethingWhichIsNotAnAttribute();
}
and implementation
#RepositoryRestResource
public class SomethingRepositoryImpl implements CustomSomethingRepository {
#Override
public List<Something> findBySomethingWhichIsNotAnAttribute() {
return new ArrayList<>(); //dummy code
}
}
Could you please give me a hint how can I expose CustomSomethingImpl as a part of Rest endpoint without creating another regular spring mvc bean which will be just handling this single request?
I've read questions like this: Implementing custom methods of Spring Data repository and exposing them through REST which state that this is not possible to achieve, but believe me or not, I had a project with spring-boot 1.3.x and those implementations were exposed as well :).
Thank you!
Since your custom method is returning a List you should put it in SomethingRepository which spring data rest will put it on the /search path. Add List findByNotAttribute()
#RepositoryRestResource public interface SomethingRepository extends CrudRepository<Something> {
#RestResource(exported = true)
List<Something> findByEmail(String email);
List<Something> findByNotAttribute(#Param String attribute);
}
So, I have the exact same question as you. I have a not fully tested solution because Im still working on it. I don't like it because it seems to be a bit hacky...Also I haven't tested it out fully. This is how far I have gotten. In your CustomSomethingRepository add the #Query annotation to the method you want to expose. Inside the annotation add a valid query.
public interface CustomSomethingRepository {
#Query("select smt from Something smt")
List<Something> findBySomethingWhichIsNotAnAttribute();
Now in the class that implements your CustomSomethingRepository
#Repositorypublic
#Transactional(readOnly = true)
class SomethingRepositoryImpl implements CustomSomethingRepository {
#PersistenceContext
private EntityManager entityManager;
#Override
public List<Something> findBySomethingWhichIsNotAnAttribute() {
System.out.println("HELLO");
}
}
Now when you go to http://localhost/something/search you should see something like
{
"_links" : {
"findByEmail" : {
"href" : "http://localhost/something/search/findByEmail{?email}"
},
"findBySomethingWhichIsNotAnAttribute" : {
"href" : "http://localhost/something/search/findBySomethingWhichIsNotAnAttribute"
},
"self" : {
"href" : "http://localhost/something/search/"
}
}
}
When you point your browser to http://localhost/something/search/findBySomethingWhichIsNotAnAttribute you will see HELLO printed and the query inside the #Query annotation will NOT run.
I'm facing another problem. In the SomethingRepositoryImpl I want to be able to call the findAll() method(s) in the SomethingRepository but if I autowire the SomethingRepository to SomethingRepositoryImpl the application errors out because it detects a cycle.
The dependencies of some of the beans in the application context form
a cycle:

Spring Data REST repository 404 from time to time

I have the Spring Boot application with Spring Data REST.
I have the following classes in it:
Data JPA repository for authentication purposes:
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String username);
}
Secured Data REST repository for API usages:
#RepositoryRestResource
#Secured(Role.ROLE_USER_READ)
public interface UserDataRestRepository extends PagingAndSortingRepository<User, Long> {
#Override
#Secured(Role.ROLE_USER_WRITE)
<S extends User>S save(S entity);
#Override
#Secured(Role.ROLE_USER_DELETE)
void delete(Long id);
}
Repository REST configurer adapter:
#Configuration
public class RepositoryRestConfig extends RepositoryRestConfigurerAdapter {
#Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.setRepositoryDetectionStrategy(RepositoryDetectionStrategies.ANNOTATED);
config.setReturnBodyOnCreate(true);
config.setReturnBodyOnUpdate(true);
config.setReturnBodyForPutAndPost(true);
}
}
The problem is when I start up my application, Data REST repository for API is unavailable from time to time. I guess it's because Spring rewrites repository bean for type User with the first JPA repository.
In Actuator beans endpoint I can see both beans even if REST API says 404 for /users page.
Again, this behavior is unpredictable for me - sometimes it works, sometimes doesn't.
Do you know the way how to tell to Spring to use the exact bean for Data REST?
Thanks in advance.
After some investigation, I've found exactly the same issue posted here.
Also, see this one.
Finally, I've merged 2 repositories into one and it solved my problem. But this is definitely not the way I prefer.

Spring project with REST and MongoDB - 404 pages and nothing working

I'm trying to get a Spring project to work with a simple rest service and a repository which fetches data from a MongoDB database. At this moment two separate things are working:
I can run this simple REST example: https://spring.io/guides/gs/rest-service/
I can connect to the MongoDB instance and fetch data
This both in separate projects.
I don't see, however, how I can bring these two together properly. At this moment I've tried the following based on several other tutorials and references (for example https://spring.io/guides/gs/accessing-mongodb-data-rest/). We now have 2 configs but when we deploy and try to go to rest url we just get 404's. it's not clear to me if the mapping is alright, I also don't see how the mapping is done in the first simple REST example.
Rest Controller:
#RestController
public class UserController {
#Autowired
private UserRepository userRepository;
#RequestMapping(value = "/users/{emailaddress}", method = RequestMethod.GET)
#ResponseBody
public User getUser(#PathVariable("emailaddress") String email) {
User user = userRepository.findByEmailAddress(email);
return user;
}
}
The Application class (as done in the tutorials):
#Configuration
#ComponentScan
#EnableAutoConfiguration
#Import(MongoConfig.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
The MongoConfig class (which we assume is about right but not 100% sure):
#Configuration
public class MongoConfig extends AbstractMongoConfiguration {
#Override
protected String getDatabaseName() {
return "<dbname>";
}
#Override
public Mongo mongo() throws Exception {
MongoCredential mongoCredential = MongoCredential.createPlainCredential("<username>", "<dbname>", "<pswd>".toCharArray());
return new MongoClient(new ServerAddress("<dbaddress>", <port>), Arrays.asList(mongoCredential));
}
}
I really hope someone can shed some light on how to this best, we don't need a Spring (MVC) front-end, just a REST service which will get data from our MongoDB.
Thanks in advance.
I too had this problem, I still get 404 error while running through eclipse tomcat, but I deployed the war in the tomcat webapps and ran through the server which worked for me.

Categories

Resources