I am using spring security to login and logout, eveything works fine.
I can get username from logged user fine, however i need userID,
I would like to know how can i get user as an object from logged in user or how could i get userID
#RequestMapping("/contato")
public String contato(Model model, Principal principal ){
String userName = principal.getName();
model.addAttribute("userName",userName);
System.out.println(userName);
return "contato";
}
Bean
import java.sql.Date;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;
public class Users {
private int user_id;
#NotBlank
#Size(min=1, max=100, message="Name must be between 1 and 100 characters")
private String firstname;
#NotBlank
private String surname;
#NotNull
private Date dob;
#NotBlank
#Email
private String username;
#NotBlank
private String telephone;
#NotBlank
private String address;
#NotBlank
private String city;
#NotBlank
private String country;
#NotBlank
private String postcode;
#NotBlank
#Size(min=6, message="Password must be have more than 6 characters")
private String password;
private boolean enabled = false;
private String authority;
public Users() {
}
public Users(int user_id, String firstname, String surname, Date dob, String username, String telephone,
String address, String city, String country, String postcode, String password, boolean enabled,
String authority) {
super();
this.user_id = user_id;
this.firstname = firstname;
this.surname = surname;
this.dob = dob;
this.username = username;
this.telephone = telephone;
this.address = address;
this.city = city;
this.country = country;
this.postcode = postcode;
this.password = password;
this.enabled = enabled;
this.authority = authority;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
}
Can anyone please help me to get user id from logged user
I have also tried using
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Users user =(Users)authentication.getPrincipal();
but it still did not work
The simplest approach would be to leverage the UserDetails and UserDetailsService interfaces.
Write a simple UserDetailsService:
#Service
public class CustomUserDetailsService implements UserDetailsService {
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return findUserByUsername(username); //load the user from somewhere (e.g. Database)
}
}
Have your Users class implement the UserDetails interface:
public class Users implements UserDetails {
private String username;
private String userId;
private String password;
private String role;
public Users(String username, String userId, String password, String role) {
this.username = username;
this.userId = userId;
this.password = password;
this.role = role;
}
//...
}
Finally, when you call this static method you'll receive the Users object from which you can extract the userId:
Users user = (Users) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Related
I'm trying to set security roles in my Spring Boot application.
If I use in memory users the roles work. My code looks as folows:
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// add users for in memory authentication
UserBuilder users = User.withDefaultPasswordEncoder();
auth.inMemoryAuthentication()
.withUser(users.username("paul").password("test123").roles("MEMBER", "ADMIN"))
.withUser(users.username("sandra").password("test123").roles("MEMBER", "ADMIN"))
.withUser(users.username("matthew").password("test123").roles("MEMBER"));
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/users/list").hasAnyRole("MEMBER", "ADMIN")
.antMatchers("/events/list").hasAnyRole("MEMBER", "ADMIN")
.antMatchers("/events/showFormForAdd").hasRole("ADMIN")
.antMatchers("/events/listEventAttendeeDetails*").hasRole("ADMIN")
.antMatchers("/resources/**").permitAll()
.and()
.formLogin()
.loginPage("/showMyLoginPage")
.loginProcessingUrl("/authenticateTheUser")
.permitAll();
}
If I use database authentication for configure() the user is not authorised to access any pages. My database method looks like this:
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
As The roles work for in memory and not database I thing the configure(HttpSecurity http) must work fine. I suspect there is some issue getting my roles. My User and Authority(roles) models are as follows:
#Entity
#Table(name="users")
public class User {
public static final PasswordEncoder PASSWORD_ENCODER = new BCryptPasswordEncoder();
#OneToMany(mappedBy="user",
cascade={CascadeType.PERSIST, CascadeType.MERGE,
CascadeType.DETACH, CascadeType.REFRESH,
CascadeType.REMOVE})
private List<Authority> authorities;
// define fields
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="first_name")
private String firstName;
#Column(name="last_name")
private String lastName;
#Column(name="gender")
private String gender;
#DateTimeFormat(pattern="yyyy-MM-dd")
#Column(name="birth_date")
private LocalDate birthDate;
#Column(name="address_line1")
private String addressLine1;
#Column(name="address_line2")
private String addressLine2;
#Column(name="town")
private String town;
#Column(name="county")
private String county;
#Column(name="country")
private String country;
#Column(name="postcode")
private String postcode;
#Column(name="email")
private String email;
#Column(name="phone")
private String phone;
#Column(name="mobile")
private String mobile;
#Column(name="password")
private #JsonIgnore String password;
#Column(name="enabled")
private int enabled;
// define constructors
public User() {
}
public User(List<Authority> authorities, int id, String firstName, String lastName, String gender, LocalDate birthDate,
String addressLine1, String addressLine2, String town, String county, String country, String postcode,
String email, String phone, String mobile, String password, int enabled) {
this.authorities = authorities;
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.gender = gender;
this.birthDate = birthDate;
this.addressLine1 = addressLine1;
this.addressLine2 = addressLine2;
this.town = town;
this.county = county;
this.country = country;
this.postcode = postcode;
this.email = email;
this.phone = phone;
this.mobile = mobile;
this.password = password;
this.enabled = enabled;
}
public List<Authority> getAuthorities() {
return authorities;
}
public void setAuthorities(List<Authority> authorities) {
this.authorities = authorities;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public LocalDate getBirthDate() {
return birthDate;
}
public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getTown() {
return town;
}
public void setTown(String town) {
this.town = town;
}
public String getCounty() {
return county;
}
public void setCounty(String county) {
this.county = county;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = PASSWORD_ENCODER.encode(password);
}
public int getEnabled() {
return enabled;
}
public void setEnabled(int enabled) {
this.enabled = enabled;
}
}
#Entity
#Table(name="authorities")
public class Authority {
#ManyToOne(cascade= {CascadeType.PERSIST, CascadeType.MERGE,
CascadeType.DETACH, CascadeType.REFRESH})
#JoinColumn(name="email")
private User user;
#Id
#Column(name="id")
private String email;
#Column(name="authority")
private String authority;
public Authority() {
}
public Authority(User user, String email, String authority) {
this.user = user;
this.email = email;
this.authority = authority;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
}
This is the service I'm using to authenticate:
#Service
public class UserDetailsServiceImpl implements UserDetailsService {
#Autowired private UserRepository userRepository = null;
#Override
#Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
org.springframework.security.core.userdetails.User user = null;
try {
Optional<User> optional = userRepository.findByEmail(username);
HashSet<GrantedAuthority> set = new HashSet<>();
/*
* Add SimpleGrantedAuthority to set as appropriate
*/
user = new org.springframework.security.core.userdetails.User(username, optional.get().getPassword(), set);
} catch (UsernameNotFoundException exception) {
throw exception;
} catch (Exception exception) {
throw new UsernameNotFoundException(username);
}
return user;
}
}
The Authorities are inserted into the DB as follows:
INSERT INTO `authorities`
VALUES
('john','ROLE_MEMBER'),
('mary','ROLE_MEMBER'),
('mary','ROLE_MANAGER'),
('susan','ROLE_MEMBER'),
('susan','ROLE_ADMIN');
I put some logging around UserDetailsServiceImpl. As you can see, no authorities are granted.
2020-10-21 17:02:17.612 INFO 20363 --- [nio-8080-exec-4] c.p.clubmanager.aspect.LoggingAspect : =====> in #Before: Calling method: UserDetailsServiceImpl.loadUserByUsername(..)
2020-10-21 17:02:17.613 INFO 20363 --- [nio-8080-exec-4] c.p.clubmanager.aspect.LoggingAspect : =====> argument: Paul_carron#hotmail.com
2020-10-21 17:02:17.619 INFO 20363 --- [nio-8080-exec-4] c.p.clubmanager.aspect.LoggingAspect : =====> in #AfterReturning: from method: UserDetailsServiceImpl.loadUserByUsername(..)
2020-10-21 17:02:17.619 INFO 20363 --- [nio-8080-exec-4] c.p.clubmanager.aspect.LoggingAspect : =====> result: org.springframework.security.core.userdetails.User#eefb770b: Username: Paul_carron#hotmail.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; **Not granted any authorities**
Is there anything I've done wrong, or may be missing in terms of getting my roles?
In UserDetailsServiceImpl it seems that you are setting Roles/Authority passing only new HashSet<>(). You can try this:
try {
Optional<User> optional = userRepository.findByEmail(username);
List<SimpleGrantedAuthority> authorities = set = new ArrayList<>();
if(optional.isPresent()) {
authorities = optional.get().getAuthorities().stream()
.map(role -> new SimpleGrantedAuthority("ROLE_" + role.getName()))
.collect(Collectors.toList()))
}
user = new org.springframework.security.core.userdetails.User(username, optional.get().getPassword(), authorities);
} catch (UsernameNotFoundException exception) {
throw exception;
} catch (Exception exception) {
throw new UsernameNotFoundException(username);
}
I am having trouble understanding why my userRepository is returning null even when there is a record like it in my table. I tried doing it with my demo codes and it works but when I try doing it with user Authentication it does not work.
Security Services
#Path("/securityservice")
public class SecurityServices {
private UserRepository userRepo;
// http://localhost:8990/login/securityservice/security
#GET
#Path("security")
#Produces(MediaType.APPLICATION_JSON)
public Response getOrderById(#QueryParam("orderId") int orderID,
#HeaderParam("Authorization") String authString) throws JSONException {
JSONObject json = new JSONObject();
if (isUserAuthenticated(authString)) {
json.put("INFO", "Authorized User!");
return Response.status(200)
.entity(json.toString())
.type(MediaType.APPLICATION_JSON)
.build();
} else {
json.put("ERROR", "Unauthorized User!");
return Response.status(403)
.entity(json.toString())
.type(MediaType.APPLICATION_JSON)
.build();
}
}
private boolean isUserAuthenticated(String authString) {
//authString = Basic 3hfjdksiwoeriounf
String[] authParts = authString.split("\\s+");
//authParts[0] = Basic
//authParts[1] = 3hfjdksiwoeriounf
String authInfo = authParts[1];
byte[] bytes = Base64.getDecoder().decode(authInfo);
String decodedAuth = new String(bytes);
// decodedAuth = dj:1234
String[] credentials = decodedAuth.split(":");
//credentials[0]=dj
//credentials[1]=1234
System.out.println("HELLO"+credentials[0]);
System.out.println("HELLO"+credentials[1]);
User user = userRepo.findByUsername(credentials[0]); //this line returns null
if (user != null) {
return true;
} else {
return false;
}
}
User class (Getters and setters for the JPA Repo)
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name="firstname")
private String firstName;
#Column(name="lastname")
private String lastName;
private String password;
private String username;
#Column(name="accesstype")
private String accessType;
public User() {
super();
}
public User(String firstName, String lastName, String password,
String username, String accessType) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
this.username = username;
this.accessType = accessType;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAccessType() {
return accessType;
}
public void setAccessType(String accessType) {
this.accessType = accessType;
}
}
When I use Retrofit to call Login API, I face a little problem: the response body is null. And the the Response Message contains this message:
"Response{protocol=http/1.1, code=200, message=OK, url=http://gagron.com/api/login.php}"
class interface
public interface getLoginDataService {
public String BaseURL = Constants.mBase_Url;
#FormUrlEncoded
#POST(Constants.mLogin)
Call<UserModel> login(#Field("email") String email, #Field("password") String password);
}
Login Method
public void loginConnector(String email, String password) {
Retrofit retrofit = new Retrofit.Builder().baseUrl(Connectors.getLoginDataService.BaseURL)
.addConverterFactory(GsonConverterFactory.create(new Gson())).build();
Connectors.getLoginDataService getLoginDataService = retrofit.create(Connectors.getLoginDataService.class);
getLoginDataService.login(email, password).enqueue(new Callback<UserModel>() {
#Override
public void onResponse(Call<UserModel> call, Response<UserModel> response) {
UserModel model= response.body();
Log.i("Successmsg", "" + response.toString());
Log.i("Successmsg1", "" + model.getFirstName());
;
}
#Override
public void onFailure(Call<UserModel> call, Throwable t) {
Log.i("Errormsg", t.getMessage() + "");
}
});
}
And finally user Model which consider the Response.
Class UserModel
public class UserModel {
#SerializedName("FirstName")
#Expose
private String firstName;
#SerializedName("LastName")
#Expose
private String lastName;
#SerializedName("Email")
#Expose
private String email;
#SerializedName("Mobile")
#Expose
private String mobile;
#SerializedName("Gender")
#Expose
private String gender;
#SerializedName("Password")
#Expose
private String password;
#SerializedName("Salt")
#Expose
private String salt;
#SerializedName("Address")
#Expose
private String address;
#SerializedName("PostalCode")
#Expose
private String postalCode;
#SerializedName("DateOfBirth")
#Expose
private String dateOfBirth;
#SerializedName("role")
#Expose
private String role;
#SerializedName("newsletter")
#Expose
private String newsletter;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getNewsletter() {
return newsletter;
}
public void setNewsletter(String newsletter) {
this.newsletter = newsletter;
}
}
In your loginConnector method you can use call.request().url() to display/debug the request URL you are calling.
Additionally you can use a REST client to make a POST request to that URL and check the difference between both responses. Nowadays Insomnia REST client is a good option for that.
I hope that may help you.
inside your onResponse add
if (response.isSuccessful()) {
if (response.body() != null) {UserModel model= response.body();
Log.i("Successmsg", "" + response.toString());
Log.i("Successmsg1", "" + model.getFirstName());
}
} else {
Toast.makeText(LoginSM.this, getString(R.string.wrongdata), Toast.LENGTH_SHORT).show();
}
i am a newbie to java.I am trying to create a library system.
Which classes should be abstract? do i need more classes?
Yes you need many classes, Your classes should look like this :
class Person{
//attributes, getters and setters
}
class User extends Person{
//attributes, getters and setters
}
class Members extends Person{
}
class Librarian extends Person{
}
class Book{
//attributes, getters and setters
}
public class Person {
private String FirstName;
private String LastName;
private String Gender;
private String Contact;
private String Email;
public Person() {
}
public Person(String FirstName, String LastName, String Gender, String Contact, String Email) {
this.FirstName = FirstName;
this.LastName = LastName;
this.Gender = Gender;
this.Contact = Contact;
this.Email = Email;
}
public String getFirstName() {
return FirstName;
}
public void setFirstName(String FirstName) {
this.FirstName = FirstName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String LastName) {
this.LastName = LastName;
}
public String getGender() {
return Gender;
}
public void setGender(String Gender) {
this.Gender = Gender;
}
public String getContact() {
return Contact;
}
public void setContact(String Contact) {
this.Contact = Contact;
}
public String getEmail() {
return Email;
}
public void setEmail(String Email) {
this.Email = Email;
}
}
public class User extends Person {
private String Password;
private String Username;
boolean isEnabled;
public User() {
}
public User(String Password, String Username, boolean isEnabled) {
this.Password = Password;
this.Username = Username;
this.isEnabled = isEnabled;
}
public String getPassword() {
return Password;
}
public void setPassword(String Password) {
this.Password = Password;
}
public String getUsername() {
return Username;
}
public void setUsername(String Username) {
this.Username = Username;
}
public boolean isIsEnabled() {
return isEnabled;
}
public void setIsEnabled(boolean isEnabled) {
this.isEnabled = isEnabled;
}
}
public class Guest extends User {
public Guest() {
}
public Guest(String Password, String Username, boolean isEnabled) {
super(Password, Username, isEnabled);
}
public void App(){
}
}
public class Members extends User{
public Members() {
}
public Members(String Password, String Username, boolean isEnabled) {
super(Password, Username, isEnabled);
}
}
public class Libararian extends User {
public Libararian() {
}
public Libararian(String Password, String Username, boolean isEnabled) {
super(Password, Username, isEnabled);
}
}
public class Book {
private String Title;
private String Publisher;
private String Category;
public Book(String Title, String Publisher, String Category) {
this.Title = Title;
this.Publisher = Publisher;
this.Category = Category;
}
public Book() {
}
public String getTitle() {
return Title;
}
public void setTitle(String Title) {
this.Title = Title;
}
public String getPublisher() {
return Publisher;
}
public void setPublisher(String Publisher) {
this.Publisher = Publisher;
}
public String getCategory() {
return Category;
}
public void setCategory(String Category) {
this.Category = Category;
}
}
I have a problem with Hibernate. Im struggling with this since yesterday, it seems very easy but I have no idea why it is not working...
I have entity Login.java:
package offersmanager.model.entity;
import org.json.JSONObject;
import javax.persistence.*;
#Entity
public class Login {
#Id
#GeneratedValue
private Integer id;
#Column(nullable = false, unique = true)
String username;
#Column(nullable = false)
String password;
public Login(){
}
public Login(String username, String password){
this.username = username;
this.password = password;
}
public Login(JSONObject jsonObject) {
this.id = (Integer) jsonObject.get("id");
this.username = (String) jsonObject.get("username");
this.password = (String) jsonObject.get("password");
}
public JSONObject toJsonObject() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", this.id);
jsonObject.put("username", this.username);
jsonObject.put("password", this.password);
return jsonObject;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
And entity TourOffice.java:
package offersmanager.model.entity;
import org.json.JSONObject;
import javax.persistence.*;
#Entity
public class TourOffice {
#Id
#GeneratedValue
private Integer id;
#Column(nullable = false)
String officeName;
#Column(nullable = false)
String eMail;
#Column(nullable = false)
String phoneNumber;
#Column(nullable = false)
String city;
#Column(nullable = false)
String zipCode;
#Column(nullable = false)
String address;
#OneToOne(cascade = {CascadeType.ALL})
#JoinColumn(name = "login_id")
Login login;
public TourOffice(){
}
public TourOffice(String officeName, String eMail, String phoneNumber, String city, String zipCode, String address) {
this.officeName = officeName;
this.eMail = eMail;
this.phoneNumber = phoneNumber;
this.city = city;
this.zipCode = zipCode;
this.address = address;
}
public TourOffice(JSONObject jsonObject) {
this.id = (Integer) jsonObject.get("id");
this.officeName = (String) jsonObject.get("officeName");
this.eMail = (String) jsonObject.get("eMail");
this.phoneNumber = (String) jsonObject.get("phoneNumber");
this.city = (String) jsonObject.get("city");
this.zipCode = (String) jsonObject.get("zipCode");
this.address = (String) jsonObject.get("address");
this.login = (new Login((JSONObject) jsonObject.get("login")));
}
public JSONObject toJsonObject() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", this.id);
jsonObject.put("officeName", this.officeName);
jsonObject.put("eMail", this.eMail);
jsonObject.put("phoneNumber", this.phoneNumber);
jsonObject.put("city", this.city);
jsonObject.put("zipCode", this.zipCode);
jsonObject.put("address", this.address);
jsonObject.put("login", this.login == null? null : login.toJsonObject());
return jsonObject;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getOfficeName() {
return officeName;
}
public void setOfficeName(String officeName) {
this.officeName = officeName;
}
public String geteMail() {
return eMail;
}
public void seteMail(String eMail) {
this.eMail = eMail;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Login getLogin() {
return login;
}
public void setLogin(Login login) {
this.login = login;
}
}
These entities are connected with #OneToOne relation.
What I'm trying to do is to find the name of my office (officeName) with field of Login class (username).
This is my function in TourOfficeDAO.java:
public TourOffice findOfficeNameByLogin(String username) {
Criteria name = createCriteria();
name.add(Restrictions.eq("login.username", username));
return (TourOffice) name.uniqueResult();
}
It goes through TourOfficeService to my rest controller where this method is invoked. But it doesn't matter cause exeception is thrown in DAO:
could not resolve property: login.username of:
offersmanager.model.entity.TourOffice; nested exception is
org.hibernate.QueryException: could not resolve property:
login.username of: offersmanager.model.entity.TourOffice
It can't find "login.username" and have no idea why... everything seems good.
I looked for similiar topics but I haven't still managed to make this works. Any help would be appreciated.
EDIT 1:
This is my abstract class DAO.java where is the function createCriteria()
public abstract class DAO<MODEL> implements Serializable {
public abstract Class<MODEL> getEntityClass();
#Autowired
protected SessionFactory sessionFactory;
protected Session getSession(){
return sessionFactory.getCurrentSession();
}
protected Query createQuery(String query){
return getSession().createQuery(query);
}
protected SQLQuery createSQLQuery(String query){
return getSession().createSQLQuery(query);
}
protected Criteria createCriteria(){
return getSession().createCriteria(getEntityClass());
}
#SuppressWarnings("unchecked")
public MODEL findById(Integer id) {
return (MODEL) getSession().get(getEntityClass(), id);
}
public void save(MODEL entity) {
getSession().save(entity);
getSession().flush();
}
public void update(MODEL entity) {
getSession().update(entity);
getSession().flush();
}
public void saveOrUpdate(MODEL entity) {
getSession().saveOrUpdate(entity);
getSession().flush();
}
public void delete(MODEL entity) {
getSession().delete(entity);
getSession().flush();
}
public List<MODEL> list(){
Criteria criteria = createCriteria();
#SuppressWarnings("unchecked")
List<MODEL> list = criteria.list();
return list;
}
}
I think you need first to create an alias like that:
public TourOffice findOfficeNameByLogin(String username) {
Criteria name = createCriteria();
name.createAlias("login", "login");
name.add(Restrictions.eq("login.username", username));
return (TourOffice) name.uniqueResult();
}