Hibernate Exception when using mappedby attribute - java

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

Related

Hiberate one-to-one annotaion builds wrong sql query

I have a small problem with hibernate query with one-to-one relation
I created 3 entities. In case of one-to-one relation user-to-group it works properly. I use property create in hiberanate config and it creates correct table with correct FK.
Creating record work correct too
MyUser user = new MyUser();
user.setLogin("Mark");
user.setPassword("123456");
MyPresence presence = new MyPresence();
presence.setPresenceId(2);
presence.setUser(user);
session.beginTransaction();
session.save(user);
session.save(presence);
session.getTransaction().commit();
session.close();
if get User by presence it works correct
int id = 2;
MyPresence myPresence = session.load(MyPresence.class, id);
System.out.println(myPresence);
But when I'm try to get presence by user result from database hibernate build wrong sql query
int id = 3;
MyUser myUser = session.load(MyUser.class, id);
System.out.println(myUser);
Generated Hibernate sql:
Hibernate: select myuser0_.id as id1_2_0_, myuser0_.group_id as group_id4_2_0_, myuser0_.login as login2_2_0_, myuser0_.password as password3_2_0_, mypresence1_.id as id1_1_1_, mypresence1_.presence_id as presence2_1_1_, mypresence1_.updated_at as updated_3_1_1_, mypresence1_.user_id as user_id4_1_1_ from users myuser0_ left outer join user_presence mypresence1_ on myuser0_.id=mypresence1_.id where myuser0_.id=?
But I expect to see
on myuser0_.id=mypresence1_.user_id instead of on myuser0_.id=mypresence1_.id
MyUser.java
#Entity
#Table(name = "users")
public class MyUser {
private int id;
private String login;
private String password;
private MyGroup group;
private MyPresence presence;
public MyUser() {
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name = "login")
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
#Column(name = "password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#JoinColumn(name = "group_id")
#OneToOne(cascade = CascadeType.DETACH, fetch = FetchType.LAZY)
public MyGroup getGroup() {
return group;
}
public void setGroup(MyGroup group) {
this.group = group;
}
#OneToOne(cascade = CascadeType.DETACH)
#JoinColumn(name = "id", referencedColumnName = "user_id")
public MyPresence getPresence() {
return presence;
}
public void setPresence(MyPresence presence) {
this.presence = presence;
}
}
MyPresence.java
#Entity
#Table(name = "presence")
public class MyPresence {
private int id;
private MyUser user;
private int presenceId;
private Date updatedAt;
public MyPresence() {
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "user_id", referencedColumnName = "id")
public MyUser getUser() {
return user;
}
public void setUser(MyUser user) {
this.user = user;
}
#Column(name = "presence_id")
public int getPresenceId() {
return presenceId;
}
public void setPresenceId(int presenceId) {
this.presenceId = presenceId;
}
#Column(name = "updated_at")
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}

JPA OneToOne association without foreign key always fail

I am new to JPA/Hibernate,
I am creating a simple join for getting some data in different table
Let's see like this:
The purpose is getting the M_PROFILE data based on M_USER.username column, but clearly you see that there is no foreign key in M_PROFILE table.
I just try to use below code but have no results and always got error.
User Entity Class
#Entity
#Table(name = "M_USER")
public class User {
#Id
#Column(name = "id")
private String uuid;
#Column(name = "email")
private String email;
#Column(name = "username")
private String username;
#OneToOne(fetch = FetchType.LAZY)
#MapsId("username")
private Profile profile;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Profile getProfile() {
return profile;
}
public void setProfile(Profile profile) {
this.profile = profile;
}
}
Profile Entity Class
#Entity
#Table(name = "M_PROFILE")
public class Profile {
private String username;
private String phone;
private String address;
#Id
#Column(name = "username", nullable = false)
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Basic
#Column(name = "phone")
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
#Basic
#Column(name = "address")
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
I got different error when calling
User user = userRepository.findByUsername("aswzen");
String phone = user.getProfile().getPhone();
for example this one.
"USER0_"."PROFILE_USERNAME": invalid identifier
Need help, thanks in advance,
NB : i don't have privilege to alter the table..
Don't forget to disable insertable and updatable for JoinColumn
#OneToOne
#JoinColumn(name = "username", referencedColumnName = "username", updatable = false, insertable = false)
private profile profile;
Try to specify a join column:
#OneToOne
#JoinColumn(name = "username", referencedColumnName = "username")
private profile profile;
You do not really need the #MapsId here.
I recommend create third table with relations for your tables
#Entity
#Table(name = "M_USER")
public class User {
#OneToOne(fetch = FetchType.LAZY)
#JoinTable(
name = "user_profile",
joinColumns = #JoinColumn(name="user_id"),
inverseJoinColumns = #JoinColumn(name="profile_username")
)
private Profile profile;
UPDATE user_profile
SET user_id = (
SELECT id
FROM M_USER
);
UPDATE user_profile
SET profile_username = (
SELECT username
FROM M_USER
);

Spring is not using ManyToMany relationship

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

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