SpelEvaluationException When Using Spring Security Expressions with Query - java

I'm trying to use Spring Security Expressions in Query. As shown in 36. Security Expressions within #Query
public interface BookRepository extends JpaRepository<Book, Long> {
#PreAuthorize("hasAuthority('AUTHOR')")
#Query("select b from Book b where b.author.id = ?#{ principal?.id }")
Page<Book> findAllOwned(Pageable p);
}
And I'm getting the error below.
2018-01-28 01:50:10.672 ERROR 12985 --- [nio-8443-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'aid' cannot be found on object of type 'java.lang.String' - maybe not public?] with root cause
org.springframework.expression.spel.SpelEvaluationException:
EL1008E:
Property or field 'id' cannot be found on object of type 'java.lang.String' - maybe not public?
Please help to resolve the issue. What am I doing wrong?
I have included the classes I think necessary and relevant to this question below.
I have defined
#Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
return new SecurityEvaluationContextExtension();
}
And the user detail service
#Component
public class AppUserDetailsService implements UserDetailsService {
#Autowired
private UserRepository userRepository;
#Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
User user = userRepository.findByUsername(s);
if (user == null) {
throw new UsernameNotFoundException(String.format("The username %s doesn't exist", s));
}
List<GrantedAuthority> authorities = new ArrayList<>();
user.getRoles()
.forEach(role -> {
authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
});
return new PrincipalUser(user.getId(), user.getUsername(), user.getPassword(), authorities);
}
}
Custom Principal User
public class PrincipalUser extends User {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private Long id;
public PrincipalUser(Long id, String username, String password, Collection<? extends GrantedAuthority> authorities) {
super(username, password, authorities);
this.id = id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
Book Entity
#Entity
#EntityListeners(AuditingEntityListener.class)
#Table(name = "book")
public class Book {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "name", unique=true)
private String name;
#Column(name = "shortcode")
private String shortcode;
#ManyToOne
#JoinColumn(name="author_user_id")
private User author;
#CreatedDate
#Column(name = "created_date", columnDefinition="DATETIME")
#Temporal(TemporalType.TIMESTAMP)
private Date createdDate;
#CreatedBy
#Column(name="created_by")
private String createdBy;
#LastModifiedDate
#Column(name = "last_modified_date", columnDefinition="DATETIME")
#Temporal(TemporalType.TIMESTAMP)
private Date lastModifiedDate;
#LastModifiedBy
#Column(name="last_modified_by")
private String lastModifiedBy;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getShortcode() {
return shortcode;
}
public void setShortcode(String shortcode) {
this.shortcode = shortcode;
}
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Date getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(Date lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
}
User Entity
#Entity
#EntityListeners(AuditingEntityListener.class)
#Table(name = "app_user")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "username", unique=true)
private String username;
#Column(name = "password")
#JsonDeserialize(using = BCryptPasswordDeserializer.class )
private String password;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "email")
private String email;
#Column(name = "is_active")
private boolean isActive;
#CreatedDate
#Column(name = "created_date", columnDefinition="DATETIME")
#Temporal(TemporalType.TIMESTAMP)
private Date createdDate;
#CreatedBy
#Column(name="created_by")
private String createdBy;
#LastModifiedDate
#Column(name = "last_modified_date", columnDefinition="DATETIME")
#Temporal(TemporalType.TIMESTAMP)
private Date lastModifiedDate;
#LastModifiedBy
#Column(name="last_modified_by")
private String lastModifiedBy;
#OneToMany(mappedBy="author")
private List<Book> authoredBooks;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "user_role", joinColumns
= #JoinColumn(name = "user_id",
referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "role_id",
referencedColumnName = "id"))
private List<Role> roles;
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
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 boolean isActive() {
return isActive;
}
public void setActive(boolean isActive) {
this.isActive = isActive;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Date getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(Date lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public List<Book> getAuthoredBooks() {
return authoredBooks;
}
public void setAuthoredBooks(List<Book> authoredBooks) {
this.authoredBooks = authoredBooks;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
}
Extended SecurityEvaluationContextExtension
class SecurityEvaluationContextExtension extends EvaluationContextExtensionSupport {
#Override
public String getExtensionId() {
return "security";
}
#Override
public SecurityExpressionRoot getRootObject() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return new SecurityExpressionRoot(authentication) {};
}
}
Top few lines of the Stack trace:
ERROR 18238 --- [nio-8443-exec-9] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'id' cannot be found on object of type 'java.lang.String' - maybe not public?] with root cause
org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'id' cannot be found on object of type 'java.lang.String' - maybe not public?
at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:226) ~[spring-expression-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:94) ~[spring-expression-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.expression.spel.ast.PropertyOrFieldReference.access$000(PropertyOrFieldReference.java:46) ~[spring-expression-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.expression.spel.ast.PropertyOrFieldReference$AccessorLValue.getValue(PropertyOrFieldReference.java:379) ~[spring-expression-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:88) ~[spring-expression-4.3.13.RELEASE.jar:4.3.13.RELEASE]
Full Stack Trace ...

There appears to be an extraneous ? in the example. Try:
#Query("select b from Book b where b.author.id = ?#{principal.id}")

Related

Getting an error about not having an Identifier even when I have one

This is my UserRole class. Here, the id_roles, id_users and updated_by are supposed to be foreign keys (id_roles coming from the Role table and the other two coming from the User table, I'll put the code for each one of the tables down below)
package offgrid.models;
import io.quarkus.hibernate.reactive.panache.PanacheEntityBase;
import javax.persistence.*;
import java.time.LocalDateTime;
#Entity
#Access(AccessType.PROPERTY)
#Table(name = "user_roles")
public class UserRole extends PanacheEntityBase {
#EmbeddedId
private UserRolePK UserRolePK;
#OneToOne
#JoinColumn(name = "id_roles", referencedColumnName = "id")
private Role roleId;
#OneToOne
#JoinColumn(name = "id_users", referencedColumnName = "id")
private User userId;
#Column(name = "created_at")
private LocalDateTime createdAt;
#Column(name = "updated_at")
private LocalDateTime updatedAt;
#ManyToOne
#JoinColumn(name = "update_by", referencedColumnName = "name")
private User updatedBy;
public offgrid.models.UserRolePK getUserRolePK() {
return UserRolePK;
}
public void setUserRolePK(offgrid.models.UserRolePK userRolePK) {
UserRolePK = userRolePK;
}
public Role getRoleId() {
return roleId;
}
public void setRoleId(Role roleId) {
this.roleId = roleId;
}
public User getUserId() {
return userId;
}
public void setUserId(User userId) {
this.userId = userId;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public LocalDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(LocalDateTime updatedAt) {
this.updatedAt = updatedAt;
}
public User getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(User updatedBy) {
this.updatedBy = updatedBy;
}
}
And this is my UserRolePK
package offgrid.models;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import java.io.Serializable;
import java.util.Objects;
#Embeddable
public class UserRolePK implements Serializable {
#Column(name = "user_id")
private Long userId;
#Column(name = "role_id")
private Long roleId;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Long getRoleId() {
return roleId;
}
public void setRoleId(Long roleId) {
this.roleId = roleId;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserRolePK that = (UserRolePK) o;
return userId.equals(that.userId) && roleId.equals(that.roleId);
}
#Override
public int hashCode() {
return Objects.hash(userId, roleId);
}
}
Here is my User class
package offgrid.models;
import io.quarkus.hibernate.reactive.panache.PanacheEntityBase;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;
import javax.persistence.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.UUID;
#Entity
#Table(name="users")
public class User extends PanacheEntityBase {
#Id
#Column(name = "id")
#GeneratedValue(generator = "UUID")
#GenericGenerator(
name = "UUID",
strategy = "org.hibernate.id.UUIDGenerator"
)
#Type(type = "pg-uuid")
private UUID id;
#Column(name = "user")
private String username;
#Column(name = "name")
private String name;
#Column(name = "date_of_birth")
private LocalDate dateOfBirth;
#Column(name = "photo")
private String photo;
#Column(name = "tax_id")
private String taxId;
#Column(name = "status")
private String status;
#Column(name = "created_at")
private LocalDateTime createdAt;
#Column(name = "updated_at")
private LocalDateTime updateAt;
#ManyToOne
#JoinColumn(name = "updated_by")
private User user;
public UUID getId() {
return id;
}
public void setId(UUID 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 LocalDate getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(LocalDate dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getTaxId() {
return taxId;
}
public void setTaxId(String taxId) {
this.taxId = taxId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public LocalDateTime getUpdateAt() {
return updateAt;
}
public void setUpdateAt(LocalDateTime updateAt) {
this.updateAt = updateAt;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
And the Role class
package offgrid.models;
import io.quarkus.hibernate.reactive.panache.PanacheEntityBase;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.UUID;
#Entity
#Table(name = "roles")
public class Role extends PanacheEntityBase {
#Id
#Column(name = "id")
#GeneratedValue(generator = "UUID")
#GenericGenerator(
name = "UUID",
strategy = "org.hibernate.id.UUIDGenerator"
)
#Type(type = "pg-uuid")
private UUID id;
#Column(name = "name")
private String name;
#Column(name = "created_at")
private LocalDateTime createdAt;
#Column(name = "updated_at")
private LocalDateTime updatedAt;
#ManyToOne
#JoinColumn(name = "updated_by")
private User updatedBy;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public LocalDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(LocalDateTime updatedAt) {
this.updatedAt = updatedAt;
}
public User getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(User updatedBy) {
this.updatedBy = updatedBy;
}
}
I'm getting this error when I try to run my code:
Caused by: org.hibernate.AnnotationException: No identifier specified for entity: offgrid.models.UserRole
But as I detailed above, there I put an EmbeddedId annotation referencing my UserRolePK class.. Am I missing something?
It's because of:
#Access(AccessType.PROPERTY)
But you used annotations on fields.
Change it to:
#Access(AccessType.FIELD)
or remove it, as JPA know it is FIELD base on where you placed the annotations.

Hibernate doesn't create table that implements Serializable interface?

I have small project with Spring Data, MVC and Web Flow. Also I have 2 entities that I use in Spring Web Flow, so they MUST implement Serializable interface, but I noticed that Hibernate doesn't create tables, that implement it, for proving it I just copied my entity, removed "implements Serializable" created new class and pasted the entity code there, the new table was created. How it works ? How to create table from entity that implement Serializable, is it possible at all ?
The entities code:
#Table(name = "users")
#Entity
public class User implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "idUsers")
private int id;
#Column(name = "login")
#Size(min = 3, max = 15,message = "Неправильний розмір")
#NotEmpty(message = "Не може бути пустим!")
private String login;
#Size(min = 6, max = 21,message = "Неправильний розмір")
#NotEmpty(message = "Не може бути пустим!")
#Column(name = "password")
private String password;
#NotNull(message = "Не може бути пустим!")
#Column(name = "email")
private String email;
#Column(name = "photo")
private String path;
#Column(name = "about")
private String about;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#OneToMany(
fetch = FetchType.EAGER,
mappedBy = "user",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private Set<CommentsToBook> commentsToBooks;
public Set<CommentsToBook> getCommentsToBooks() {
return commentsToBooks;
}
public void setCommentsToBooks(Set<CommentsToBook> commentsToBooks) {
this.commentsToBooks = commentsToBooks;
}
public Set<BookOrder> getOrders() {
return orders;
}
public void setOrders(Set<BookOrder> orders) {
this.orders = orders;
}
#OneToMany(
fetch = FetchType.EAGER,
mappedBy = "user",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private Set<BookOrder> orders;
public String getPath() {
return path;
}
public String getAbout() {
return about;
}
public void setAbout(String about) {
this.about = about;
}
public void setPath(String path) {
this.path = path;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
And the second one:
#Entity
#Table(name = "booook_order")
public class BookOrder implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private int id;
#Column(name = "bank_card")
private String bankCardId;
#Column(name = "user_name")
private String custName;
public User getUser() {
return user;
}
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(name = "book", joinColumns = {
#JoinColumn(name = "id")
},inverseJoinColumns = {#JoinColumn(name = "idlibrary")})
private Set<Book> booksList;
#Column(name ="novaposhta-vid")
private String NPVid;
public String getNPVid() {
return NPVid;
}
public void setNPVid(String NPVid) {
this.NPVid = NPVid;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
#Column(name = "city")
private String city;
public void setUser(User user) {
this.user = user;
}
#ManyToOne(cascade = CascadeType.ALL,
fetch = FetchType.EAGER)
#JoinColumn(name = "idUsers")
private User user;
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Set<Book> getBooksList() {
return booksList;
}
public void setBooksList(Set<Book> booksList) {
this.booksList = booksList;
}
public String getBankCardId() {
return bankCardId;
}
public void setBankCardId(String bankCardId) {
this.bankCardId = bankCardId;
}
}

An issue with getting user roles in a Spring Rest application

I have a RestController class with the following :
#RestController
public class UserRestController
{
#Autowired
UserService userService;
#Autowired
private SecurityService securityService;
#Autowired
private UserValidator userValidator;
// Get a Single User
#GetMapping("/api/users/{id}")
public User getUserById(#PathVariable(value = "id") Long userId) {
return userService.getUserById(userId);
}
This is getUserById function in UserService :
public User getUserById(#PathVariable(value = "id") Long userId) {
return userRepository.findById(userId).orElseThrow(() -> new ResourceNotFoundException("User", "id", userId));
}
This is the result of a GET request on localhost:8080/api/users/11 :
{
"id": 11,
"name": null,
"email": null,
"password": "$2a$10$HykDWcHU3vO9YAcdXiWieua9YyYMkwrNIk7WgpmVzVwENb71fDCsW",
"status": null,
"tel": null,
"confirmation": null,
"birth_date": null,
"createdAt": "2018-05-22T09:09:12.000+0000",
"updatedAt": "2018-05-22T09:09:12.000+0000",
"username": "ouissal#gmail.com"
}
This is the result of a GET request on localhost:8080/users/11
{
"name": null,
"email": null,
"password": "$2a$10$HykDWcHU3vO9YAcdXiWieua9YyYMkwrNIk7WgpmVzVwENb71fDCsW",
"status": null,
"tel": null,
"confirmation": null,
"birth_date": null,
"createdAt": "2018-05-22T09:09:12.000+0000",
"updatedAt": "2018-05-22T09:09:12.000+0000",
"username": "ouissal#gmail.com",
"_links": {
"self": {
"href": "http://localhost:8080/users/11"
},
"user": {
"href": "http://localhost:8080/users/11"
},
"roles": {
"href": "http://localhost:8080/users/11/roles"
}
}
}
I do not have anything mapped for /users in my controller, how can I get the roles using my controller?
edit
This is my User class :
#Entity
#Table(name = "user")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = {"createdAt", "updatedAt"},
allowGetters = true)
public class User implements Serializable{
private static final long serialVersionUID = 1L;
public User() {
super();
// TODO Auto-generated constructor stub
}
#Id
#Column(name = "user_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "user_name")
//#NotBlank
private String name;
#Column(name = "user_email")
//#NotBlank
private String email;
#Column(name = "user_password")
#NotBlank
private String password;
#Column(name = "user_status")
private String status;
#Column(name = "user_tel")
private String tel;
#Column(name = "user_confirmation")
private String confirmation;
#Column(name = "user_birth_date")
#Temporal(TemporalType.DATE)
private Date birth_date;
#Column(nullable = false, updatable = false)
#Temporal(TemporalType.TIMESTAMP)
#CreatedDate
private Date createdAt;
#Column(nullable = false)
#Temporal(TemporalType.TIMESTAMP)
#LastModifiedDate
private Date updatedAt;
#JsonBackReference
#ManyToMany
#JoinTable(name = "user_role", joinColumns = #JoinColumn(name = "user_id"), inverseJoinColumns = #JoinColumn(name = "role_id"))
private Set<Role> roles;
#Column(name = "username")
#NotBlank
private String username;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
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;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getConfirmation() {
return confirmation;
}
public void setConfirmation(String confirmation) {
this.confirmation = confirmation;
}
public Date getBirth_date() {
return birth_date;
}
public void setBirth_date(Date birth_date) {
this.birth_date = birth_date;
}
public Date getCreatedAt() {
return createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
and this is my role class :
#Entity
#Table(name = "role")
public class Role {
#Id
#Column(name = "role_id")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "role_name")
private String name;
#ManyToMany(mappedBy = "roles")
#JsonManagedReference
private Set<User> users;
public Role() {
super();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
}
Properties annotated with JsonBackReference will not be included in your serialized content.
To include the roles swap the JsonBackReference and JsonManagedReference annotations in Role and User.
This will include Roles into User but not the other way round.
For more information you can check this answer

Declaring class is not found in the inheritance state hierarchy: UserAccount

I'm using servlets with JPA+Hibernate). I don't understand the error, unless I've tried other solutions suggested in this forum. In fact, I don't want to store the UserAccount class as an entity; but I just want to declare it in the Utilisateur class (the Ids of the Utilisateur class are declared in the useraccount class).
My code :
#Entity
#Table(name = "utilisateur")
public class Utilisateur implements Serializable {
#Id
private UserAccount userAccount;
private Civility civility;
private Address address;
private Contact contact;
#Column(name = "sessions")
private List<String> sessions;
#Column(name = "particularRules")
private boolean particularRules;
public Utilisateur(UserAccount pAccount, Civility pCivility,
Address pAddress, Contact pContact, List<String>
pSessions,
boolean particularRules) {
this.userAccount = pAccount;
this.civility = pCivility;
this.address = pAddress;
this.contact = pContact;
this.sessions = pSessions;
this.particularRules = particularRules;
}
public Civility getCivility() {
return civility;
}
public void setCivility(Civility civility) {
this.civility = civility;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public Contact getContact() {
return contact;
}
public void setContact(Contact contact) {
this.contact = contact;
}
public boolean isParticularRules() {
return particularRules;
}
public void setParticularRules(boolean particularRules) {
this.particularRules = particularRules;
}
public UserAccount getUserAccount() {
return userAccount;
}
public void setUserAccount(UserAccount userAccount) {
this.userAccount = userAccount;
}
public List<String> getSessions() {
return sessions;
}
public void setSessions(List<String> sessions) {
this.sessions = sessions;
}
}
#Embeddable
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class UserAccount implements Serializable {
public UserAccount() {
}
public UserAccount(String pId, String pEmail, String pwsd, Date pCreaDate, Date pLastModDate) {
this.identifier = pId;
this.email = pEmail;
this.password = pwsd;
this.creationDate = pCreaDate;
this.lastModificationDate = pLastModDate;
}
#OneToOne(mappedBy = "userAccount", cascade = CascadeType.ALL,
fetch = FetchType.EAGER, orphanRemoval = true, targetEntity =
Utilisateur.class)
private Utilisateur user;
#Column(name = "creationDate")
#Temporal(javax.persistence.TemporalType.DATE)
private Date creationDate;
#Column(name = "lastModificationDate")
#Temporal(javax.persistence.TemporalType.DATE)
private Date lastModificationDate;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "identifier", nullable = false)
private String identifier;
#Column(name = "email")
private String email;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "password", nullable = false)
private String password;
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
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;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Date getLastModificationDate() {
return lastModificationDate;
}
public void setLastModificationDate(Date lastModificationDate) {
this.lastModificationDate = lastModificationDate;
}
public Utilisateur getUser() {
return user;
}
public void setUser(Utilisateur user) {
this.user = user;
}
}
You must use an Embedded Primary Key.
See the answer to this question here in Stackoverflow How to create and handle composite primary key in JPA.
Best regards!
It may occur when Embedded Primary Key contains #EmbeddedId. Sub-composite key should be annotated with #Embedded instead.

How to join Maps

How to join newMap detals in custMap.
Map<String, Customer> custMap= new HashMap<String,Customer>();
Map<String, DoCustomer> newMap= new HashMap<String,DoCustomer>();
for (Map.Entry<String, DoCustomer> cust: newMap.entrySet()) {
custMap.put(cust.getKey(),cust.getValue());
}
public class DoCustomer {
private Long id;
private String custName;
private String description;
private String status;
private List<DoCustomerBranch> doCustomerBranch=new ArrayList<DoCustomerBranch>
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
getter/setters of doCustomerBranch
}
#Entity
#Table(name = "CUSTOMER")
public class Customer implements Serializable{
private static final long serialVersionUID = 1L;
private Long id;
private String custName;
private String description;
private String createdBy;
private Date createdOn;
private String updatedBy;
private Date updatedOn;
private Set<CustomerBranch> customerBranch=new HashSet<CustomerBranch>
#Id
#GeneratedValue(generator = "CUSTOMER_SEQ")
#SequenceGenerator(name = "CUSTOMER_SEQ", sequenceName = "CUSTOMERN_SEQ", allocationSize = 1)
#Column(name = "ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "CUST_NAME",nullable=false)
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
#Column(name = "DESCRIPTION")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name = "CREATED_BY", length = 50)
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "CREATED_ON")
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
#Column(name = "UPDATED_BY", length = 50)
public String getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "UPDATED_ON")
public Date getUpdatedOn() {
return updatedOn;
}
public void setUpdatedOn(Date updatedOn) {
this.updatedOn = updatedOn;
}
#OneToMany(cascade = { CascadeType.PERSIST, CascadeType.REMOVE }, fetch = FetchType.LAZY, mappedBy = "customer")
public Set<CustomerBranch> getCustomerBranch() {
return customerBranch;
}
public void setCustomerBranch(Set<CustomerBranch> customerBranch) {
this.customerBranch = customerBranch;
}
}
CustomerBranch
#Entity
#Table(name = "CUSTOMER_BRANCH")
public class CustomerBranch implements Serializable{
#Id
#GeneratedValue(generator = "CUSTOMER_BRANCH_SEQ")
#SequenceGenerator(name = "CUSTOMER_BRANCH_SEQ", sequenceName = "CUSTOMER_BRANCH_SEQ", allocationSize = 1)
#Column(name = "ID")
private Long id;
private String branchName;
private String branchAddress;
private Customer customer;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "BRANCH_NAME",nullable=false)
public String getBranchName() {
return branchName;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "MOBEE_CUSTOMER")
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
}
The problem with your code is that you want to put a DoCustomer in a Customer container. It only works if DoCustomer is a subclass of Customer.
Edit 1: You could use BeanUtils to convert a DoCustomer into a Customer. Here is a good tutorial.
Do you mean:
custMap.putAll(newMap)
As everyone else has pointed out, we need to know what DoCustomer is to be able to help.
But, from what you have given us, I'd suggest casting each DoCustomer to a Customer or, more correctly, making a new Customer from the fields of each DoCustomer.
Something like:
custMap.put(cust.getKey(), new Customer(cust.getValue().getId(), cust.getValue().getCustName(), and so on..));
inside your for loop.
I can see the customer class defined you have provided doesn't have a constructor, so naturally you would have to add one to it

Categories