Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 21 days ago.
Improve this question
I've been trying to create a spring security logic to authorize users (inserted into my database) to do different things based on their roles (simple). I'm supposed to have ROLE_USER and ROLE_ADMIN, but I don't think any of them work. Please help. I'll try to put every bit of important code here (even the imports).
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.security.core.GrantedAuthority;
import com.vitoria.enums.RoleName;
#Entity
#Table(name = "TB_ROLE")
public class RoleModel implements GrantedAuthority, Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private UUID roleId;
#Enumerated(EnumType.STRING)
#Column(nullable = false, unique = true)
private RoleName roleName;
#Override
public String getAuthority() {
return this.roleName.toString();
}
public UUID getRoleId() {
return roleId;
}
public void setRoleId(UUID roleId) {
this.roleId = roleId;
}
public RoleName getRoleName() {
return roleName;
}
public void setRoleName(RoleName roleName) {
this.roleName = roleName;
}
}
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
#Entity
#Table(name = "TB_USER")
public class UserModel implements UserDetails, Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private UUID userId;
#Column(nullable = false, unique = true)
private String username;
#Column(nullable = false)
private String password;
#ManyToMany
#JoinTable(name = "TB_USERS_ROLES",
joinColumns = #JoinColumn(name = "user_id"),
inverseJoinColumns = #JoinColumn(name = "role_id"))
private List<RoleModel> roles;
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.roles;
}
#Override
public String getPassword() {
return this.password;
}
#Override
public String getUsername() {
return this.username;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
public UUID getUserId() {
return userId;
}
public void setUserId(UUID userId) {
this.userId = userId;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
}
public enum RoleName {
ROLE_ADMIN,
ROLE_USER;
}
import javax.transaction.Transactional;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.vitoria.models.UserModel;
import com.vitoria.repositories.UserRepository;
#Service
#Transactional
public class UserDetailsServiceImpl implements UserDetailsService {
final UserRepository userRepository;
public UserDetailsServiceImpl(UserRepository userRepository) {
this.userRepository = userRepository;
}
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserModel userModel = userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("User Not Found with username: " + username));
return new User(userModel.getUsername(), userModel.getPassword(), true, true, true,true, userModel.getAuthorities());
}
}
import org.springframework.data.jpa.repository.JpaRepository;
import com.vitoria.models.RoleModel;
public interface RoleRepository extends JpaRepository<RoleModel, Long> {
RoleModel findByRoleName(String roleName);
}
import java.util.Optional;
import java.util.UUID;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.vitoria.models.UserModel;
#Repository
public interface UserRepository extends JpaRepository<UserModel, UUID> {
Optional<UserModel> findByUsername(String username);
}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig {
#Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.httpBasic()
.and()
.authorizeHttpRequests()
.anyRequest().authenticated()
.and()
.csrf().disable();
return http.build();
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.vitoria.models.Flowers;
import com.vitoria.repositories.FlowersRepository;
#RestController
#CrossOrigin(origins = "*", maxAge = 3600)
#EnableAutoConfiguration
#RequestMapping("/flowers")
public class FlowersController {
#Autowired
private FlowersRepository repo;
#PreAuthorize("hasRole('ROLE_USER')")
#GetMapping
public ResponseEntity<List<Flowers>> findAll(){
List<Flowers> allFlowers=repo.findAll();
return ResponseEntity.ok().body(allFlowers);
}
#PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_USER')")
#PostMapping("/insert")
public ResponseEntity<Flowers> insert(#RequestBody Flowers flower){
Flowers entity=flower;
repo.save(entity);
return ResponseEntity.ok().body(entity);
}
#PreAuthorize("hasRole('ROLE_ADMIN')")
#DeleteMapping("/delete/{id}")
public ResponseEntity<Void> deleteById(#PathVariable Integer id){
repo.deleteById(id);
return ResponseEntity.noContent().build();
}
}
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.vitoria.models.UserModel;
import com.vitoria.repositories.UserRepository;
#RestController
#RequestMapping("/users")
public class UserController {
#Autowired
private UserRepository repo;
#PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_USER')")
#GetMapping
public ResponseEntity<List<UserModel>> findAll(){
List<UserModel> users=repo.findAll();
return ResponseEntity.ok().body(users);
}
#PreAuthorize("hasRole('ROLE_USER')")
#GetMapping("/{username}")
public ResponseEntity<Optional<UserModel>> findByUsername(#RequestParam("username")String username){
Optional<UserModel> user=repo.findByUsername(username);
return ResponseEntity.ok().body(user);
}
#PreAuthorize("hasRole('ROLE_ADMIN')")
#PostMapping("/save")
public ResponseEntity<UserModel> insert(#RequestBody UserModel user){
UserModel entity=user;
user.setPassword(passwordEncoder().encode(user.getPassword()));
repo.save(entity);
return ResponseEntity.ok().body(entity);
}
private PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
my database looks like this:
tb_user
tb_role
tb_users_roles
I think this is all.
Please keep in mind that when I try to make ->any<- request to any endpoint it comesback unauthorized. SO, I tried something else: taking off the role permission (using the #PreAuthorize("permitAll()")) of get all users and I still get 401 as return! Please please help me.
I have a spring controller that let's me sign in and supposed to return user details(roles, username) in response when entering correct credentials but instead only return the jwt token and username. Here's the api response:
{
"username": "adam",
"token": "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZGFtIiwicm9sZXMiOlsiUk9MRV9BRE1JTiJdLCJpYXQiOjE1NTcyMzUxMTMsImV4cCI6MTU1NzIzODcxM30.PksRTzgYu6r79KNmc4YDNXGqO1Ke63oOzzoPjURUY9k"
}
My controller:
package com.example.demo.controller;
import com.example.demo.domain.User;
import com.example.demo.repository.UserRepository;
import com.example.demo.security.jwt.JwtTokenProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
import static org.springframework.http.ResponseEntity.ok;
#RestController
#RequestMapping("/auth")
public class AuthController {
#Autowired
AuthenticationManager authenticationManager;
#Autowired
JwtTokenProvider jwtTokenProvider;
#Autowired
UserRepository users;
#PostMapping("/signin")
public ResponseEntity signin(#RequestBody User user) {
try {
String username = user.getUsername();
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, user.getPassword()));
String token = jwtTokenProvider.createToken(username, this.users.findByUsername(username).orElseThrow(() -> new UsernameNotFoundException("Username " + username + "not found")).getRoles());
Map<Object, Object> model = new HashMap<>();
model.put("username", username);
model.put("token", token);
model.put("roles", user.getRoles());
return ok(model);
} catch (AuthenticationException e) {
throw new BadCredentialsException("Invalid username/password supplied");
}
}
}
My entity:
package com.example.demo.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonSetter;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import static java.util.stream.Collectors.toList;
#Entity
#Table(name="users")
#Data
#Builder
#NoArgsConstructor
#AllArgsConstructor
public class User implements UserDetails {
private static final long serialVersionUID = 357523406648925755L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
Long id;
#NotEmpty
#Column(name="username")
private String username;
#Column(name="firstname")
private String firstName;
#Column(name="lastname")
private String lastName;
#NotEmpty
#Column(name="password")
private String password;
#Column(name = "email")
#NotEmpty()
private String email;
#Column(name = "enabled")
private boolean enabled;
#ElementCollection(fetch = FetchType.EAGER)
#Builder.Default
private List<String> roles = new ArrayList<>();
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.roles.stream().map(SimpleGrantedAuthority::new).collect(toList());
}
#JsonIgnore
#Override
public String getPassword() {
return this.password;
}
#JsonSetter
public void setPassword(String password) {
this.password = password;
}
#Override
public String getUsername() {
return this.username;
}
#JsonIgnore
#Override
public boolean isAccountNonExpired() {
return true;
}
#JsonIgnore
#Override
public boolean isAccountNonLocked() {
return true;
}
#JsonIgnore
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
}
My Custom UserDetailsService
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import br.com.fimd.entidades.Usuario;
import br.com.fimd.service.UsuarioService;
#Transactional(readOnly=true)
#Service("userDetailsServiceImpl")
public class UserDetailsServiceImpl implements UserDetailsService{
#Autowired
private UsuarioService usuarioService;
#Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
Usuario usuario = usuarioService.findUserByEmail(email);
if(usuario == null) {
throw new UsernameNotFoundException("Usuário nao encontrado.");
}
return new User(usuario.getEmail(), usuario.getSenha(), usuario.getAuthorities());
}
}
My Security Configuration
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
#Qualifier("userDetailsServiceImpl")
private UserDetailsService userDetailsService;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().disable().
csrf().disable().authorizeRequests()
.antMatchers("/home").permitAll()
.antMatchers("/public/**").permitAll()
.antMatchers("/private/**").hasRole("USER")
//.antMatchers("/admin*").access("hasRole('ROLE_ADMIN')")
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
//.addFilterBefore(new JWTAuthenticationFilter(),UsernamePasswordAuthenticationFilter.class)
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/assets/**");
}
#Bean
CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
return source;
}
}
My User Entity
import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#Entity
#Table(name = "usuarios")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = { "createdAt", "updatedAt" }, allowGetters = true)
public class Usuario implements UserDetails, Serializable{
private static final long serialVersionUID = 4038437690572999966L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_id")
private Long id;
#NotBlank
private String nome;
#NotBlank
private String email;
#NotBlank
private String senha;
#NotBlank
private String cpf;
#Column
private boolean ativo;
#ManyToMany
#JoinTable(name="perfil_usuario", joinColumns=
{#JoinColumn(name="user_id")}, inverseJoinColumns=
{#JoinColumn(name="tipo_perfil")})
private Set<Perfil> perfis = new HashSet<>();
#OneToMany(mappedBy = "usuario", cascade = CascadeType.ALL)
private List<Investimento> investimentos;
#OneToMany(mappedBy = "usuario", cascade = CascadeType.ALL)
private List<Extrato> extratos;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
public boolean isAtivo() {
return ativo;
}
public void setAtivo(boolean ativo) {
this.ativo = ativo;
}
public Set<Perfil> getPerfis() {
return perfis;
}
public void setPerfis(Set<Perfil> perfis) {
this.perfis = perfis;
}
public List<Investimento> getInvestimentos() {
return investimentos;
}
public void setInvestimentos(List<Investimento> investimentos) {
this.investimentos = investimentos;
}
public List<Extrato> getExtratos() {
return extratos;
}
public void setExtratos(List<Extrato> extratos) {
this.extratos = extratos;
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.perfis;
}
#Override
public String getPassword() {
return this.senha;
}
#Override
public String getUsername() {
return this.email;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
}
My Perfil Entity
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import org.springframework.security.core.GrantedAuthority;
#Entity
public class Perfil implements GrantedAuthority{
private static final long serialVersionUID = 1L;
#Id
private String tipoPerfil;
#ManyToMany(mappedBy="perfis")
private List<Usuario> usuarios;
public List<Usuario> getUsuarios() {
return usuarios;
}
public void setUsuarios(List<Usuario> usuarios) {
this.usuarios = usuarios;
}
public String getTipoPerfil() {
return tipoPerfil;
}
public void setTipoPerfil(String tipoPerfil) {
this.tipoPerfil = tipoPerfil;
}
#Override
public String getAuthority() {
return this.tipoPerfil;
}
}
My Spring Filter Initializer
import org.springframework.context.annotation.Configuration;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
#Configuration
public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}
When i call a "/private/service" my loadUserByUsername not being called never, my application ever send me a 403 forbidden, access denied.
Why that?
I tried a lot of tutorials from internet and my code seems to be correct, i'm using spring starter 2.0.5.RELEASE
I already tried to call the userDetailsService from a #Bean method in SecurityConfiguration
Your security configuration is not complete, you must provide as well the login information:
.formLogin()
.loginPage("/login.html")
.defaultSuccessUrl("/home")
.failureUrl("/login.html?error=true")
Otherwise all your requests will be unauthorized. Please see this tutorial:
https://www.baeldung.com/spring-security-login
Your Custom UserDetails service will be called only when the application will receive a POST to login url with username and password, otherwise it will not have what data to authorize.
package hibernate2;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="User1_Details")
public class UserDetails {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int userId;
private String userName;
#OneToMany(mappedBy="user")
private Collection<Vehicle> vehicle = new ArrayList<Vehicle>();
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Collection<Vehicle> getVehicle() {
return vehicle;
}
public void setVehicle(Collection<Vehicle> vehicle) {
this.vehicle = vehicle;
}
}
And i created a vehicle class
package hibernate2;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#Entity
public class Vehicle {
#Id
#GeneratedValue(strategy =GenerationType.AUTO)
private int vehicle_Id;
private String vehicle_Name;
#ManyToOne
#JoinColumn(name="USER_ID")
private UserDetails user;
public UserDetails getUser() {
return user;
}
public void setUser(UserDetails user) {
this.user = user;
}
public int getVehicle_Id() {
return vehicle_Id;
}
public void setVehicle_Id(int vehicle_Id) {
this.vehicle_Id = vehicle_Id;
}
public String getVehicle_Name() {
return vehicle_Name;
}
public void setVehicle_Name(String vehicle_Name) {
this.vehicle_Name = vehicle_Name;
}
}
And The Following were my hiernate code or DAO class
package hibernate2;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Hibernate {
public static void main(String[] args) {
UserDetails user = new UserDetails();
user.setUserName("Ranjith");
Vehicle vehicle = new Vehicle();
vehicle.setVehicle_Name("Car");
Vehicle vehicle2 = new Vehicle();
vehicle2.setVehicle_Name("Jeep");
user.getVehicle().add(vehicle);
user.getVehicle().add(vehicle2);
vehicle.setUser(user);
vehicle2.setUser(user);
SessionFactory sessionfactory = new
Configuration().configure().buildSessionFactory();
Session session = sessionfactory.openSession();
session.beginTransaction();
session.save(user);
session.save(vehicle);
session.save(vehicle2);
session.getTransaction().commit();
session.close();
}
}
After Running this above class i get the following error
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not execute statement
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'USER_ID' in 'field list'
I have the following simple spring mvc 4 application with JPA 2.0 using java config
package com.somecompany.class;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#Configuration
#EnableWebMvc
#Import({JPAConfig.class, BeanConfig.class})
#ComponentScan("com.*")
public class AppConfig {
public InternalResourceViewResolver setupInternalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}
The AppConfig.java class contains the application configuration logic
package com.somecompany.class;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver;
import org.springframework.instrument.classloading.LoadTimeWeaver;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackages="com.somecompany.model.*")
public class JPAConfig {
#Bean
public JpaTransactionManager jpaTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager(getEntityManagerFactoryBean().getObject());
return transactionManager;
}
#Bean
public LocalContainerEntityManagerFactoryBean getEntityManagerFactoryBean() {
LocalContainerEntityManagerFactoryBean containerEntityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
containerEntityManagerFactoryBean.setDataSource(getDataSource());
containerEntityManagerFactoryBean.setPersistenceUnitName("pmd-web");
LoadTimeWeaver loadTimeWeaver = new InstrumentationLoadTimeWeaver();
containerEntityManagerFactoryBean.setLoadTimeWeaver(loadTimeWeaver);
return containerEntityManagerFactoryBean;
}
#Bean
public DataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/somedatabase");
dataSource.setUsername("someuser");
dataSource.setPassword("somepassword");
return dataSource;
}
}
The JPAConfig.java contains the JPA configuration details
package com.somecompany.class;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class WebAppInitializer implements WebApplicationInitializer{
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext webApplicationContext = new AnnotationConfigWebApplicationContext();
webApplicationContext.register(AppConfig.class);
webApplicationContext.setServletContext(servletContext);
webApplicationContext.refresh();
Dynamic dynamic = servletContext.addServlet("dispatcher", new DispatcherServlet(webApplicationContext));
dynamic.addMapping("/");
dynamic.setLoadOnStartup(1);
}
}
WebAppInitializer.java contains the logic for initializing the web app
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="pmd-web">
<description>project metrics dashboard</description>
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
</properties>
</persistence-unit>
</persistence>
persistence.xml is as above.
package com.somecompany.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.RestController;
import com.somecompany.VO.LoginVO;
import com.somecompany.loginService.LoginService;
#RestController
public class LoginController {
#Autowired
LoginService loginService;
#RequestMapping(value = "/login", method = RequestMethod.POST)
public ResponseEntity<LoginVO> authenticateUser(#RequestBody LoginVO loginVO) {
loginVO = loginService.authenticateUser(loginVO);
if (loginVO.getStatus()) {
return new ResponseEntity<LoginVO>(loginVO, HttpStatus.OK);
} else {
return new ResponseEntity<LoginVO>(loginVO, HttpStatus.FORBIDDEN);
}
}
}
The Restful controller class is as above
package com.somecompany.loginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import somecompany.VO.LoginVO;
import somecompany.mapper.LoginMapper;
import somecompany.model.PmdUser;
import com.somecompany.LoginDAO;
#Service
public class LoginService {
#Autowired
LoginDAO loginDAO;
#Autowired
LoginMapper loginMapper;
#Transactional
public LoginVO authenticateUser(LoginVO loginVO) {
PmdUser pmdUser = loginMapper.getpmdUserFromLoginVO(loginVO);
LoginVO loginVOFromDB = loginDAO.authenticateUser(pmdUser);
if (loginVO.getUserName().equalsIgnoreCase(loginVOFromDB.getUserName())) {
loginVO.setStatus(true);
}
return loginVO;
}
}
The service class is as above
package com.somecompany.loginDAO;
import java.util.List;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.somecompany.VO.LoginVO;
import com.somecompany.baseDAO.BaseDao;
import com.somecompany.mapper.LoginMapper;
import com.somecompany.model.PmdUser;
#Repository
public class LoginDAO extends BaseDao {
#Autowired
LoginMapper loginMapper;
public LoginVO authenticateUser(PmdUser pmdUser) {
PmdUser user = null;
LoginVO loginVO = null;
List<PmdUser> pmdUsers = findByNamedQuery("findByUsername", pmdUser.getUserName());
if (pmdUsers.size() > 0) {
user = pmdUsers.get(0);
loginVO = loginMapper.getLoginVOFromPmdUser(user);
}
return loginVO;
}
}
The loginDAO.java class is as above
package com.somecompany.baseDAO;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceException;
import javax.persistence.Query;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.springframework.stereotype.Repository;
#Repository
public abstract class BaseDao<E, K> {
/** The entity manager. */
#PersistenceContext(unitName = "pmd-web")
protected EntityManager entityManager;
/**
* Gets the entity manager.
*
* #return the entity manager
*/
public EntityManager getEntityManager() {
return entityManager;
}
/** The entity class. */
protected Class<E> entityClass;
/**
* Instantiates a new base DAO.
*/
#SuppressWarnings("unchecked")
public BaseDao() {
ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
this.entityClass = (Class<E>) genericSuperclass.getActualTypeArguments()[0];
}
public List<E> findByNamedQuery(final String name, Object... params) {
javax.persistence.Query query = getEntityManager().createNamedQuery(name);
for (int i = 0; i < params.length; i++) {
query.setParameter(i + 1, params[i]);
}
final List<E> result = (List<E>) query.getResultList();
return result;
}
}
On deploying the application war and execution the REST service i get the exception
Caused by: java.lang.IllegalArgumentException: No query defined for that name [findByUsername]
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.buildQueryFromName(AbstractEntityManagerImpl.java:788) [hibernate-entitymanager-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createNamedQuery(AbstractEntityManagerImpl.java:767) [hibernate-entitymanager-4.3.7.Final.jar:4.3.7.Final]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.8.0_65]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) [rt.jar:1.8.0_65]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.8.0_65]
at java.lang.reflect.Method.invoke(Method.java:497) [rt.jar:1.8.0_65]
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:294) [spring-orm-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at com.sun.proxy.$Proxy92.createNamedQuery(Unknown Source)
at com.somecompany.baseDAO.BaseDao.findByNamedQuery(BaseDao.java:184) [classes:]
at com.somecompany.loginDAO.LoginDAO.authenticateUser(LoginDAO.java:26) [classes:]
at com.somecompany.loginDAO.LoginDAO$$FastClassBySpringCGLIB$$1909bedd.invoke(<generated>) [classes:]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) [spring-core-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:651) [spring-aop-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at com.somecompany.loginDAO.LoginDAO$$EnhancerBySpringCGLIB$$45d26c87.authenticateUser(<generated>) [classes:]
at com.somecompany.loginService.LoginService.authenticateUser(LoginService.java:25) [classes:]
at com.somecompany.loginService.LoginService$$FastClassBySpringCGLIB$$3de2163d.invoke(<generated>) [classes:]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) [spring-core-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720) [spring-aop-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) [spring-aop-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) [spring-tx-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281) [spring-tx-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) [spring-tx-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) [spring-aop-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655) [spring-aop-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at com.somecompany.loginService.LoginService$$EnhancerBySpringCGLIB$$912637e7.authenticateUser(<generated>) [classes:]
at com.somecompany.loginController.LoginController.authenticateUser(LoginController.java:22) [classes:]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.8.0_65]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) [rt.jar:1.8.0_65]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.8.0_65]
at java.lang.reflect.Method.invoke(Method.java:497) [rt.jar:1.8.0_65]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) [spring-web-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) [spring-web-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) [spring-webmvc-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:817) [spring-webmvc-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:731) [spring-webmvc-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) [spring-webmvc-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959) [spring-webmvc-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) [spring-webmvc-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:968) [spring-webmvc-4.2.5.RELEASE.jar:4.2.5.RELEASE]
... 30 more
But i have the named query on the entity as below
package com.somecompany.model;
import static javax.persistence.GenerationType.IDENTITY;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;
import org.springframework.stereotype.Component;
#Entity
#Table(name = "pmd_user", catalog = "pmd", uniqueConstraints = {
#UniqueConstraint(columnNames = { "CUSTOMER_ID", "USER_NAME" }),
#UniqueConstraint(columnNames = "EMAIL_ADDRESS") })
#Component
#NamedQuery(name="findByUsername", query="SELECT u FROM PmdUser u WHERE u.userName = ?1")
public class PmdUser implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Long userId;
private PmdCustomer pmdCustomer;
private String userName;
private String emailAddress;
private Long phone;
private String firstName;
private String lastName;
private String password;
private Boolean passwordChangeRequired;
private Date lastPasswordChange;
private Long challengeQuestionId;
private String challengeAnswer;
private Boolean deactivated;
private Boolean deleted;
private Boolean isPreview;
private Boolean receiveEmail;
private Boolean isGuest;
private Boolean newsletter;
private String emailFormat;
private Date dateOfLastLogon;
private Long visits;
private String note;
private Long createdIp;
private Long updatedIp;
private Date dateCreated;
private Date dateUpdated;
private Long createdBy;
private Long updatedBy;
private List<PmdUserRole> pmdUserRoles = new ArrayList<PmdUserRole>(0);
public PmdUser() {
}
public PmdUser(String userName, String emailAddress) {
this.userName = userName;
this.emailAddress = emailAddress;
}
public PmdUser(PmdCustomer pmdCustomer, String userName, String emailAddress, Long phone, String firstName,
String lastName, String password, Boolean passwordChangeRequired, Date lastPasswordChange,
Long challengeQuestionId, String challengeAnswer, Boolean deactivated, Boolean deleted, Boolean isPreview,
Boolean receiveEmail, Boolean isGuest, Boolean newsletter, String emailFormat, Date dateOfLastLogon,
Long visits, String note, Long createdIp, Long updatedIp, Date dateCreated, Date dateUpdated,
Long createdBy, Long updatedBy, List<PmdUserRole> pmdUserRoles) {
this.pmdCustomer = pmdCustomer;
this.userName = userName;
this.emailAddress = emailAddress;
this.phone = phone;
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
this.passwordChangeRequired = passwordChangeRequired;
this.lastPasswordChange = lastPasswordChange;
this.challengeQuestionId = challengeQuestionId;
this.challengeAnswer = challengeAnswer;
this.deactivated = deactivated;
this.deleted = deleted;
this.isPreview = isPreview;
this.receiveEmail = receiveEmail;
this.isGuest = isGuest;
this.newsletter = newsletter;
this.emailFormat = emailFormat;
this.dateOfLastLogon = dateOfLastLogon;
this.visits = visits;
this.note = note;
this.createdIp = createdIp;
this.updatedIp = updatedIp;
this.dateCreated = dateCreated;
this.dateUpdated = dateUpdated;
this.createdBy = createdBy;
this.updatedBy = updatedBy;
this.pmdUserRoles = pmdUserRoles;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "USER_ID", unique = true, nullable = false)
public Long getUserId() {
return this.userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "CUSTOMER_ID")
public PmdCustomer getPmdCustomer() {
return this.pmdCustomer;
}
public void setPmdCustomer(PmdCustomer pmdCustomer) {
this.pmdCustomer = pmdCustomer;
}
#Column(name = "USER_NAME", nullable = false, length = 32)
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
#Column(name = "EMAIL_ADDRESS", unique = true, nullable = false, length = 128)
public String getEmailAddress() {
return this.emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
#Column(name = "PHONE")
public Long getPhone() {
return this.phone;
}
public void setPhone(Long phone) {
this.phone = phone;
}
#Column(name = "FIRST_NAME", length = 32)
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "LAST_NAME", length = 32)
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Column(name = "PASSWORD", length = 128)
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name = "PASSWORD_CHANGE_REQUIRED")
public Boolean getPasswordChangeRequired() {
return this.passwordChangeRequired;
}
public void setPasswordChangeRequired(Boolean passwordChangeRequired) {
this.passwordChangeRequired = passwordChangeRequired;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "LAST_PASSWORD_CHANGE", length = 19)
public Date getLastPasswordChange() {
return this.lastPasswordChange;
}
public void setLastPasswordChange(Date lastPasswordChange) {
this.lastPasswordChange = lastPasswordChange;
}
#Column(name = "CHALLENGE_QUESTION_ID")
public Long getChallengeQuestionId() {
return this.challengeQuestionId;
}
public void setChallengeQuestionId(Long challengeQuestionId) {
this.challengeQuestionId = challengeQuestionId;
}
#Column(name = "CHALLENGE_ANSWER", length = 128)
public String getChallengeAnswer() {
return this.challengeAnswer;
}
public void setChallengeAnswer(String challengeAnswer) {
this.challengeAnswer = challengeAnswer;
}
#Column(name = "DEACTIVATED")
public Boolean getDeactivated() {
return this.deactivated;
}
public void setDeactivated(Boolean deactivated) {
this.deactivated = deactivated;
}
#Column(name = "DELETED")
public Boolean getDeleted() {
return this.deleted;
}
public void setDeleted(Boolean deleted) {
this.deleted = deleted;
}
#Column(name = "IS_PREVIEW")
public Boolean getIsPreview() {
return this.isPreview;
}
public void setIsPreview(Boolean isPreview) {
this.isPreview = isPreview;
}
#Column(name = "RECEIVE_EMAIL")
public Boolean getReceiveEmail() {
return this.receiveEmail;
}
public void setReceiveEmail(Boolean receiveEmail) {
this.receiveEmail = receiveEmail;
}
#Column(name = "IS_GUEST")
public Boolean getIsGuest() {
return this.isGuest;
}
public void setIsGuest(Boolean isGuest) {
this.isGuest = isGuest;
}
#Column(name = "NEWSLETTER")
public Boolean getNewsletter() {
return this.newsletter;
}
public void setNewsletter(Boolean newsletter) {
this.newsletter = newsletter;
}
#Column(name = "EMAIL_FORMAT", length = 4)
public String getEmailFormat() {
return this.emailFormat;
}
public void setEmailFormat(String emailFormat) {
this.emailFormat = emailFormat;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "DATE_OF_LAST_LOGON", length = 19)
public Date getDateOfLastLogon() {
return this.dateOfLastLogon;
}
public void setDateOfLastLogon(Date dateOfLastLogon) {
this.dateOfLastLogon = dateOfLastLogon;
}
#Column(name = "VISITS")
public Long getVisits() {
return this.visits;
}
public void setVisits(Long visits) {
this.visits = visits;
}
#Column(name = "NOTE", length = 65535)
public String getNote() {
return this.note;
}
public void setNote(String note) {
this.note = note;
}
#Column(name = "CREATED_IP")
public Long getCreatedIp() {
return this.createdIp;
}
public void setCreatedIp(Long createdIp) {
this.createdIp = createdIp;
}
#Column(name = "UPDATED_IP")
public Long getUpdatedIp() {
return this.updatedIp;
}
public void setUpdatedIp(Long updatedIp) {
this.updatedIp = updatedIp;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "DATE_CREATED", length = 19)
public Date getDateCreated() {
return this.dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "DATE_UPDATED", length = 19)
public Date getDateUpdated() {
return this.dateUpdated;
}
public void setDateUpdated(Date dateUpdated) {
this.dateUpdated = dateUpdated;
}
#Column(name = "CREATED_BY")
public Long getCreatedBy() {
return this.createdBy;
}
public void setCreatedBy(Long createdBy) {
this.createdBy = createdBy;
}
#Column(name = "UPDATED_BY")
public Long getUpdatedBy() {
return this.updatedBy;
}
public void setUpdatedBy(Long updatedBy) {
this.updatedBy = updatedBy;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pmdUser")
public List<PmdUserRole> getPmdUserRoles() {
return this.pmdUserRoles;
}
public void setPmdUserRoles(List<PmdUserRole> pmdUserRoles) {
this.pmdUserRoles = pmdUserRoles;
}
#Override
public String toString() {
return "PmdUser [userId=" + userId + ", userName=" + userName + ", emailAddress=" + emailAddress
+ ", firstName=" + firstName + ", lastName=" + lastName + "]";
}
}
I suspect this is due to an integration issue with spring and JPA as the same query works fine in a unit test.
Has anybody faced this issue before ? or Is my JPA configuration not complete ?
Refer to your persistence xml location :
containerEntityManagerFactoryBean.setPersistenceXmlLocation("classpath:...");
Refer to your entities either from persistence xml OR
containerEntityManagerFactoryBean.setPackagesToScan("com.somecomany.model");
And you are configuring repositories from the wrong location, change :
#EnableJpaRepositories(basePackages="com.somecompany.model.*")
to :
#EnableJpaRepositories(basePackages="com.somecompany")
The issue was with the class deceleration in the Persistence.xml file previously the deceleration was as below
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="pmd-web">
<description>project metrics dashboard</description>
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
</properties>
</persistence-unit>
and had to change it to have the class declarations
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="pmd-web">
<class>com.somecompany.model.PmdCustomer</class>
<class>com.somecompany.model.CustomerModule</class>
<class>com.somecompany.model.Modules</class>
<class>com.somecompany.model.Project</class>
<class>com.somecompany.model.ProjectRelease</class>
<class>com.somecompany.model.ProjectSprint</class>
<class>com.somecompany.model.Role</class>
<class>com.somecompany.model.User</class>
<class>com.somecompany.model.UserRole</class>
</persistence-unit>