Spring boot application failed to start with exception org.springframework.beans.factory.NoSuchBeanDefinitionException: - spring

I am using spring boot v2.5.2. Below is my folder structure and code. This is simple test project.
My folder structure:
RESTController Class:
package com.user.UserManagementSystem.controller;
import com.user.UserManagementSystem.model.User;
import com.user.UserManagementSystem.service.UserServiceImpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/api/v1/")
public class UserController {
#Autowired
private UserServiceImpl userRepository;
#GetMapping("/getAllUsers")
public List<User> getAllUsers() {
return userRepository.getUsers();
}
#GetMapping("/")
public String home() {
return "Hello";
}
}
User.java
package com.user.UserManagementSystem.model;
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= "Users")
public class User {
public User() {
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name ="userName")
private String userName;
#Column(name ="name")
private String name;
#Column(name ="language")
private String language;
#Column(name ="mobileNumber")
private int mobileNumber;
public User(String userName, String name, String language, int mobileNumber) {
this.userName = userName;
this.name = name;
this.language = language;
this.mobileNumber = mobileNumber;
}
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 getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public int getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(int mobileNumber) {
this.mobileNumber = mobileNumber;
}
}
UserRepository.java
package com.user.UserManagementSystem.repository;
import com.user.UserManagementSystem.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UserRepository extends JpaRepository<User, Long>{
}
UserService.java
package com.user.UserManagementSystem.service;
import com.user.UserManagementSystem.model.User;
import java.util.List;
public interface UserService {
List<User> getUsers();
User getUserById(Long id);
User addUser(User user);
void deleteUser(Long id);
}
UserServiceImpl.java
package com.user.UserManagementSystem.service;
import com.user.UserManagementSystem.repository.UserRepository;
import com.user.UserManagementSystem.model.User;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class UserServiceImpl implements UserService{
#Autowired
UserRepository userRepository;
#Override
public List<User> getUsers() {
return userRepository.findAll();
}
#Override
public User getUserById(Long id) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public User addUser(User user) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void deleteUser(Long id) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
UserManangmentSystemApplication.java
package com.user.UserManangmentSystem;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication(scanBasePackages = {"com.user.UserManangmentSystem", "com.user.UserManagementSystem.controller", "com.user.UserManagementSystem.repository", "com.user.UserManagementSystem.service"})
//#SpringBootApplication
public class UserManangmentSystemApplication {
public static void main(String[] args) {
SpringApplication.run(UserManangmentSystemApplication.class, args);
}
}
application.properties:
spring.datasource.url=jdbc:mariadb://localhost:3306/ums
spring.datasource.username=ums
spring.datasource.password=ums
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MariaDB53Dialect
server.port=8888
debug=true
When it build the project i am getting :
Caused by:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.user.UserManagementSystem.repository.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1790) ~[spring-beans-5.3.8.jar:5.3.8]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1346) ~[spring-beans-5.3.8.jar:5.3.8]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300) ~[spring-beans-5.3.8.jar:5.3.8]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:657) ~[spring-beans-5.3.8.jar:5.3.8]
Thanks in Advance.

Typo in your base package name which makes packages different.
Change
com.user.UserManangmentSystem
To
com.user.UserManangementSystem
Correct management spelling.

You have correct package structure it will collect all bean within base package and sub package also. No need explicitly mention package scan. If you have any spell mistakes then that error will occur.

Related

Spring boot (data jpa ) i am not able to save eumn value in database

