我嘗試通過jpa-hibernate獲取數據,但是我得到一個錯誤。
這裏我的東西:我有jpa-hibernate中的「沒有會話」錯誤
表USER_ROLE
user_role_id username ROLE
2 petroff ROLE_ADMIN
表用戶
id username password salt email profile phone repassword
6 petroff 12345 ${config.salt} [email protected]еуые.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
刪除了用戶介紹,清理了代碼,格式化了問題 – CSchulz 2015-03-06 08:02:37