gpt4 book ai didi

java - Hibernate 延迟初始化 - 延迟初始化集合失败

转载 作者:行者123 更新时间:2023-12-03 20:43:09 25 4
gpt4 key购买 nike

每当我尝试从我的 Users 表中检索数据时,我都会收到以下错误,我在网上搜索了很多次,试图找出可能出错的地方,但找不到任何东西,所以有人可以通过告诉我来帮助我我错过了什么/我在这里错了吗?

错误:

ERROR: org.hibernate.LazyInitializationException - failed to lazily initialize a collection of role: com.domain.crm.domain.Role.users, no session or session was closed org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.domain.crm.domain.Role.users, no session or session was closed

用户类:

@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>

谢谢你的时间

最佳答案

我在这里发布示例。基本思想是只有 3 个数据库表,其中 2 个用于实体 UserRole,最后一个作为映射表,比如 user_role .在用户表中,我们存储用户详细信息,在角色表中,我们存储角色 ID 和名称,在我们的映射表中,我们将用户映射到角色。我从我自己的项目中复制。我的类扩展的 BaseEntity 只是一个映射的父类(super class),它具有每个实体的通用字段,例如 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 默认使用 eagerly fetch 类型,所以我们不需要设置它。现在,当我从我的服务中查询我的 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 查询。对我来说使用 eagerly fetch on the roles 是必要的,因为每次我想查询用户列表时,我不需要获取角色,因为在我的真实项目中角色也有一组权限和查询您不需要的东西是不值得的。

关于java - Hibernate 延迟初始化 - 延迟初始化集合失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21220234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com