TimVD
Aug 14th, 2011, 11:14 AM
Hi I'm trying to build a Spring MVC application with Hibernate.
for now my DAO looks like this:
import java.util.ArrayList;
import javax.annotation.Resource;
import org.goldendragon.yahtzee.model.Player;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.User nameNotFoundException;
import org.springframework.stereotype.Repository;
@Repository("playerDAO")
public class PlayerDAO {
@Resource(name="sessionFactory")
private SessionFactory sessionFactory;
private static final Logger logger = LoggerFactory.getLogger(PlayerDAO.class);
public Player getPlayerById( Integer id ) {
Session session = sessionFactory.getCurrentSession();
Player player = (Player) session.get(Player.class, id);
return player;
}
public Player getPlayerByUserName(String username) throws UsernameNotFoundException, Exception{
Player player = null;
try{
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("FROM Player WHERE username = :un ");
query.setParameter("un", username);
@SuppressWarnings("unchecked")
ArrayList<Player> list = (ArrayList<Player>) query.list();
player = (Player) list.get(0);
}catch(IndexOutOfBoundsException iob){
throw new UsernameNotFoundException("Username not found!");
}catch(Exception e){
throw new Exception("Error in retrieving user");
}
return player;
}
public void addPlayer(Player player){
logger.info("Registration of new player: " + player.getUsername());
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
session.save(player);
}
}
I have added
@Repository("playerDAO")
so I can inject the DAO in other classes like this:
@Autowired
private PlayerDAO playerDAO;
However this results in the error message "No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here" when calling the method addPlayer from my controller.
After reading some topics I discovered I had to put "@Transactional" at the top of my DAO-class. But when I do this the project fails to build. And I get this output:
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building abc
[INFO] task-segment: [tomcat:run]
[INFO] ------------------------------------------------------------------------
[INFO] Preparing tomcat:run
[INFO] [aspectj:compile {execution: default}]
[ERROR] The attribute value is undefined for the annotation type Repository
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Compiler errors :
error at @Repository("playerDAO")
^^^^^^^^^^
/home/tim/Desktop/Yahtzee-Workspace/src/main/java/org/goldendragon/yahtzee/dao/PlayerDAO.java:17:0::0 The attribute value is undefined for the annotation type Repository
[INFO] ------------------------------------------------------------------------
[INFO] For more information, run Maven with the -e switch
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 7 seconds
[INFO] Finished at: Sun Aug 14 18:12:58 CEST 2011
[INFO] Final Memory: 15M/127M
[INFO] ------------------------------------------------------------------------
This is my hibernate-context.xml:
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<!-- Enable annotation style of managing transactions -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- Declare the Hibernate SessionFactory for retrieving Hibernate sessions -->
<!-- See http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/orm/hibernate3/annotation/AnnotationSessionFactoryBean.html -->
<!-- See http://docs.jboss.org/hibernate/stable/core/api/index.html?org/hibernate/SessionFactory.html -->
<!-- See http://docs.jboss.org/hibernate/stable/core/api/index.html?org/hibernate/Session.html -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.Anno tationSessionFactoryBean"
p:dataSource-ref="dataSource"
p:configLocation="/WEB-INF/config/hibernate.cfg.xml"
p:packagesToScan="org.goldendragon.yahtzee"/>
<!-- Declare a datasource that has pooling capabilities-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close"
p:driverClass="com.mysql.jdbc.Driver"
p:jdbcUrl="jdbc:mysql://localhost/yahtzee"
p:user="yahtzee"
p:password="paswoord"
p:acquireIncrement="5"
p:idleConnectionTestPeriod="60"
p:maxPoolSize="100"
p:maxStatements="50"
p:minPoolSize="10" />
<!-- Declare a transaction manager-->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransa ctionManager" p:sessionFactory-ref="sessionFactory" />
</beans>
and my hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property name="show_sql">false</property>
<property name="hbm2ddl.auto">create</property>
</session-factory>
</hibernate-configuration>
if anyone can point out what I'm doing wrong I would greatly appreciate it
for now my DAO looks like this:
import java.util.ArrayList;
import javax.annotation.Resource;
import org.goldendragon.yahtzee.model.Player;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.User nameNotFoundException;
import org.springframework.stereotype.Repository;
@Repository("playerDAO")
public class PlayerDAO {
@Resource(name="sessionFactory")
private SessionFactory sessionFactory;
private static final Logger logger = LoggerFactory.getLogger(PlayerDAO.class);
public Player getPlayerById( Integer id ) {
Session session = sessionFactory.getCurrentSession();
Player player = (Player) session.get(Player.class, id);
return player;
}
public Player getPlayerByUserName(String username) throws UsernameNotFoundException, Exception{
Player player = null;
try{
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("FROM Player WHERE username = :un ");
query.setParameter("un", username);
@SuppressWarnings("unchecked")
ArrayList<Player> list = (ArrayList<Player>) query.list();
player = (Player) list.get(0);
}catch(IndexOutOfBoundsException iob){
throw new UsernameNotFoundException("Username not found!");
}catch(Exception e){
throw new Exception("Error in retrieving user");
}
return player;
}
public void addPlayer(Player player){
logger.info("Registration of new player: " + player.getUsername());
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
session.save(player);
}
}
I have added
@Repository("playerDAO")
so I can inject the DAO in other classes like this:
@Autowired
private PlayerDAO playerDAO;
However this results in the error message "No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here" when calling the method addPlayer from my controller.
After reading some topics I discovered I had to put "@Transactional" at the top of my DAO-class. But when I do this the project fails to build. And I get this output:
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building abc
[INFO] task-segment: [tomcat:run]
[INFO] ------------------------------------------------------------------------
[INFO] Preparing tomcat:run
[INFO] [aspectj:compile {execution: default}]
[ERROR] The attribute value is undefined for the annotation type Repository
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Compiler errors :
error at @Repository("playerDAO")
^^^^^^^^^^
/home/tim/Desktop/Yahtzee-Workspace/src/main/java/org/goldendragon/yahtzee/dao/PlayerDAO.java:17:0::0 The attribute value is undefined for the annotation type Repository
[INFO] ------------------------------------------------------------------------
[INFO] For more information, run Maven with the -e switch
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 7 seconds
[INFO] Finished at: Sun Aug 14 18:12:58 CEST 2011
[INFO] Final Memory: 15M/127M
[INFO] ------------------------------------------------------------------------
This is my hibernate-context.xml:
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<!-- Enable annotation style of managing transactions -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- Declare the Hibernate SessionFactory for retrieving Hibernate sessions -->
<!-- See http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/orm/hibernate3/annotation/AnnotationSessionFactoryBean.html -->
<!-- See http://docs.jboss.org/hibernate/stable/core/api/index.html?org/hibernate/SessionFactory.html -->
<!-- See http://docs.jboss.org/hibernate/stable/core/api/index.html?org/hibernate/Session.html -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.Anno tationSessionFactoryBean"
p:dataSource-ref="dataSource"
p:configLocation="/WEB-INF/config/hibernate.cfg.xml"
p:packagesToScan="org.goldendragon.yahtzee"/>
<!-- Declare a datasource that has pooling capabilities-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close"
p:driverClass="com.mysql.jdbc.Driver"
p:jdbcUrl="jdbc:mysql://localhost/yahtzee"
p:user="yahtzee"
p:password="paswoord"
p:acquireIncrement="5"
p:idleConnectionTestPeriod="60"
p:maxPoolSize="100"
p:maxStatements="50"
p:minPoolSize="10" />
<!-- Declare a transaction manager-->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransa ctionManager" p:sessionFactory-ref="sessionFactory" />
</beans>
and my hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property name="show_sql">false</property>
<property name="hbm2ddl.auto">create</property>
</session-factory>
</hibernate-configuration>
if anyone can point out what I'm doing wrong I would greatly appreciate it