An issue with getting user roles in a Spring Rest application - java

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

Related

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;
}
}

SpelEvaluationException When Using Spring Security Expressions with Query

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}")

JPA- Compound Primary Key using #EmbededId

Goal: To impolement an #Entity where the id is a compound primary key using #EmbededId.
Problem: Based on my current implementation, I am getting the following result:
[
{
"id": 1,
"name": "Recipe 1",
"instruction": "Test Instruction",
"note": "Note 1",
"show": true,
"createDate": null,
"modify_date": null,
"ingredient": [
{},
{}
]
}
]
but I want to have this:
[
{
"id": 1,
"name": "Recipe 1",
"instruction": "Test Instruction",
"note": "Note 1",
"show": true,
"createDate": null,
"modify_date": null,
"ingredient": [
{ingredient_id: 1,
amount: 10},
{ingredient_id: 2,
amount: 20}
]
}
]
Can someone please help me too see where I have done wrong in my recipeIngredient class? Thanks in advance.
The following are my implementation:
The schema:
RecipeIngredientId.java
#Embeddable
public class RecipeIngredientId implements Serializable {
#Column(name = "recipe_id", nullable = false)
private int recipeId;
#Column(name = "ingredient_id", nullable = false)
private int ingredientId;
public RecipeIngredientId() {}
public RecipeIngredientId(int recipeId, int ingredientId) {
this.recipeId = recipeId;
this.ingredientId = ingredientId;
}
}
RecipeIngredient.java
#Entity
#Table(name = "recipe_ingredient")
public class RecipeIngredient implements Serializable
{
#EmbeddedId
private RecipeIngredientId id;
#ManyToOne
#JoinColumn(name="ingredient_id", insertable = false, updatable = false)
private Ingredient ingredient;
#ManyToOne
#JoinColumn(name = "recipe_id", insertable = false, updatable = false)
private Recipe recipe;
private double amount;
public RecipeIngredient() {}
public RecipeIngredient(Recipe recipe, Ingredient ingredient, double amount){
this.recipe = recipe;
this.ingredient = ingredient;
this.amount = amount;
}
}
Recipe.java:
#Entity
public class Recipe {
private int id;
#NotNull
private String name;
private String instruction;
private String note;
#NotNull
private boolean show;
#CreationTimestamp
#Temporal(TemporalType.DATE)
#Column(name = "create_date")
private Date createDate;
#UpdateTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "modify_date")
private Date modify_date;
private Set<RecipeIngredient> recipeIngredients;
public Recipe() {}
public Recipe(String name, String instruction, String note, boolean show) {
this.name = name;
this.instruction = instruction;
this.note = note;
this.show = show;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getInstruction() {
return instruction;
}
public void setInstruction(String instruction) {
this.instruction = instruction;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public boolean isShow() {
return show;
}
public void setShow(boolean show) {
this.show = show;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getModify_date() {
return modify_date;
}
public void setModify_date(Date modify_date) {
this.modify_date = modify_date;
}
#OneToMany(mappedBy = "recipe", cascade = CascadeType.ALL)
public Set<RecipeIngredient> getIngredient() {
return recipeIngredients;
}
public void setIngredient(Set<RecipeIngredient> recipeIngredients) {
this.recipeIngredients = recipeIngredients;
}
}
Ingredient.java
#Entity
public class Ingredient {
private int id;
#NotNull
#Column(unique=true)
private String name;
private Set<RecipeIngredient> recipeIngredients;
public Ingredient() {}
public Ingredient(String name) {
this.name = name;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#OneToMany(mappedBy = "ingredient", cascade = CascadeType.ALL)
public Set<RecipeIngredient> getRecipeIngredients() {
return recipeIngredients;
}
public void setRecipeIngredients(Set<RecipeIngredient> recipeIngredients) {
this.recipeIngredients = recipeIngredients;
}
}
This is a case of "derived identity". RecipeIngredient should look like this:
#Entity
#Table(name = "recipe_ingredient")
public class RecipeIngredient implements Serializable
{
#EmbeddedId
private RecipeIngredientId id;
#MapsId("ingredientId") // maps ingredientId attribute of embedded id
#ManyToOne
#JoinColumn(name="ingredient_id", insertable = false, updatable = false)
private Ingredient ingredient;
#MapsId("recipeId") // maps recipeId attribute of embedded id
#ManyToOne
#JoinColumn(name = "recipe_id", insertable = false, updatable = false)
private Recipe recipe;
private double amount;
public RecipeIngredient() {}
public RecipeIngredient(Recipe recipe, Ingredient ingredient, double amount){
this.recipe = recipe;
this.ingredient = ingredient;
this.amount = amount;
}
}
Note the MapsId annotations on the two fields whose primary keys make up the entity's composite key.
Derived identities are discussed in the JPA 2.1 spec in section 2.4.1.

Hibernate: Many to many mapping exception

I am stuck up with mapping exception. I have many to many relationship between Employee and Role. Here is the code.
Role class
#Entity
#Table(name = "role", catalog = "app")
public class Role implements java.io.Serializable {
#GeneratedValue(strategy = IDENTITY)
#Column(name = "roleId", unique = true, nullable = false)
private Integer roleId;
#Column(name = "title", nullable = false, length = 50)
private String title;
#ManyToMany(fetch = FetchType.LAZY, mappedBy = "roles")
private Set<Employee> employees = new HashSet<Employee>(0);
public Role() {
}
public Role(String title) {
this.title = title;
}
public Role(String title, Set<Employee> employees) {
this.title = title;
this.employees = employees;
}
public Integer getRoleId() {
return this.roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public Set<Employee> getEmployees() {
return this.employees;
}
public void setEmployees(Set<Employee> employees) {
this.employees = employees;
}
}
and Employee class
#Entity
#Table(name = "employee", catalog = "app", uniqueConstraints = #UniqueConstraint(columnNames = "email"))
public class Employee implements java.io.Serializable {
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "empId", unique = true, nullable = false)
private Integer empId;
#Column(name = "name", nullable = false, length = 100)
private String name;
#Column(name = "email", unique = true, nullable = false, length = 50)
private String email;
#Column(name = "phone", nullable = false, length = 11)
private String phone;
#Column(name = "ip", nullable = false, length = 20)
private String ip;
#Column(name = "password", nullable = false, length = 200)
private String password;
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(name = "employee_role", catalog = "app", joinColumns = {
#JoinColumn(name = "empId", nullable = false, updatable = false) }, inverseJoinColumns = {
#JoinColumn(name = "roleId", nullable = false, updatable = false) })
private Set<Role> roles = new HashSet<Role>(0);
public Employee() {
}
public Integer getEmpId() {
return this.empId;
}
public void setEmpId(Integer empId) {
this.empId = empId;
}
public City getCity() {
return this.city;
}
public void setCity(City city) {
this.city = city;
}
public Posts getPosts() {
return this.posts;
}
public void setPosts(Posts posts) {
this.posts = posts;
}
public Teams getTeams() {
return this.teams;
}
public void setTeams(Teams teams) {
this.teams = teams;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return this.phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getIp() {
return this.ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public Set<Role> getRoles() {
return this.roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
Here is the exception. Please also explain the exception
org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: org.company.app.models.Role.employees in org.company.app.models.Employee.roles
what is wrong?
It looks you miss #Id anotation for Role class
#Id
#Column(name = "roleId", unique = true, nullable = false)
private Integer roleId;

Hibernate Criteria list always return 0 items

Function in my DAO (findByUsername) is always returning 0 rows no matter if I change the entity class, even after removing annotation from the entity there is no exception, just 0 rows. This code is implemented in the spring based app according to some examples I have found.
DAO:
#Repository("userDao")
public class UserDao extends CustomHibernateDaoSupport {
public void save(User user) {
getHibernateTemplate().save(user);
}
public void delete(User user) {
getHibernateTemplate().delete(user);
}
public User findByUsername(String username) throws DataNotFoundException {
Session session = getSession();
Criteria crit = session.createCriteria(User.class);
System.out.println(username);
crit.add(Restrictions.eq("username", username));
crit.setMaxResults(1);
List<User> users = crit.list();
System.out.println(users);
if (users.size() < 1) {
throw new DataNotFoundException();
}
return users.get(0);
}
}
ENTITY:
#Entity
#Table(name = "users")
public class User {
private Integer id;
private String username;
private String password;
private boolean active;
private String activationCode;
private Date createdAt;
private String email;
private Set<Wall> walls = new HashSet<Wall>();
#Id
#GeneratedValue
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "username", unique = true, nullable = false)
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Column(name = "password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name = "active")
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
#Column(name = "activation_code")
public String getActivationCode() {
return activationCode;
}
public void setActivationCode(String activationCode) {
this.activationCode = activationCode;
}
#Column(name = "created_at", columnDefinition = "DATETIME")
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
#Column(name = "email")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "users_has_walls", joinColumns = {
#JoinColumn(name = "user_id", nullable = false, updatable = false) },
inverseJoinColumns = { #JoinColumn(name = "wall_id",
nullable = false, updatable = false) })
public Set<Wall> getWalls() {
return walls;
}
public void setWalls(Set<Wall> walls) {
this.walls = walls;
}
}
The solution was to change import declaration to
import javax.persistence.Entity;
instead of hibernate.
User entity class was not imported.

Categories