Spring is not using ManyToMany relationship - java

I have a user and a movie model:
user:
#Entity(name = "User")
#Table(name = "USER")
public class User {
#Id
#Column(name = "ID")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_seq")
#SequenceGenerator(name = "user_seq", sequenceName = "user_seq", allocationSize = 1)
private Long id;
#Column(name = "USERNAME", length = 50, unique = true)
#NotNull
#Size(min = 4, max = 50)
private String username;
#Column(name = "PASSWORD", length = 100)
#NotNull
#Size(min = 4, max = 100)
private String password;
#Column(name = "FIRSTNAME", length = 50)
#NotNull
#Size(min = 4, max = 50)
private String firstname;
#Column(name = "LASTNAME", length = 50)
#NotNull
#Size(min = 4, max = 50)
private String lastname;
#Column(name = "EMAIL", length = 50)
#NotNull
#Size(min = 4, max = 50)
private String email;
#Column(name = "ENABLED")
#NotNull
private Boolean enabled;
#Column(name = "LASTPASSWORDRESETDATE")
#Temporal(TemporalType.TIMESTAMP)
#NotNull
private Date lastPasswordResetDate;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(
name = "USER_AUTHORITY",
joinColumns = {#JoinColumn(name = "USER_ID", referencedColumnName = "ID")},
inverseJoinColumns = {#JoinColumn(name = "AUTHORITY_ID", referencedColumnName = "ID")})
private List<Authority> authorities;
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 getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public List<Authority> getAuthorities() {
return authorities;
}
public void setAuthorities(List<Authority> authorities) {
this.authorities = authorities;
}
public Date getLastPasswordResetDate() {
return lastPasswordResetDate;
}
public void setLastPasswordResetDate(Date lastPasswordResetDate) {
this.lastPasswordResetDate = lastPasswordResetDate;
}
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "user_movie",
joinColumns = #JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "movie_id", referencedColumnName = "id")
)
private Set<Movie> movies;
public Set<Movie> getMovies() {
return movies;
}
public void setMovies(Set<Movie> movies) {
this.movies = movies;
}
}
movie:
#Entity(name = "Movie")
#Table(name = "movie")
public class Movie {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
public Movie(){}
public Movie(Integer id, String name ) {
this.id = id;
this.name = name;
}
#ManyToMany(mappedBy = "movies")
private Set<User> users;
public Set<User> getUsers() {
return users;
}
public void addUser(User user){
System.out.println("ADD MOVIE: " + user);
users.add(user);
user.getMovies().add(this);
}
public void setUsers(Set<User> users) {
this.users = users;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString(){
return "id: " + id + "name: " + name;
}
}
I've set up a many to many relation between these models. With, if I am correct, the user as the owner of the relation.
In my MovieController.java I have:
#RequestMapping(value = "/", method = RequestMethod.POST)
public Movie createMovie(#RequestBody Movie movie){
return movieService.createMovie(movie);
}
This calls the MovieService.java:
#Override
public Movie createMovie(Movie movie) {
return movieRepository.save(movie);
}
And this calls the MovieRepository.java:
#Repository
public interface MovieRepository extends CrudRepository<Movie, Serializable> {}
When I call the post methode from my front-end a movie record is saved in my movie table, but no record is created in the user_movie table. Doesn't Hibernate do this implicit since I set up a Many to Many relation between user and movie?

For the first view, your code is correct.
The problem can be in GenerationType.SEQUENCE (try to use GenerationType.AUTO for User's id), or you need to add #Transactional to your controller.

You save the movie and in order to also have the user saved the cascade has to be set in the movie. Otherwise you can keep the cascade in user and save him.
You need to put the cascade to the entity on which you call save to cascade it.
Movie{
#ManyToMany(mappedBy = "movies", cascade={CascadeType.ALL})
private Set<User> users;
public Set<User> getUsers() {
return users;
}
}
User {
#ManyToMany
#JoinTable(name = "user_movie",
joinColumns = #JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "movie_id", referencedColumnName = "id")
)
private Set<Movie> movies;
}
Don't forget to add the user to movie and vice versa before saving.
As with all bi-directional relationships it is your object model's and application's responsibility to maintain the relationship in both direction. There is no magic in JPA, if you add or remove to one side of the collection, you must also add or remove from the other side, see object corruption. Technically the database will be updated correctly if you only add/remove from the owning side of the relationship, but then your object model will be out of synch, which can cause issues.
see here: https://en.wikibooks.org/wiki/Java_Persistence/ManyToMany

Related

Map external id to local id

In my app users can add movies to their watchlist. The movie data comes from an external API. Each movie has its own unique id. For example: Star Wars - A new hope has id 11. And Fight Club has id 550.
When a user adds a movie I pass the whole movie object from the front-end to the back-end:
Component:
createMovie(movie: Movie): void {
this._dataService.createMovie<Movie>({'name': 'Star Wars - A new hope', 'id': 11})
.subscribe((data) => this.movies.push(data),
error => () => {
'something went wrong';
},
() => {
// console.log(this.movies);
});
}
In this case I'm using example data.
Service:
public createMovie<T>(movie: Movie): Observable<T> {
return this.http.post<T>('/api/movies/', movie, {headers: this.getToken()});
}
The MovieController in the back-end:
#RequestMapping(value = "/", method = RequestMethod.POST)
public Movie createMovie(#RequestBody Movie movie){
return movieService.createMovie(movie);
}
The MovieService:
#Override
public Movie createMovie(Movie movie) {
User current_user = userService.getUser();
current_user.addMovie(movie);
userRepository.save(current_user);
return movie;
}
And the User model:
public void addMovie(Movie movie) {
movies.add(movie);
movie.getUsers().add(this);
}
When the movie is saved in the database it's saved with a unique id, starting from 1. How would I map the id from the front-end to the id of the object in my database? I could create another column "external_id" and map it to that, but I think that's a lesser solution than to use the id from the external API.
//edit. Added my movie and user model:
package com.movieseat.models;
import com.movieseat.model.security.User;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
#Entity(name = "Movie")
#Table(name = "movie")
public class Movie {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Integer id;
private String name;
private String description;
#ManyToMany(mappedBy = "movies")
private Set<User> users = new HashSet<>();
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
User model:
package com.movieseat.model.security;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.movieseat.models.Movie;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
#Entity(name = "User")
#Table(name = "USER")
#JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
public class User {
#Id
#Column(name = "ID")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_seq")
#SequenceGenerator(name = "user_seq", sequenceName = "user_seq", allocationSize = 1)
private Long id;
#Column(name = "USERNAME", length = 50, unique = true)
#NotNull
#Size(min = 4, max = 50)
private String username;
#Column(name = "PASSWORD", length = 100)
#NotNull
#Size(min = 4, max = 100)
private String password;
#Column(name = "FIRSTNAME", length = 50)
#NotNull
#Size(min = 4, max = 50)
private String firstname;
#Column(name = "LASTNAME", length = 50)
#NotNull
#Size(min = 4, max = 50)
private String lastname;
#Column(name = "EMAIL", length = 50)
#NotNull
#Size(min = 4, max = 50)
private String email;
#Column(name = "ENABLED")
#NotNull
private Boolean enabled;
#Column(name = "LASTPASSWORDRESETDATE")
#Temporal(TemporalType.TIMESTAMP)
#NotNull
private Date lastPasswordResetDate;
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(
name = "USER_AUTHORITY",
joinColumns = {#JoinColumn(name = "USER_ID", referencedColumnName = "ID")},
inverseJoinColumns = {#JoinColumn(name = "AUTHORITY_ID", referencedColumnName = "ID")})
private List<Authority> authorities;
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 getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public List<Authority> getAuthorities() {
return authorities;
}
public void setAuthorities(List<Authority> authorities) {
this.authorities = authorities;
}
public Date getLastPasswordResetDate() {
return lastPasswordResetDate;
}
public void setLastPasswordResetDate(Date lastPasswordResetDate) {
this.lastPasswordResetDate = lastPasswordResetDate;
}
#ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
#JoinTable(name = "user_movie",
joinColumns = #JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "movie_id", referencedColumnName = "id")
)
private Set<Movie> movies = new HashSet<>();
public void addMovie(Movie movie) {
movies.add(movie);
movie.getUsers().add(this);
}
public void removeMovie(Movie movie) {
movies.remove(movie);
movie.getUsers().remove(this);
}
}

Hibernate Exception when using mappedby attribute

I am trying to map between tables in pojo class.But I am getting exception for one attribute.
Pojo Classes
Users:
#Entity
#Table(name = "Users")
public class Users implements java.io.Serializable {
private int userId;
private Role role;
private Groups groupId;
private UserType userType;
private String userName;
private Boolean isActive;
public Users() {
}
public Users(int userId, Role role, Groups groupId ,UserType userType, String userName, boolean isActive) {
this.userId = userId;
this.role = role;
this.groupId = groupId;
this.userType = userType;
this.userName = userName;
this.isActive = isActive;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "UserID", unique = true, nullable = false)
public int getUserId() {
return this.userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "RoleID", nullable = false)
public Role getRole() {
return this.role;
}
public void setRole(Role role) {
this.role = role;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "GroupId", nullable = false)
public Groups getGroup() {
return this.groupId;
}
public void setGroup(Groups group) {
this.groupId = group;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "UserTypeID", nullable = false)
public UserType getUserType() {
return this.userType;
}
public void setUserType(UserType userType) {
this.userType = userType;
}
#Column(name = "UserName", nullable = false)
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
#Column(name = "IsActive", nullable = false, columnDefinition = "BIT")
public Boolean isIsActive() {
return this.isActive;
}
public void setIsActive(Boolean isActive) {
this.isActive = isActive;
}
}
Groups:
#Entity
#Table(name = "Groups")
public class Groups implements java.io.Serializable{
private int groupId;
private String groupName;
private String groupDesc;
private Set<Users> users = new HashSet<Users>(0);
public Groups (){
}
public Groups(int groupId, String groupName, String groupDesc){
super();
this.groupId = groupId;
this.groupName = groupName;
this.groupDesc = groupDesc;
}
public Groups(int groupId, String groupName, String groupDesc, Set<Users> users) {
super();
this.groupId = groupId;
this.groupName = groupName;
this.groupDesc = groupDesc;
this.users = users;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name ="GroupID", nullable = false)
public int getGroupId() {
return groupId;
}
public void setGroupId(int groupId) {
this.groupId = groupId;
}
#Column(name = "GroupName", nullable = false)
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
#Column(name = "GroupDesc", nullable = false)
public String getGroupDesc() {
return groupDesc;
}
public void setGroupDesc(String groupDesc) {
this.groupDesc = groupDesc;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "groupId") //Error
public Set<Users> getUserse() {
return this.userse;
}
public void setUserse(Set<Users> users) {
this.users = users;
}
}
I am mapping the correct member variable of Users class. But I am getting exception like this
org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: com.project.pojo.Users.groupId in com.project.pojo.Groups.users
In users pojo I have attributes like role,usertype which are mapped without any exception.Whereas for group I am getting this exception.
Can someone please help me to resolve this exception.
Thank you :)
There is a problem in your member variables of classes users and groups
Change the variable name groupId to group of Users.pojo and change mappedby attribute to group in groups class set method.
This will resolve your problem.
In your Groups class, you first declared a variable named users as a set of Users, which is fine. So if you gonna annotate #OneToMany on your setters, the name must match the variable name.
Also, in your Users table, you created a Groups variable and you named it as groupId, but in your Users table you have a int type named groupId, this will confuse the heck out of hibernate and causing problems. You should rename it to:
private Groups group;
So it should be like:
#OneToMany(fetch = FetchType.LAZY, mappedBy = "group")
public Set<Users> getUsers() {
return this.users;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "group", nullable = false)
public Groups getGroup() {
return this.group;
}
You didn't ask but you need to fix your RoleID table also. I don't think you really understand how hibernate ORM works yet, see this:
http://www.mkyong.com/hibernate/hibernate-one-to-many-relationship-example-annotation/
It must be because of difference between users and userse.
You defined getter for the Group object in Users bean as:
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "GroupId", nullable = false)
public Groups getGroup() {
return this.groupId;
}
which is not the best accessor name for a bean.
Try renaming the Group object in Users from groupID to group and change the mapping annotation into something like:
#OneToMany(fetch = FetchType.LAZY, mappedBy = "group")
public Set<Users> getUserse() {
return this.userse;
}

could not resolve property: userId.username

I have following entity classes:
#MappedSuperclass
public class AbstractEntity implements Serializable, Comparable<AbstractEntity> {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
protected Integer id;
#Override
public int compareTo(AbstractEntity o) {
return this.toString().compareTo(o.toString());
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
#Entity
#Table(name = "ticket")
#NamedQueries({
#NamedQuery(name = "Ticket.findAll", query = "SELECT t FROM Ticket t")})
public class Ticket extends AbstractEntity {
#Column(name = "title")
private String title;
#Column(name = "description")
private String description;
#Enumerated(EnumType.STRING)
#Column(name = "status")
private TicketStatus status;
#Enumerated(EnumType.STRING)
#Column(name = "priority")
private TicketPriority priority;
#Column(name = "categories")
private String categories;
#Column(name = "views")
private Integer views;
#Column(name = "date_time_created")
#Temporal(TemporalType.TIMESTAMP)
private Date dateTimeCreated;
#Column(name = "date_time_modified")
#Temporal(TemporalType.TIMESTAMP)
private Date dateTimeModified;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "ticketId")
private List<TicketFollower> ticketFollowerList;
#JoinColumn(name = "project_id", referencedColumnName = "id")
#ManyToOne(optional = false)
private Project projectId;
#JoinColumn(name = "ticket_attachment_id", referencedColumnName = "id")
#ManyToOne
private TicketAttachment ticketAttachmentId;
#JoinColumn(name = "user_id", referencedColumnName = "id")
#ManyToOne(optional = false)
private User userId;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "ticketId")
private List<TicketComment> ticketCommentList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "ticketId")
private List<TicketAttachment> ticketAttachmentList;
#Inject
public Ticket() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
...
#Override
public String toString() {
return getTitle();
}
}
#Entity
#Table(name = "user")
#NamedQueries({
#NamedQuery(name = "User.findAll", query = "SELECT u FROM User u")})
public class User extends AbstractEntity {
#Enumerated(EnumType.STRING)
#Column(name = "role")
private Role role;
#Column(name = "username")
private String username;
#Column(name = "password")
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 = "avatar_path")
private String avatarPath;
#Column(name = "date_time_registered")
#Temporal(TemporalType.TIMESTAMP)
private Date dateTimeRegistered;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userId")
private List<TicketFollower> ticketFollowerList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userId")
private List<Ticket> ticketList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userId")
private List<TicketComment> ticketCommentList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userId")
private List<ProjectFollower> projectFollowerList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userId")
private List<TicketAttachment> ticketAttachmentList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userId")
private List<Project> projectList;
#Inject
public User() {}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
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;
}
I get this exception from creating a hibernate Criteria. In my TicketDao class I have a method which search ticket by username, and when I invoke code below
Criteria criteria = session.createCriteria(Ticket.class);
criteria.add(Restrictions.eq("userId.username", username));
it throws exception:
could not resolve property: userId.username of: com.entities.Ticket
However, when I write criteria like:
criteria.add(Restrictions.eq("userId.id", userId));
it does not show any exception and returns me result. Any idea why my syntax for criteria.add(Restrictions.eq("userId.username", username)); and other properties like firstname, last name is wrong ?
Criteria does not work like EL or Java methods or attributes, you cannot refer to inner objects with a dot ..
You have to create a restriction in Ticket, right? What does Ticket has? An User. Then... you have to create a new User, set the username to this User and then set the created User to Ticket's criteria:
Criteria criteria = session.createCriteria(Ticket.class);
User user = new User();
user.setUsername(username);
criteria.add(Restrictions.eq("user", user));

Creating a simple user/group model with permissions with Hibernate (annotations)

This is most likely a very basic question, but nevertheless:
Basically the User entity has an Id and a privilege enum.
The group has an id and a name.
I wonder how to model a relationship where an user can be in multiple groups, having different privilege levels in different groups. Every group can of course have multiple members.
What's the way I'm supposed to solve that idiomatically with Hibernate?
Adding some membership field to User? A membership field to Group? Both? Creating a new class for it? Which annotations are required to wire these things together?
I used next architecture
UserEntity class
#Entity
#Table(name = "user")
public class UserEntity implements Serializable {
private Long user_id;
private String username;
private String password;
public UserEntity() {
}
public UserEntity(String name, String passwd) {
username = name;
password = passwd;
}
#Column(name = "password", nullable = false)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.AUTO)
public Long getUser_id() {
return user_id;
}
public void setUser_id(Long user_id) {
this.user_id = user_id;
}
#Column(name = "username", nullable = false)
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
AuthorityEntity class
#Entity
#Table(name = "authority_role")
public class AuthorityEntity implements Serializable {
private Integer id;
private String authority;
private List<UserEntity> people;
public AuthorityEntity() {
}
public AuthorityEntity(String authString) {
authority = authString;
}
#Column(name = "authority", nullable = false)
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.AUTO)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#ManyToMany(targetEntity = UserEntity.class,
cascade = {CascadeType.PERSIST, CascadeType.MERGE})
#JoinTable(name = "authority_role_people",
joinColumns =
#JoinColumn(name = "authority_role_id"),
inverseJoinColumns =
#JoinColumn(name = "user_id"))
public List<UserEntity> getPeople() {
return people;
}
public void setPeople(List<UserEntity> people) {
this.people = people;
}
}
In fact - this is how implemented spring security plugin.
In your case you can implement that architecture, which will be more useful for you.

how to solve lazyinitializationexception not using fetch=FetchType.EAGER?

Iam still getting the exception lazyinitializationexception.
Yes, i know that it means, that the session is closed while I or something else is trying to access the collection.
No, the OpenEntityManagerInViewFilter did not work.
Yes, #ManyToOne(fetch=FetchType.EAGER) helped but i dont want to use it, cause it will fecth aumotically all the time.
How Else can i do that ?
P.S. : I am using HibernateEntityManger with jpa with annotated class.
UPADATE
here is my code, first of all
I have 4 tables :
users(id,first_name,last_name,email....)
roles(id,name,comment....)
users_roles(user_id,role_id)
mails(id,user_id,subject,message,to_id...)
An user can have mutiples roles ....
Users Entity
#Entity
#Table(name = "USERS")
public class User implements GenericDomain{
public static final String _ID = "id";
private Long id;
private String firstName;
private String lastName;
private String email;
private Set<Role> roles = new HashSet<Role>(0);
/* Constructors */
public User() {
}
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name = "ID", unique = true, nullable = false)
public Long getId() { return this.id; }
public void setId(Long id) { this.id = id; }
#Column(name="FIRST_NAME", nullable = false, length = 64)
#NotEmpty
#Length(min = 4, max = 45)
public String getFirstName() { return this.firstName; }
public void setFirstName(String firstname) { this.firstName = firstname; }
#Column(name="LAST_NAME", nullable = false, length = 64)
#NotEmpty
#Length(min = 4, max = 45)
public String getLastName() { return this.lastName; }
public void setLastName(String lastname) { this.lastName = lastname; }
#Column(name="EMAIL", unique = false, length = 64)
#Email
#NotEmpty
#Length(min = 4, max = 45)
public String getEmail() { return this.email; }
public void setEmail(String email) { this.email = email; }
#ManyToMany(fetch=FetchType.EAGER)
#JoinTable(name = "USERS_ROLES"
, joinColumns = { #JoinColumn(name = "user_id") }
, inverseJoinColumns = { #JoinColumn(name = "role_id") }
)
public Set<Role> getRoles() {
return this.roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
/*#Override toString/equals/hascode */
}
Role Entity
#Entity
#Table(name = "ROLES")
public class Role implements GenericDomain {
private Long id;
private String name;
private String comment;
private Set<User> users = new HashSet<User>(0);
public Role() {
}
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name = "ID", unique = true, nullable = false)
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
#Column(name="NAME", nullable = false, length = 64)
#NotEmpty
#Length(min = 1, max = 32)
public String getName() { return name; }
public void setName(String name) { this.name = name; }
#Column(name="COMMENT", nullable = true, length = 256)
#Length(min = 0, max = 255)
public String getComment() { return this.comment; }
public void setComment(String comment) { this.comment = comment;}
#ManyToMany(cascade=CascadeType.REFRESH,fetch=FetchType.EAGER)
#JoinTable(
name = "USERS_ROLES"
, joinColumns = { #JoinColumn(name = "role_id") }
, inverseJoinColumns = { #JoinColumn(name = "user_id") }
)
public Set<User> getUsers() {
return this.users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
/*#Override toString/equals/hascode */
}
mails
#Entity
#Table(name = "mails")
public class Mail implements GenericDomain{
private Long id;
private String mailSubject;
private String mailContent;
private Long receiverId;
private User user = null;
public Mail(){
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID", nullable = false)
public Long getId(){ return this.id; }
public void setId(Long id){ this.id = id;}
#Column(name = "MAILSUBJECT", nullable = false, length = 63)
#Length(max = 63)
public String getMailSubject(){ return this.mailSubject; }
public void setMailSubject(String mailSubject){ this.mailSubject = mailSubject; }
#Column(name = "MAILCONTENT", nullable = true, length = 255)
#Length(max = 255)
public String getMailContent(){ return this.mailContent; }
public void setMailContent(String mailContent){ this.mailContent = mailContent; }
#Column(name = "RECEIVERID")
public Long getReceiverId(){ return this.receiverId; }
public void setReceiverId(Long receiverId){ this.receiverId = receiverId; }
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name = "USER_ID")
#NotNull
public User getUser(){ return this.user; }
public void setUser(User user){ this.user = user; }
}
user controller
#Controller
#RequestMapping("/admin/user")
#SessionAttributes("user")
public class UserController {
private UserService userService;
private RoleService roleService;
#Autowired
public UserController(UserService userService, RoleService roleService) {
this.userService = userService;
this.roleService = roleService;
}
#RequestMapping(value = "edit", method = RequestMethod.GET)
public String editUser(#RequestParam(value="id", required = true) Long id, ModelMap model) {
model.addAttribute("allRoles", roleService.getAll());
model.addAttribute("user", userService.getOne(id));
return "/admin/user/edit";
} }
mail controller
#Controller
#SessionAttributes("mail")
#RequestMapping("/portal/mail")
public class MailController{
#Autowired
private MailService mailService;
#RequestMapping(value = "ajaxLoad", method = RequestMethod.GET)
public #ResponseBody List<Mail> list(#RequestParam(value = "type", required = true) String type){
return mailService.getUserMails((Long) WebHelper.getPrincipal().getUser().getId(),type);
}
}
my web.xml
<filter>
<filter-name>SpringOpenEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SpringOpenEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
my edit.jsp for user
<select >
<c:forEach items="${allRoles}" var="role">
<option value="${role.id}" <c:if test="${fn:contains(roleSelected, role)}">selected="selected"</c:if> >${role.name}</option>
</c:forEach>
</select>
With all that, i edit.jsp for user is working fine with lazy=false.
With FetchType.EAGER am not able to get any of my mails, am getting into a cycle stackovrflow, without FetchType.EAGER i got that lazy exception.
removing all the eager and adding this solve my problem
<mvc:interceptors>
<bean class="org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
</mvc:interceptors>
the filter didnt work
OpenEntityManagerInViewFilter and OpenEntityManagerInViewInterceptor work. You are doing something wrong.
Apart from that, you can use Hibernate.initialize(..) to initialize your collections. But doing this manually is not preferred. Give more details of why the filter/interceptor don't work.
Update: Instead of mapping the filter to a pattern, map it to the dispatcher servlet. So instead of specifying <url-pattern> specfiy <servlet-name>.
First of all, check if you really need Collection rather than Set. If objects within collection are unique, declare variable as Set, which solves 90% of issues with LazyInitializationException.

Categories