package com.kk.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#ComponentScan(basePackages="com.kk")
#EnableJpaRepositories(basePackages="com.kk.respositry")
#EntityScan(basePackages="com.kk.entity")
#SpringBootApplication
public class SpringBootEnumExampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootEnumExampleApplication.class, args);
}
}
package com.kk.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.kk.entity.Account;
import com.kk.service.AccountService;
#Controller
public class AccountController {
#Autowired
private AccountService accountService;
#RequestMapping(value="create",method=RequestMethod.POST)
private #ResponseBody String createAccout(#RequestBody Account account) {
Long l=accountService.save(account);
return "{\"accountId\":l}";
}
}
package com.kk.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import com.kk.enums.AccountRole;
#Entity
#Table(name = "account_tab")
public class Account {
#Id
#GeneratedValue
private Long id;
private String accountHolderName;
private String mobile;
private Integer age;
#Enumerated(EnumType.STRING)
#Column(name = "account_role", length = 40)
private AccountRole accountRole;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAccountHolderName() {
return accountHolderName;
}
public void setAccountHolderName(String accountHolderName) {
this.accountHolderName = accountHolderName;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public AccountRole getAccountRole() {
return accountRole;
}
public void setAccountRole(AccountRole accountRole) {
this.accountRole = accountRole;
}
}
package com.kk.enums;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.kk.enums.utils.AccountRoleDeserializer;
#JsonDeserialize(using = AccountRoleDeserializer.class)
public enum AccountRole {
EMPLOYEE_CUSTOMER("Employee customer"),
JOINTER_ACSCOUNT("Jointer customer"),
PRIMARY_ACCOUNT("Primary customer"),
TENANT_ACCOUNT("Tenant customer");
private final String text;
AccountRole(final String text) {
this.text = text;
}
#Override
public String toString() {
return text;
}
public String getText() {
return this.text;
}
public static AccountRole fromText(String text) {
for (AccountRole r : AccountRole.values()) {
if (r.getText().equals(text)) {
return r;
}
}
throw new RuntimeException("Your AccountRole not valied: "+text );
}
}
package com.kk.enums.utils;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.kk.enums.AccountRole;
public class AccountRoleDeserializer extends JsonDeserializer<AccountRole> {
#Override
public AccountRole deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);
if (node == null) {
return null;
}
String text = node.textValue(); // gives "A" from the request
if (text == null) {
return null;
}
return AccountRole.fromText(text);
}
}
package com.kk.respositry;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.kk.entity.Account;
#Repository
public interface AccountRespositry extends JpaRepository<Account, Long> {
}
package com.kk.service;
import com.kk.entity.Account;
public interface AccountService {
Long save(Account account);
}
package com.kk.service;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.kk.entity.Account;
import com.kk.respositry.AccountRespositry;
#Service
#Transactional
public class AccountServiceImpl implements AccountService{
#Autowired
private AccountRespositry accountRespositry;
#Override
public Long save(Account account) {
account=accountRespositry.save(account);
return account.getId();
}
}
server.port=8088
server.servlet.context-path=/SpringBootEnum/
## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url = jdbc:mysql://localhost:3306/Account?useSSL=false
spring.datasource.username = root
spring.datasource.password = root
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
#Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update
I am using spring boot (data jpa ) but am getting the wrong value in the database.
The #Enumerated is behaving as expected. It's going to return the name of the enum and that's what gets persisted. Remember JPA uses the name() of the enum and not the toString() even if you have overridden the toString(). I would recommend using an AttributeConverter (JPA 2.1+) to control the persistence of your enum. In your case, create the converter to use the getText() method you already have defined in your Enum.
#Converter(autoApply = true)
public class AccountRoleConverter implements AttributeConverter<AccountRole, String> {
#Override
public String convertToDatabaseColumn(AccountRole role) {
return role.getText();
}
#Override
public AccountRole convertToEntityAttribute(String dbData) {
return AccountRole.fromText(dbData);
}
}
Note: #Converter(autoApply = true), tells JPA provider to use it to map all AccountRole enums.
Now you just need to make sure you remove the #Enumerated from your Account Entity:
#Enumerated(EnumType.STRING)
#Column(name = "account_role", length = 40)
private AccountRole accountRole;
becomes
#Column(name = "account_role", length = 40)
private AccountRole accountRole;
Ok you may ask how you use the converter. Well that is the nice part, you don't have to do anything. The persistence provider will use it for all read and write operations. I hope this helps.

No property findOne() found for type class User

