我有以下课程:
@Entity
@Table(name="Player")
public class Player {
private String id;
private Set<String> nicknames = new HashSet<String>();
@ElementCollection(fetch=FetchType.LAZY)
@CollectionTable(name="Nicknames", joinColumns=@JoinColumn(name="user_id"))
@Column(name="nickname")
public Set<String> getNicknames() {
return nicknames;
}
}
我的DaoServiceImpl看起来像这样:
@Repository("daoService")
public class DaoServiceImpl implements DaoService {
@Autowired
SessionFactory sessionFactory;
@Override
public String addPlayer(Player player){
Session session = sessionFactory.getCurrentSession();
return (String) session.save(player);
}
@Override
public Player getPlayer(String id){
Session session = sessionFactory.getCurrentSession();
return (Player)session.load(Player.class, id);
}
@Override
public void updatePlayer(Player player){
Session session = sessionFactory.getCurrentSession();
session.update(player);
}
}
我的交易管理器看起来像这样:
<aop:config>
<aop:pointcut id="daoServicePoint"
expression="execution(* com.vanilla.daoService.DaoService.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="daoServicePoint"/>
</aop:config>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
在我的主要功能中,我正在做以下事情:
public void run(){
Player player = new Player();
player.addNickName("Nick1");
player.addNickName("Nick2");
player.setFirstName("Danny");
player.setLastName("Lesnik");
String playerId = daoService.addPlayer(player);
player = daoService.getPlayer(playerId);
player.addNickName("Nick4");
player.removeNickName("Nick2");
daoService.updatePlayer(player);
}
我在player.addNickName
Exception in thread "main" org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:167)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:215)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:190)
at com.vanilla.objects.Player_$$_javassist_0.addNickName(Player_$$_javassist_0.java)
at com.vanilla.main.Main.run(Main.java:27)
at com.vanilla.main.Main.main(Main.java:36)
如果是Web应用程序,我会使用OpenSessionIviewFilter。 我应该如何解决Spring Hibernate Java Console Application?
我知道我可以使用连接HQL查询或使其成为Eager,但我想让它懒得用于自学习目的:)
答案 0 :(得分:0)
String playerId = daoService.addPlayer(player); 在上面的代码中,您保存实体并在当前会话关闭。之后,您尝试使用相同的会话加载玩家。但是没有开放会话。你必须在getPlayer方法中打开新会话,
您的代码应该更改为
public Player getPlayer(String id){ 会话会话= sessionFactory.openSession(); return(Player)session.load(Player.class,id); }