Saving the foreign key in a hibernate - java

I have two tables 1. User 2. USersLocation, In the location table I use the userId as foreign key. When I save the location object in database I want to save the current user Id as well in the table.
What I have tried so far is
SocialLogin Controller
SocialAuthManager manager = socialAuthTemplate.getSocialAuthManager();
AuthProvider provider = manager.getCurrentAuthProvider();
Profile userProfile = provider.getUserProfile();
Location Controller
UsersLocation location = new UsersLocation();
location.setSourceLat(SOURCE_LATITUDE);
location.setSourceLng(SOURCE_LONGITUDE);
location.setDestinationLat(DEST_LATITUDE);
location.setDestinationLng(DEST_LONGITUDE);
location.setUserId((User) WebUtils.getSessionAttribute(request, "userId"));
placesService.saveLocaion(location);
The Userslocation class is
#Entity
#Table(name = "locations")
public class UsersLocation implements Serializable{
private static final long serialVersionUID = 1L;
private double sourceLat;
private double sourceLng;
private double destinationLat;
private double destinationLng;
public UsersLocation(){}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int locationId;
#ManyToOne
#JoinColumn(name = "userId")
private User user;
public void setUserId(User user){
this.user = user;
}
public User getUserId(){
return user;
}
#Column(name = "SourceLat", nullable = false)
public double getSourceLat(){
return sourceLat;
}
public void setSourceLat(double sourceLat){
this.sourceLat = sourceLat;
}
#Column(name = "SourceLng", nullable = false)
public double getSourceLng(){
return sourceLng;
}
public void setSourceLng(double sourceLng){
this.sourceLng = sourceLng;
}
#Column(name = "DestinationLat", nullable = false)
public double getDestinationLat(){
return destinationLat;
}
public void setDestinationLat(double destinationLat){
this.destinationLat = destinationLat;
}
#Column(name = "DestinationLng", nullable = false)
public double getDestinationLng(){
return destinationLng;
}
public void setDestinationLng(double destinationLng){
this.destinationLng = destinationLng;
}
}
User Class
#Entity
#Table(name = "users")
public class User implements Serializable{
private static final long serialVersionUID = 1L;
private Integer userId;
private String email;
private String lastName;
private String firstName;
private String location;
public User() {
}
#Id
#Column(name = "userId", unique = true, nullable = false)
public Integer getUserId() {
return this.userId;
}
public Integer setUserId(Integer socialId) {
return this.userId = socialId;
}
#Column(name = "email", nullable = false, length = 50)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name = "firstName", nullable = true, length = 20)
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "lastName", nullable = true, length = 20)
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Column(name = "location", nullable = true, length = 50)
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
When I save the location I get the userId NULL,I am new to hibernate kindly help me
Thanks

Save the whole user object to the session like below instead of just the userId, as later you need to set the full User object in location.setUserId(user);
WebUtils.setSessionAttribute(request, "userId", user)

If you're saying that you want to save a Location in the database along with the UserId, you have this relation wrong. This should be a OneToOne, since each location will have only one UserId associated.
On the other hand, if you're trying to set a location capable of storing many userIds, you're also doing it wrong because you should be saving a set of users, something like:
#OneToMany(mappedBy = "UsersLocation")
private Set<User> user;
It's not really clear what you're trying to do, but I'm pretty sure your mistake lies in the fact that you're doing the relations in the wrong way.

Related

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

How to persist entity with joining?

