java - 使用 hibernate 和 gilead for gwt 添加到实体类中保存的列表时出现 LazyInitializationException

标签 java hibernate orm gwt gilead

是的,所以我正在使用 hibernate gilead 和 gwt 将我的数据保存在网站的用户和文件上。我的用户有一个文件位置列表。我正在使用注释将我的类映射到数据库。当我尝试将文件位置添加到用户类中保存的列表时,出现了 org.hibernate.LazyInitializationException

这是下面的一个方法,它被我正在使用的外部文件上传 servlet 类覆盖。当文件上传时它调用这个方法。

user1 是从别处的数据库加载的。 异常发生在 user1.getFileLocations().add(fileLocation); 处。我真的完全不明白。任何帮助都会很棒。错误的堆栈跟踪如下

public String executeAction(HttpServletRequest request,
            List<FileItem> sessionFiles) throws UploadActionException {
          for (FileItem item : sessionFiles) {
              if (false == item.isFormField()) {
                try {
                    YFUser user1 = (YFUser)getSession().getAttribute(SESSION_USER);

                    // This is the location where a file will be stored

                    String fileLocationString = "/Users/Stefano/Desktop/UploadedFiles/" + user1.getUsername();
                    File fl = new File(fileLocationString);
                    fl.mkdir();
                    // so here i will create the a file container for my uploaded file

                  File file = File.createTempFile("upload-", ".bin",fl);


                  // this is where the file is written to disk

                  item.write(file);

                  // the FileLocation object is then created
                  FileLocation fileLocation = new FileLocation();
                  fileLocation.setLocation(fileLocationString);
                  //test
                  System.out.println("file path = "+file.getPath());



                  user1.getFileLocations().add(fileLocation);

                  //the line above is where the exception occurs 

                } catch (Exception e) {
                  throw new UploadActionException(e.getMessage());
                }
              }
              removeSessionFileItems(request);
            }
            return null;
    }  

//这是您的文件用户的类文件

@Entity
@Table(name = "yf_user_table")
public class YFUser implements Serializable,ILightEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id",nullable = false)
private int userId;
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
@Column(name = "email")
private String email;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "USER_FILELOCATION", joinColumns = { 
        @JoinColumn(name = "user_id") }, inverseJoinColumns = { 
        @JoinColumn(name = "locationId") })
private List<FileLocation> fileLocations = new ArrayList<FileLocation>() ;

public YFUser(){

}

public int getUserId() {
    return userId;
}

private void setUserId(int userId) {
    this.userId = userId;
}

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 getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public List<FileLocation> getFileLocations() {
    if(fileLocations ==null){
        fileLocations = new ArrayList<FileLocation>();
    }
    return fileLocations;

}

public void setFileLocations(List<FileLocation> fileLocations) {
    this.fileLocations = fileLocations;
}
/*
public void addFileLocation(FileLocation location){
    fileLocations.add(location);
}*/

@Override
public void addProxyInformation(String property, Object proxyInfo) {
    // TODO Auto-generated method stub

}

@Override
public String getDebugString() {
    // TODO Auto-generated method stub
    return null;
}

@Override
public Object getProxyInformation(String property) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public boolean isInitialized(String property) {
    // TODO Auto-generated method stub
    return false;
}

@Override
public void removeProxyInformation(String property) {
    // TODO Auto-generated method stub

}

@Override
public void setInitialized(String property, boolean initialised) {
    // TODO Auto-generated method stub

}

@Override
public Object getValue() {
    // TODO Auto-generated method stub
    return null;
}

@Entity
@Table(name = "fileLocationTable")
public class FileLocation implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "locationId", updatable = false, nullable = false)
private int ieId;
@Column (name = "location")
private String location;


public FileLocation(){

}

public int getIeId() {
    return ieId;
}

private void setIeId(int ieId) {
    this.ieId = ieId;
}

public String getLocation() {
    return location;
}

public void setLocation(String location) {
    this.location = location;
}

Apr 2, 2010 11:33:12 PM org.hibernate.LazyInitializationException <init>
SEVERE: failed to lazily initialize a collection of role: com.example.client.YFUser.fileLocations, no session or session was closed
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.example.client.YFUser.fileLocations, no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:380)
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:372)
at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:365)
at org.hibernate.collection.AbstractPersistentCollection.write(AbstractPersistentCollection.java:205)
at org.hibernate.collection.PersistentBag.add(PersistentBag.java:297)
at com.example.server.TestServiceImpl.saveFileLocation(TestServiceImpl.java:132)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at net.sf.gilead.gwt.PersistentRemoteService.processCall(PersistentRemoteService.java:174)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:224)
at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:713)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:806)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:729)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.handler.RequestLogHandler.handle(RequestLogHandler.java:49)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:324)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505)
at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:843)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:647)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:396)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488)
Apr 2, 2010 11:33:12 PM net.sf.gilead.core.PersistentBeanManager clonePojo
INFO: Third party instance, not cloned : org.hibernate.LazyInitializationException:     failed to lazily initialize a collection of role: com.example.client.YFUser.fileLocations, no session or session was closed

最佳答案

惰性意味着集合的值只有在被访问时才从数据库中加载。如果此时 Session 已关闭,则抛出 LazyInitializationException,因为无法获取数据。

在你的情况下,我只是建议向关联添加一个急切的获取类型:

@ManyToMany(cascade = CascadeType.ALL, fetchType=FetchType.EAGER)

这将在加载实体时加载 fileLocations,并且不需要延迟加载。

一个常见的解决方案是使用 OpenSessionInView , 但它可能并不总是与 GWT 一起工作,因为客户端是远程的并且无法在那里打开 session 。

所以你会遇到延迟初始化的一些问题。相关问题大家可以搜索一下,有几个-thisthis例如。

关于java - 使用 hibernate 和 gilead for gwt 添加到实体类中保存的列表时出现 LazyInitializationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2569648/

相关文章:

java - 在 AWS lambda java 中使用 Thread.sleep 是个好主意吗

hibernate - Seam 2.x 和 Hibernate 3.5?

java - 如何替换 fragment 运行时

java - 404-MVC 中找不到资源

java - 我的 Java 代码遇到一些问题。在循环中区分正数和负数时不会运行

java - Spring + hibernate : Initializing database with JUnit doesn't work

mysql - 调试约 39 分钟后关闭的 MySQL 连接的最佳方法?

java - 组织.hibernate.MappingException : <mapping> element in configuration specifies no known attributes

orm - Clojure - 处理数据库持久性的惯用方法

java - Java中接口(interface)使用的一些疑惑(创建Hibernate DAO)