[英]i have error “no Session” in jpa-hibernate
我尝试通过jpa-hibernate,lazy join获取数据,但是我收到了一个错误。
我的东西:
表user_role
user_role_id username ROLE
2 petroff ROLE_ADMIN
表用户
id username password salt email profile phone repassword
6 petroff 12345 ${config.salt} petroff@еуые.com test petroff prifile "" 12345
零件类用户
@Entity
@Table(name = "tbl_user")
@Repassword(pass = "password", repass = "repassword")
public class User {
@Id
@Column(name = "id")
private int id;
@NotNull
@Size(min = 2, max = 64)
@Column(name = "username")
private String username;
@NotNull
@Size(min = 2, max = 64)
@Column(name = "password")
private String password;
@Column(name = "salt")
private String salt;
@Email
@Column(name = "email")
private String email;
@NotEmpty
@Column(name = "profile")
private String profile;
private String repassword;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
private Set<UserRole> userRole = new HashSet<UserRole>();
public Set<UserRole> getUserRole() {
return userRole;
}
public void setUserRole(Set<UserRole> userRole) {
this.userRole = userRole;
}
零件类UserRole
@Entity
@Table(name = "user_roles")
public class UserRole {
@Id
@Column(name = "user_role_id")
private Integer userRoleId;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "username", nullable = false)
private com.blog.blog.entity.User user;
@Column(name = "role", nullable = false, length = 45)
private String role;
//getter and setter methods
public Integer getUserRoleId() {
return userRoleId;
}
public void setUserRoleId(Integer userRoleId) {
this.userRoleId = userRoleId;
}
通话方法
@Autowired
UserService us;
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String printHello(ModelMap model, HttpSession session) {
com.blog.blog.entity.User u = us.getByUserName("petroff");
Set<UserRole> userRoles = u.getUserRole();
return "hello";
}
服务
@Service
@Transactional(readOnly = true)
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@PersistenceContext
private EntityManager entityManager;
@Override
public User addUser(User u) {
User savedUser = userRepository.saveAndFlush(u);
return savedUser;
}
@Override
public void delete(Integer id) {
userRepository.delete(id);
}
@Override
public User editUser(User u) {
return userRepository.saveAndFlush(u);
}
@Override
public List<User> getAll() {
return userRepository.findAll();
}
@Override
public User getByUserName(String name) {
return userRepository.findByUserName(name);
}
}
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/config.properties"/>
<context:component-scan base-package="com.blog.blog.service.impl"/>
<jpa:repositories base-package="com.blog.blog.repositories"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.drivers}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
<property name="database" value="MYSQL"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
<!-- spring based scanning for entity classes-->
<property name="packagesToScan" value="com.blog.blog.entity"/>
</bean>
<tx:annotation-driven/>
<bean id="userDetailsService"
class="com.blog.blog.service.impl.UserDetailsImpl">
</bean>
<import resource="spring-security.xml"/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"/>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true"/>
<tx:method name="find*" read-only="true"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<bean id="sessionFactory" class="org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<aop:config>
<aop:pointcut id="userServicePointCut"
expression="execution(* com.blog.blog.service.impl.*Service.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="userServicePointCut"/>
</aop:config>
</beans>
我得到用户obj
com.blog.blog.entity.User u = us.getByUserName("petroff");
但是当我打电话的时候
Set<UserRole> userRoles = u.getUserRole();
我收到一个错误:
Exception occurred in target VM: failed to lazily initialize a collection of role: com.blog.blog.entity.User.userRole, could not initialize proxy - no Session
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.blog.blog.entity.User.userRole, could not initialize proxy - no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:566)
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:186)
at org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:137)
at org.hibernate.collection.internal.PersistentSet.size(PersistentSet.java:156)
at com.blog.blog.controller.Main.printHello(Main.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at
如果要在调用者端使用它,则需要在服务中初始化延迟集合。 尝试这个
@Override
public User getByUserName(String name) {
User u = userRepository.findByUserName(name);
Hibernate.initialize(u.getUserRole());
return u;
}
有关此主题的在线讨论很多,如果您想了解更多有关该主题的背景信息,请查阅。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.