I have searched many pages but didnt found the answer so i paste the whole code.I am testing the testclass and getting the error like "Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract org.home.mysystem.entity.User org.home.mysystem.repository.UserRepository.findOne(java.lang.String)! No property findOne found for type User!". Please someone help me
Role.java
package org.home.mysystem.entity;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
#Entity
public class Role {
#Id
private String name;
#ManyToMany(mappedBy = "roles")
private List<User> users;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public Role(String name, List<User> users) {
this.name = name;
this.users = users;
}
public Role() {
}
public Role(String name) {
this.name = name;
}
}
Task.java
package org.home.mysystem.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import org.hibernate.validator.constraints.NotEmpty;
#Entity
public class Task {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotEmpty
private String date;
#NotEmpty
private String startTime;
#NotEmpty
private String stopTime;
#NotEmpty
#Column(length=1000)
private String description;
#ManyToOne
#JoinColumn(name="USER_EMAIL")
private User user;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getStopTime() {
return stopTime;
}
public void setStopTime(String stopTime) {
this.stopTime = stopTime;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Task(String date, String startTime, String stopTime, String description, User user) {
this.date = date;
this.startTime = startTime;
this.stopTime = stopTime;
this.description = description;
this.user = user;
}
public Task(String date, String startTime, String stopTime, String description) {
this.date = date;
this.startTime = startTime;
this.stopTime = stopTime;
this.description = description;
}
public Task() {
}
}
User.java
package org.home.mysystem.entity;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
#Entity
public class User {
#Id
#Email
#NotEmpty
#Column(unique = true)
private String email;
#NotEmpty
private String name;
#Size(min = 4)
private String password;
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private List<Task> tasks;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "USER_ROLES", joinColumns={
#JoinColumn(name = "USER_EMAIL", referencedColumnName = "email") }, inverseJoinColumns = {
#JoinColumn(name = "ROLE_NAME", referencedColumnName = "name") })
private List<Role> roles;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<Task> gettasks() {
return tasks;
}
public void settasks(List<Task> tasks) {
this.tasks = tasks;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public User(String email, String name, String password) {
this.email = email;
this.name = name;
this.password = password;
}
public User() {
}
}
RoleRepository.java
package org.home.mysystem.repository;
import org.home.mysystem.entity.Role;
import org.springframework.data.jpa.repository.JpaRepository;
public interface RoleRepository extends JpaRepository<Role, String> {
}
TaskRepository.java
public interface TaskRepository extends JpaRepository<Task, Long> {
List<Task> findByUser(User user);
}
UserRepository.java
package org.home.mysystem.repository;
import org.home.mysystem.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User,String> {
User findOne(final String email);
}
TaskService.java
package org.home.mysystem.service;
import java.util.ArrayList;
import java.util.List;
import org.home.mysystem.entity.Role;
import org.home.mysystem.entity.Task;
import org.home.mysystem.entity.User;
import org.home.mysystem.repository.TaskRepository;
import org.home.mysystem.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
#Service
public class TaskService {
#Autowired
private TaskRepository taskRepository;
public void addTask(Task task, User user) {
task.setUser(user);
taskRepository.save(task);
}
public List<Task> findUserTask(User user){
return taskRepository.findByUser(user);
}
}
UserService.java
import java.util.ArrayList;
import java.util.List;
import org.home.mysystem.entity.Role;
import org.home.mysystem.entity.User;
import org.home.mysystem.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
#Service
public class UserService {
#Autowired
private UserRepository userRepository;
public void createUser(User user) {
BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
user.setPassword(encoder.encode(user.getPassword()));
Role userRole=new Role("USER");
List<Role> roles=new ArrayList<>();
roles.add(userRole);
user.setRoles(roles);
userRepository.save(user);
}
public void createAdmin(User user) {
BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
user.setPassword(encoder.encode(user.getPassword()));
Role userRole=new Role("ADMIN");
List<Role> roles=new ArrayList<>();
roles.add(userRole);
user.setRoles(roles);
userRepository.save(user);
}
public User findOne(String email) {
return userRepository.findOne(email);
}
}
MyApplicationTest.java
package org.home.mysystem;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.List;
import org.home.mysystem.entity.Task;
import org.home.mysystem.entity.User;
import org.home.mysystem.service.TaskService;
import org.home.mysystem.service.UserService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
#RunWith(SpringRunner.class)
#SpringBootTest
public class MySystemApplicationTests {
#Autowired
private UserService userService;
#Autowired
private TaskService taskService;
#Before
public void initDb() {
{
User newUser = new User("testUser#mail.com", "testUser", "123456");
userService.createUser(newUser);
}
{
User newUser = new User("testAdmin#mail.com", "testAdmin", "123456");
userService.createUser(newUser);
}
Task userTask = new Task("03/01/2018", "00:11", "11:00", "You need to work today");
User user = userService.findOne("testUser#mail.com");
taskService.addTask(userTask, user);
}
#Test
public void testUser() {
User user=userService.findOne("testUser#mail.com");
assertNotNull(user);
User admin=userService.findOne("testAdmin#mail.com");
assertEquals(admin.getEmail(),"testAdmin#mail.com");
}
#Test
public void testTask() {
User user=userService.findOne("testUser#mail.com");
List<Task> task=taskService.findUserTask(user);
assertNotNull(task);
}
}
The issue is that Spring is expecting something else as you are giving it.
findOne is by default defined to take an ID (primary key) to load the entity by. So it expects a long or Long (as far as I know). It takes the name of the parameter given (email) and is searching for an ID with that name and that simply doesn't add up.
If you want to search by an email or other field that has been defined by you, you need to use the following syntax:
Example 1
Example field to search by: email
Method in repository:
User findByEmail(String email)
Example 2
Example field to search by: username
Method in repository:
User findByUsername(String username)
I hope this helps!

Jersey - get parameter always null

I changed my code according to R4J answer.
I think there's something more to correct since I can't display anything now...
result I get - console is clear (no errors)
Could anyone be so kind and help me find the issue?
Below I describe my project:
DB:
database table "users"
TestUser.java
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 = "USERS")
public class TestUser {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Column(name = "email", nullable = false)
private String email;
#Column(name = "password", nullable = false)
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
TestService.class
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.test.testapp.dao.UserDao;
import com.test.testapp.model.TestUser;
#Component
public class TestService {
#Autowired
UserDao userDao;
public List<TestUser> getUsers() {
return userDao.findAll();
}
}
UserDao.class
import java.util.List;
import javax.persistence.PersistenceException;
import com.test.testapp.model.TestUser;
public interface UserDao /* extends CrudRepository<TestUser, Integer>*/{
public List<TestUser> findAll() throws PersistenceException;
}
UserDaoImpl.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import org.jvnet.hk2.annotations.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.test.testapp.dao.UserDao;
import com.test.testapp.model.TestUser;
#Repository("userDao")
#Service
public class UserDaoImpl implements UserDao {
#Autowired
private EntityManager entityManager;
#PersistenceContext
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public TestUser findPersonById(Integer id) {
return entityManager.find(TestUser.class, id);
}
#Override
#Transactional
public List<TestUser> findAll() {
try {
return entityManager.createQuery("SELECT u FROM Users u ORDER BY p.id", TestUser.class).getResultList();
} finally {
entityManager.close();
}
}
}
TestWebApi.java
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
#Controller
#Path("test")
public interface TestWebApi {
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/")
public Response getUsers();
}
TestWebApiImpl.java
import java.util.List;
import javax.inject.Inject;
import javax.ws.rs.core.Response;
import com.test.testapp.model.TestUser;
import com.test.testapp.service.TestService;
import com.test.testapp.web.TestWebApi;
public class TestWebApiImpl implements TestWebApi {
#Inject
TestService testService;
#Override
public Response getUsers() {
List<TestUser> test = testService.getUsers();
return Response.ok().entity(test).build();
}
}
You are mixing JAX-RS annotations with Spring-MVC annotations. If you want to stick to JAX-RS then your code should look like this:
#Path("users")
#Component
public class UserController {
#Inject
UserService userService;
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/")
public List<User> getUsers() {
return userService.findAll();
}
#GET
#Path("/users/{name}")
#Produces(MediaType.APPLICATION_JSON)
public Response getUserByName(#NotNull #PathParam("name") String username) {
User user = userService.findByName(username);
return Response.ok().entity(user).build();
}
}
Currently, you have #RestController on your Class which makes it a Spring Rest Controller. So Spring scans all methods and finds '#RequestMapping("/user/{name}")' and '#RequestMapping("/users")' so it binds these methods to default GET operations and ignores completely #PathVariable annotation because it comes from JAX-RS not Spring.
Spring-MVC version of your code would be:
#RestController
#RequestMapping("/")
public class UserController {
#Inject
UserService userService;
#RequestMapping(value = "/users", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<User> getUsers() {
return userService.findAll();
}
#RequestMapping(value = "/users/{name}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public Response getUserByName(#NotNull #PathVariable("name") String username) {
User user = userService.findByName(username);
return Response.ok().entity(user).build();
}
}

Spring Hibernate get tuple by id

I am trying to create a simple "teacher" database. I was able to create a method for adding a new teacher to database, now I need to be able to get one and delete one by "Id". I would like some help, of how should I implement it. I have added following code files: AppConfig, Teacher (entity class), ITeacherDao (interface), TeacherDao(implementation of interface) and class with main method TimeStarApplication.
AppConfig
package com.superum.timestar;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.superum.timestar.dao.ITeacherDao;
import com.superum.timestar.dao.TeacherDao;
import com.superum.timestar.entity.Teacher;
#Configuration
#EnableTransactionManagement
public class AppConfig {
#Bean
public ITeacherDao teacherDao() {
return new TeacherDao();
}
#Bean
public HibernateTemplate hibernateTemplate() {
return new HibernateTemplate(sessionFactory());
}
#Bean
public SessionFactory sessionFactory() {
return new LocalSessionFactoryBuilder(getDataSource())
.addAnnotatedClasses(Teacher.class)
.buildSessionFactory();
}
#Bean
public DataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/time_star");
dataSource.setUsername("root");
dataSource.setPassword("password");
return dataSource;
}
#Bean
public HibernateTransactionManager hibTransMan(){
return new HibernateTransactionManager(sessionFactory());
}
}
Teacher
package com.superum.timestar.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="teachers")
public class Teacher {
#Id#GeneratedValue
#Column(name="t_id")
private int Id;
#Column(name="t_name")
private String name;
#Column(name="t_lastname")
private String lastname;
#Column(name="t_phone")
private String phone;
#Column(name="t_age")
private int age;
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
ITeacherDAO
package com.superum.timestar.dao;
public interface ITeacherDao {
public void addTeacher(String name, String lastname, String phone, int age);
// public void getTeacher(int id);
`` // public void deleteTeacher();
}
TeacherDao
package com.superum.timestar.dao;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import com.superum.timestar.entity.Teacher;
#Transactional
public class TeacherDao implements ITeacherDao{
#Autowired
private HibernateTemplate hibernateTemplate;
public void addTeacher(String name, String lastname, String phone, int age){
Teacher teacher = new Teacher();
teacher.setName(name);
teacher.setLastname(lastname);
teacher.setPhone(phone);
teacher.setAge(age);
hibernateTemplate.save(teacher);
}
// I need to create get by Id
// public void getTeacher(int Id){
//
// }
I hope the question is not entirely horrible.
}
ITeacherDAO
package com.superum.timestar.dao;
public interface ITeacherDao {
public void addTeacher(String name, String lastname, String phone, int age);
public Teacher getTeacher(int id); //Method to get the teacher by id
public void deleteTeacher(int id); //Method to delete the teacher by id
}
TeacherDao
package com.superum.timestar.dao;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import com.superum.timestar.entity.Teacher;
#Transactional
public class TeacherDao implements ITeacherDao{
#Autowired
private HibernateTemplate hibernateTemplate;
public void addTeacher(String name, String lastname, String phone, int age){
Teacher teacher = new Teacher();
teacher.setName(name);
teacher.setLastname(lastname);
teacher.setPhone(phone);
teacher.setAge(age);
hibernateTemplate.save(teacher);
}
public Teacher getTeacher(int id){
Teacher teacher = (Teacher)hibernateTemplate.get(Teacher.class, id);
return teacher;
}
public void deleteTeacher(int id){
Teacher teacher = (Teacher)hibernateTemplate.get(Teacher.class, id);
hibernateTemplate.delete(teacher);
}

SpringData: How Map AngularJS page with #RepositoryRestResource?

I follow this tutorial about Data Accessing:
http://spring.io/guides/gs/accessing-data-rest/
So, I have this structure
http://i.stack.imgur.com/wUnrx.png
"Project" is the Model
package Serveur;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Project {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private String mail;
private String password;
public long getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
And the interface "ProjectRepository", which implemented directly by the "#RepositoryRestResource" annotation
package Serveur;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
#RepositoryRestResource(collectionResourceRel = "jsonProjects", path = "jsonProjects")
public interface ProjectRepository extends CrudRepository<Project, Integer> {
List<Project> findById(#Param("name") String name);
}
The "Home Controller" contains a #RequestMapping Annotation and redirects the user to "index" page :
package Serveur;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class HomeController {
#RequestMapping("/")
public String index()
{
return "index";
}
}
But, when I connect to localhost:8080/ , the index page does not display but this:
{
_links: {
jsonProjects: {
href: "http://localhost:8080/jsonProjects{?page,size,sort}",
templated: true
}
}
}
The problem is that the #RepositoryRestResource annotation binds to "/". To fix your issue, edit Application.java and add this function:
#Override
protected void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
super.configureRepositoryRestConfiguration(config);
try {
config.setBaseUri(new URI("/api"));
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
Your HomeController will not bind to "/" and your API's will be available at "/api"
Here is the answer:
By default all Repository search function comes after search keyword. So in your case URL will be something like:
http://localhost:PORT/APP/jsonProjects/search/findById?name=NAME
See my working example and blog for the same:
http://sv-technical.blogspot.com/2015/11/spring-boot-and-repositoryrestresource.html
https://github.com/svermaji/Spring-boot-with-hibernate-no-controller
Hope this helps.

Resources