I am confused about how to save entry in db with column's join. I have #Entity bellow
#XmlRootElement
#XmlAccessorType(value = XmlAccessType.FIELD)
#Entity
#Table(name = "psc_users")
#NamedQuery(name = "User.findAll", query = "SELECT u FROM User u")
public class User implements Serializable {
private static final long serialVersionUID = 8885916014620036457L;
#Id
private static final String SEQUENCE_NAME = "psc_users_user_id_seq";
#Id
#GeneratedValue(generator = "UseExistingOrGenerateIdGenerator",
strategy = GenerationType.SEQUENCE)
#GenericGenerator(name = "UseExistingOrGenerateIdGenerator",
strategy = "com.psc.util.UseExistingOrGenerateIdGenerator",
parameters = {
#org.hibernate.annotations.Parameter(name = "sequence", value = SEQUENCE_NAME)
}
)
#Column(name = "USER_ID")
private Long userId;
#Column(name = "DEF", length = 30)
private String def;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "DEL_DATE")
private Date delDate;
#Column(name = "DISPLAY_DEF", length = 60)
private String displayDef;
#Column(name = "EMAIL", length = 60)
private String email;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "NAVI_DATE")
private Date naviDate;
#Column(name = "NAVI_USER")
private String naviUser;
#Column(name = "PHONE", length = 30)
private String phone;
#Column(name = "PWD", length = 40)
private String pwd;
//bi-directional many-to-one association to Branch
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "BRNC_BRNC_ID", nullable = false)
private Branch pscBranch;
public Long getBrncBrncId() {
return brncBrncId;
}
public void setBrncBrncId(Long brncBrncId) {
this.brncBrncId = brncBrncId;
}
#Column(name = "BRNC_BRNC_ID", insertable = false, updatable = false)
private Long brncBrncId;
//bi-directional many-to-one association to User
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "CURATOR_USER_ID")
private User pscUser;
public Long getCuratorUserId() {
return curatorUserId;
}
public void setCuratorUserId(Long curatorUserId) {
this.curatorUserId = curatorUserId;
}
#Column(name = "CURATOR_USER_ID", insertable = false, updatable = false)
private Long curatorUserId;
public User() {
}
public Long getUserId() {
return this.userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getDef() {
return this.def;
}
public void setDef(String def) {
this.def = def;
}
public Date getDelDate() {
return this.delDate;
}
public void setDelDate(Date delDate) {
this.delDate = delDate;
}
public String getDisplayDef() {
return this.displayDef;
}
public void setDisplayDef(String displayDef) {
this.displayDef = displayDef;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getNaviDate() {
return this.naviDate;
}
public void setNaviDate(Date naviDate) {
this.naviDate = naviDate;
}
public String getNaviUser() {
return this.naviUser;
}
public void setNaviUser(String naviUser) {
this.naviUser = naviUser;
}
public String getPhone() {
return this.phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPwd() {
return this.pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public Branch getPscBranch() {
return this.pscBranch;
}
public void setPscBranch(Branch pscBranch) {
this.pscBranch = pscBranch;
}
public User getPscUser() {
return this.pscUser;
}
public void setPscUser(User pscUser) {
this.pscUser = pscUser;
}
}
if I save User instance without field pscUser (here null) but there is valid CuratorUserId with correct value I end up in a situation with empty CuratorUserId in db. If you look at code then you will see these bound fields.
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "CURATOR_USER_ID")
private User pscUser;
#Column(name = "CURATOR_USER_ID", insertable = false, updatable = false)
private Long curatorUserId;
code to save user
repositoryUser.save(user);
this i see in debugger
this i see in database after saving my user.
sorry for my stupid question but I come across on a different behavior, there is code in my project which behaves in another manner. I don't want to search actual another user(curator) for saving my user, because of overhead on query
The #Column annotation on the curetorUserId field has properties
insertable=false and updatable=false, which means that its value is ignored during inserts and updates.
You can either change these properties to true (but it can break your application in some other places) or just fill in pscUser field using EntityManager.getReference, which just creates a proxy and doesn't actualy produce a query to the database.
Your mapping should look like the below:
#XmlRootElement
#XmlAccessorType(value = XmlAccessType.FIELD)
#Entity
#Table(name = "psc_users")
#NamedQuery(name = "User.findAll", query = "SELECT u FROM User u")
public class User implements Serializable {
private static final long serialVersionUID = 8885916014620036457L;
#Id
private static final String SEQUENCE_NAME = "psc_users_user_id_seq";
#Id
#GeneratedValue(generator = "UseExistingOrGenerateIdGenerator",
strategy = GenerationType.SEQUENCE)
#GenericGenerator(name = "UseExistingOrGenerateIdGenerator",
strategy = "com.psc.util.UseExistingOrGenerateIdGenerator",
parameters = {
#org.hibernate.annotations.Parameter(name = "sequence", value = SEQUENCE_NAME)
}
)
#Column(name = "USER_ID")
private Long userId;
#Column(name = "DEF", length = 30)
private String def;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "DEL_DATE")
private Date delDate;
#Column(name = "DISPLAY_DEF", length = 60)
private String displayDef;
#Column(name = "EMAIL", length = 60)
private String email;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "NAVI_DATE")
private Date naviDate;
#Column(name = "NAVI_USER")
private String naviUser;
#Column(name = "PHONE", length = 30)
private String phone;
#Column(name = "PWD", length = 40)
private String pwd;
//bi-directional many-to-one association to Branch
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "BRNC_BRNC_ID", nullable = false)
private Branch pscBranch;
//bi-directional many-to-one association to User
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "CURATOR_USER_ID")
private User pscUser;
public User() {
}
}
You need to think in terms of objects. The FK will only be set in the database if you set the pscUser reference to an instance of a User. If this is an existing User then you need to set a reference to the existing persistent entity.
Real answer is that I have two points for saving and updating my entity. Please see this Hibernate: Where do insertable = false, updatable = false belong in composite primary key constellations involving foreign keys?

