每当我尝试从Users表中检索数据时,我都会收到以下错误,我搜索了很多网页,试图找出可能出错的但却找不到任何内容,所以有人可以通过告诉我帮助我我错过了什么/我错在这里?
错误:
错误:org.hibernate.LazyInitializationException - 懒得失败 初始化角色集合:com.domain.crm.domain.Role.users,no 会议或会议已结束 org.hibernate.LazyInitializationException:懒得初始化 角色集合:com.domain.crm.domain.Role.users,没有会话或 会议已经结束
用户类:
@Entity
@Table(name="COM_USER")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="USER_ID")
private Long id;
@Column(name="USER_NAME",nullable=false,length=25,unique=true)
private String userName;
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="ROLE_ID",nullable=false)
private Role role;
}
角色类:
@Entity
@Table(name="COM_ROLE")
public class Role {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="ROLE_ID")
private Long id;
@Column(name="ROLE",nullable=false,unique=false)
private Integer Role;
@OneToMany(mappedBy="role")
private Set<User> users=new HashSet<User>();
}
用户DAO类调用以收集所有用户的方法:
public List<User> getUsers(Long page, Long pageSize) {
Long start = (page-1)*pageSize;
return sessionfactory.getCurrentSession().createQuery("from User u ").setFirstResult(start.intValue()).setMaxResults(pageSize.intValue()).list();
}
用户服务类方法:
@Transactional
public List<User> getUsers(Long page, Long pageSize) {
return userdao.getUsers(page, pageSize);
}
调用方法的Controller类:
@RequestMapping(value = "/users/list-user-data")
@ResponseBody
public UserListData listUserData(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
UserListData listData = new UserListData();
String page = request.getParameter("page");
Long pageLong = Long.parseLong(page);
Long pageSize = (long)15;
List<User> searchResults = iuserservice.getUsers(pageLong, pageSize);
if( searchResults != null ){
List<List<Object>> aaData = new ArrayList<List<Object>>();
List<Object> listItem = null;
for( User u : searchResults ){
listItem = new ArrayList<Object>();
listItem.add(u.getLastName());
listItem.add(u.getFirstName());
listItem.add(u.getUserName());
listItem.add(u.getEmail());
listItem.add(u.getRole());
aaData.add(listItem);
}
listData.setAaData(aaData);
}
int totalCount = iuserservice.getAllUsersCount().intValue();
System.out.println("Number of records in DB: "+totalCount);
listData.setiTotalRecords(totalCount);
return listData;
}
最后这是我的pom.xml依赖项:
<properties>
<java-version>1.6</java-version>
<org.springframework-version>3.1.0.RELEASE</org.springframework-version>
<org.aspectj-version>1.6.9</org.aspectj-version>
<org.slf4j-version>1.5.10</org.slf4j-version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
<scope>runtime</scope>
</dependency>
<!-- @Inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>3.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>3.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>3.1.3.RELEASE</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- Mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.6.0.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- Commons DBCP -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.1</version>
</dependency>
</dependencies>
感谢您的时间
答案 0 :(得分:4)
我在这里发布了这个例子。基本思路就是拥有3个数据库表,其中2个用于实体User
和Role
,最后一个用作映射表,比如user_role
。在用户表中我们存储用户详细信息,在角色表中我们存储角色id和名称,在我们的映射表中我们将用户映射到角色。我从我自己的项目中复制。我的类扩展的BaseEntity只是一个映射的超类,它具有每个实体的通用字段,如id,创建/修改日期等。
用户实体
@Entity
@Table(name = "user_t")
public class User extends BaseEntity {
@Column(name = "username", nullable = false, unique = true)
private String userName;
@Column(name = "password", nullable = false)
private String password;
@ManyToMany
@JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> role = new HashSet<Role>();
// getters & setters
}
角色实体
@Entity(name = "role_t")
public class Role extends BaseEntity {
@Column(name = "role_name", nullable = false)
private String roleName;
public Role() {
}
public Role(String roleName) {
this.roleName = roleName;
}
// getters & setters
}
请注意,ManyToMany
默认使用急切获取类型,因此我们不需要设置它。现在,当我从我的服务中查询我的User
实体时。无法获取role
集合。如果我需要获取属于该用户的角色,那么我需要使用查询手动获取它们。我使用Spring Data JPA存储库,例如,对于单个结果,查询看起来就像那样。
UserRepository类
public interface UserRepository extends JpaRepository<User, Long> {
@Query("SELECT u FROM User u JOIN FETCH u.role WHERE u.userName = (:userName)")
public User findByUserNameAndFetchRoles(@Param("userName") String userName);
@Query("FROM User u JOIN FETCH u.role")
public List<User> getAllUsersAndFetchRoles(); // **query that you would use!**
}
然后在您的UserService
图层中,您将使用该存储库/ DAO查询。对我来说,使用热切的角色获取是必要的,因为每次我想查询用户列表时,我都不需要获取角色,因为在我的真实项目中角色也有一组权限和查询你不需要的东西是不值得的。
答案 1 :(得分:2)
问题是@OneToMany
关联在默认情况下是惰性的,当您调用getUsers()
时,会话已在您的服务方法中关闭。
解决这个问题的一种方法是急切地加载子记录。 但请注意,因为这可能会导致您加载太多数据,这会降低数据速度并消耗内存。例如,在Role
实体中,如果您将其设置为急切加载{{ 1}}:
Users
每当您加载@OneToMany(mappedBy="role", fetch = FetchType.EAGER)
private Set<User> users=new HashSet<User>();
}
时,Hibernate都会加载其所有子Role
。
处理你的案例的一种方法是在Users
方法内完成服务的所有工作,这应该确保会话仍然是开放的(最好有服务方法@Transactional
而不是DAO)
@Transactional
答案 2 :(得分:0)
某处(上面的代码中未显示)您正在访问users
实体中Role
集合字段的某种方法。
答案 3 :(得分:0)
您无法使用eager fetch类型从同一事务加载Roles
集合。要解决此问题,您需要手动初始化角色集合或对查询执行fetch join
。这应该为你解决。
public List<User> getUsers(Long page, Long pageSize) {
Long start = (page-1)*pageSize;
return sessionfactory.getCurrentSession().createQuery("FROM User u JOIN FETCH u.role ").setFirstResult(start.intValue()).setMaxResults(pageSize.intValue()).list();
}
另外,我建议在ManyToMany
和User
之间建立Roles
关系并使用映射表。使用以下内容并从角色实体中删除用户集。在角色表上复制角色记录是多余的。
@ManyToMany
@JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> role = new HashSet<Role>();