OneToMany between 2 classes with Hibernate

I'm trying to get the hang of Hibernate.
After getting my project to compile, I've started to convert my classes to be "Hibernate-enabled"
Currently, I'm having 2 classes
1) Person (id, name, firstname, ...)
2) Task (Id, name, description, idOwner)
I would like to have a OneToMany relationship between Person(id) and Task (idOwner)
So when the users gets the List from the Person class, they would get all the tasks linked to that.
After some trying and failing, here's my current code:
Person.java
#Entity
#Table(name = "people", uniqueConstraints = {
#UniqueConstraint(columnNames = "PERSON_ID")
})
public class Person implements Serializable {
private int id;
private String firstName;
private String name;
private String function;
private String email;
private String password;
private RoleEnum role;
private List<Task> lstTasks;
public Person(String firstName, String name, String function) {
this.firstName = firstName;
this.name = name;
this.function = function;
this.email = "";
this.password = "";
this.setRole(RoleEnum.User);
}
// <editor-fold defaultstate="collapsed" desc="Getters">
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "PERSON_ID", unique = true, nullable = false)
public int getId() {
return id;
}
#Column(name = "PERSON_FIRSTNAME", unique = false, nullable = false, length = 30)
public String getFirstName() {
return firstName;
}
#Column(name = "PERSON_NAME", unique = false, nullable = false, length = 30)
public String getName() {
return name;
}
#Column(name = "PERSON_FUNCTION", unique = false, nullable = false, length = 30)
public String getFunction() {
return function;
}
#Column(name = "PERSON_EMAIL", unique = false, nullable = false, length = 30)
public String getEmail() {
return email;
}
#Column(name = "PERSON_PASSWORD", unique = false, nullable = false, length = 30)
public String getPassword() {
return password;
}
#Column(name = "PERSON_ROLE", unique = false, nullable = false, length = 30)
public RoleEnum getRole() {
return role;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "idOwner")
public List<Task> getLstTasks() {
return lstTasks;
}
//Setters
}
Task.java
#Entity
#Table(name="tasks", uniqueConstraints =
#UniqueConstraint(columnNames = "TASK_ID"))
public class Task implements Serializable {
private int id;
private String name;
private String description;
private int idOwner;
public Task(int id, String name, int idOwner) {
this.id = id;
this.name = name;
this.idOwner = idOwner;
}
// <editor-fold defaultstate="collapsed" desc="Getters">
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "TASK_ID", unique = true, nullable = false)
public int getId() {
return id;
}
#Column(name = "TASK_NAME")
public String getName() {
return name;
}
#Column(name = "TASK_DESCRIPTION")
public String getDescription() {
return description;
}
#Column(name = "TASK_ID_OWNER")
public int getIdOwner() {
return idOwner;
}
// </editor-fold>
//Setters
}
Can somebody tell/show/explain me what I have to do exactly, to make this work?
Currently your mapping should linking ownerId instead of Task class.
Change your Task class to this
private Person person;
#ManyToOne
#JoinColumn(name = "TASK_ID_OWNER")
public Person getPerson() {
return person;
}
In your Person entity you have declared one-to-many relationship with Task entity like this:
#OneToMany(fetch = FetchType.LAZY, mappedBy = "idOwner")
public List<Task> getLstTasks() {
return lstTasks;
}
Here you have given idOwner to mappedBy attribute, it means you are telling hibernate that there is property in Task class called idOwner which is of type Person.
So you have to modify your Tasks class like this (Changing the variable type from int to Person):
private Person idOwner;
#ManyToOne
#JoinColumn(name = "TASK_ID_OWNER")
public Person getIdOwner() {
return idOwner;
}
public void setIdOwner(Person idOwner) {
this.idOwner=idOwner;
}
If you remove the #JoinColumn annotation then hibernate will create a Join table for your relationship, else it will just create a foreign key in Task table with foreign key column name as TASK_ID_OWNER.

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