#Transactional questions and how to use with #Service - java

My service makes use of a generic DAO (which explicitly uses Hibernate session factory). I have spent some time before I discovered this error
org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
I annotated my service and all works perfectly. Now I want to use context path scanning, and remove this line from my configuration:
<bean id="societaService" class="it.trew.prove.services.SocietaService" />
So.... here's my final version:
#Service
#Transactional(readOnly = true)
public class SocietaService {
private Dao societaDao;
#Autowired
public void setSocietaDao(Dao societaDao) {
this.societaDao = societaDao;
}
public void salvaSocieta(Societa s) {
societaDao.save(s);
}
public List<Societa> listAll() {
return societaDao.getAll(Societa.class);
}
public void deleteById(Long id) {
societaDao.delete(getSocieta(id));
}
public Societa getSocieta(String id) {
return getSocieta(Long.parseLong(id));
}
public Societa getSocieta(Long id) {
return societaDao.get(Societa.class, id);
}
}
Adding #Service annotation makes my app give the awful hibernate error above. Why?
Removing #Service and configuring the service bean via xml = it works. WHY??
In addition:
does transactional annotating my service class makes all its methods to be executing in a transaction?
EDIT
Here's my context xml:
<context:annotation-config />
<context:component-scan base-package="it.trew.prove" />
<!-- Hibernate -->
<bean id="myDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.google.appengine.api.rdbms.AppEngineDriver" />
<property name="url" value="jdbc:google:rdbms://xxx:xxx/xxx" />
</bean>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<list>
<value>it.trew.prove.model.beans.Scadenza</value>
<value>it.trew.prove.model.beans.Fornitore</value>
<value>it.trew.prove.model.beans.Societa</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<!-- <prop key="hibernate.hbm2ddl.import_files">/setup.sql</prop> -->
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory" />
</bean>

Did you enabled annotations ?
<context:annotation-config />
and
<context:component-scan base-package="org.example"/>
this will enable annotations like #Service, #Component and #Repository

First of all, you need to tell spring to enable Transactional annotation with something like that:
<tx:annotation-driven transaction-manager="transactionManager" />
Second, if you use #Transactional at class level, any call to a method of your Service will be transactional. Whether it starts a transaction or not depends on the "propagation" attribute. The default is start one if none started in this session (Propagation.REQUIRED). If you use #Transactional only at class level, all of your methods will inherit its attributes, i.e., if you set "readOnly = true", all of yours methods will be read only, thus, updates/saves/delete won't work. I would recommend you to read more the Spring Transaction Management Doc

Related

Hibernate entity life cycle and session life cycle inside a Spring transaction

Im having some trouble understanding the way spring handles the hibernate entities, and does the lazy loading process.
So for this case we have to entities
#Entity
public class EntityA{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#ManyToMany(cascade={CascadeType.PERSIST, CascadeType.REFRESH})
private Collection<EntityB> bss= new ArrayList<EntityB>();
and the agregated entity
#Entity
public class EntityB{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#ManyToMany(mappedBy="bss")
private Collection<EntityA> ass= new ArrayList<EntityA>();
then I have a simple business class marked as transactional:
#Component
#Scope("session")
#Transactional(propagation=Propagation.TRIED_EVERY_SINGLE_ONE)
public class GenericTestBean {
private EntityA entityA;
#Autowired
private IGenericDAO genericDAO;
public GenericTestBean() {
System.out.println("bean creado!");
}
public void testQuery() {
entityA= genericDAO.get(EntityA.class, 1l);
System.out.println(TransactionIndicatingUtil.getTransactionStatus(true));
System.out.println("is element atached? :" + genericDAO.isAtached(entityA));
//this.loadData();
}
public void loadData(){
System.out.println(TransactionIndicatingUtil.getTransactionStatus(true));
System.out.println("is element atached? :" + genericDAO.isAtached(currentCompany));
System.out.println(entityA.getBss.size());
}
}
and a Simple test class
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "applicationContext.xml" })
#WebAppConfiguration
public class EntityQueryTest {
// #Autowired
// private SessionFactory sessionFactory;
#Autowired
GenericTestBean genericTestBean;
#Test
public void consultarCompania(){
genericTestBean.testQuery();
genericTestBean.loadData();
}
what Im guessin that should happen is:
1. GenericTestBean gets instantiated
2. testQuery is called from outside the proxy starting the transaction
2. loadData is called, the proxy sees the active transaction, and takes the existent resources
3. the data is retrieived
4. The transacion is closed...
But this doesn't happens, there seems to be two different transactions in each method call, and the entity gets detached between calls, issuing a lazy init exception.
the actual output log is this:
bean creado! --here the object get created
Hibernate: select company0_.companyId as ..... --here the first query get executed
[com.pe.controlLines.data.dao.GenericTestBean.testQuery] --here we check the name for the transaction
is element atached? :true --and see if the element is attached to the session
[com.pe.controlLines.data.dao.GenericTestBean.loadData] --this is in the second method call (with a different transaction name :O )
is element atached? :false --both now, the same element get detached
I tried re-attaching the entity, but this gives me a new query to the database (a new query to table EntityA is sent plus the query to get the objects, which I really don't like).
Im hoping to save one additional query just in order to have lazy loading, or does it have to be this way?, or maybe I have some configuration wrong?
Pdta: I think that the view filter option is even worst than the re-attaching option, it could lead to serious performance issues under high concurrency.
Can anyone please clarify the behavior of transaction contexts between methods calls, and how it get related to the session and the state of the entities?
the TransactionIndicatingUtil implementation is taken from here http://java.dzone.com/articles/monitoring-declarative-transac?page=0,1
and the generic dao is build after this idea
General or specific DAO to record delivery with information from multiple tables?
Update
in case is of some use, here is the spring config file
<context:component-scan base-package="xxxxxx" />
<context:annotation-config />
<context:spring-configured />
<aop:aspectj-autoproxy proxy-target-class="true"/>
<!-- Data Source Declaration -->
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/xxxx" />
<property name="username" value="xxxxx" />
<property name="password" value="xxxxx" />
<property name="initialSize" value="2" />
<property name="minIdle" value="0" />
<property name="minEvictableIdleTimeMillis" value="120000" />
<property name="maxActive" value="20" />
<property name="maxWait" value="5000" />
</bean>
<!-- Session Factory Declaration <bean id="SessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> -->
<!-- Session Factory Declaration -->
<bean id="SessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan">
<list>
<value>com.xx.xx.xx.xx</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.search.default.directory_provider">filesystem</prop>
<prop key="hibernate.search.default.indexBase">C:/DEVELOPMENT/lucene/indexes</prop>
</props>
</property>
</bean>
<!-- Enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="txManager"/>
<!-- Transaction Manager is defined -->
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="SessionFactory"/>
</bean>
The Test class should be transactional too
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "applicationContext.xml" })
#Transactional // <--- add
public class EntityQueryTest {
I am assuming that your applicationContext.xml file is the XML code shown in your post
The JUnit test itself is not transactional. Each method of your GenericTestBean bean is transactional. So, each time the non-transactional test calls a method of the transactional bean, a transaction is started, the bean method is executed, and the transaction is committed. Since you call two transactional methods successively, so two separate transactions are started.
If the test method itself was transactional, then a transaction would be started for the test method, and (by default), the two bean methods would execute in the context of the existing transaction, started by the test. The transaction would commit after the test method has returned.

Write operations are not allowed in read-only mode - Issue while persisting

I have been facing the below error while trying to save the object to database. I tried the solution mentioned here1 and here2 but no good. I was following a tutorial but the only difference is versions of Spring and Hibernate.
I am able to persist the object directly using the SessionFactory but it fails with below error if I try this with HibernateDaoSupport
spring.xml
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#localhost:1521:xe" />
<property name="username" value="system" />
<property name="password" value="xxx" />
</bean>
<context:annotation-config/>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="packagesToScan" value="org.sri.sphiber.model"></property>
<property name="hibernateProperties">
<props>
<prop key="dialect">org.hibernate.dialect.OracleDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="customerDAOImpl" class="org.sri.sphiber.dao.CustomerDAOImpl">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
CustomerDAOImpl.java
public class CustomerDAOImpl extends HibernateDaoSupport {
public boolean insertCustomer(Customer cust){
try {
getHibernateTemplate().saveOrUpdate(cust);
} catch (DataAccessException e) {
e.printStackTrace();
return false;
}
return true;
}
}
Invoke it using.
public class MainClass {
public static void main(String[] args) {
ApplicationContext appContext = new ClassPathXmlApplicationContext("spring.xml");
CustomerDAOImpl hdi=appContext.getBean("customerDAOImpl",CustomerDAOImpl.class);
Customer customer=new Customer();
customer.setCustomerName("Sri");
boolean isUpdated = hdi.insertCustomer(customer);
}
}
Error message.
Aug 10, 2014 12:45:52 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
at org.springframework.orm.hibernate4.HibernateTemplate.checkWriteOperationAllowed(HibernateTemplate.java:1135)
at org.springframework.orm.hibernate4.HibernateTemplate$16.doInHibernate(HibernateTemplate.java:684)
at org.springframework.orm.hibernate4.HibernateTemplate.doExecute(HibernateTemplate.java:340)
at org.springframework.orm.hibernate4.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:308)
at org.springframework.orm.hibernate4.HibernateTemplate.saveOrUpdate(HibernateTemplate.java:681)
at org.sri.sphiber.dao.CustomerDAOImpl.insertCustomer(CustomerDAOImpl.java:16)
at org.sri.sphiber.main.MainClass.main(MainClass.java:26)
Version Details :
Spring version : spring-framework-4.0.6.RELEASE
Hibernate Version : hibernate-release-4.3.5.Final
Database : Orcale 11g
You are missing TransactionManager definition, see http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/transaction.html
[UPDATE]
Previously i was writing from my mobile so it was hard to provide details, here is what you need to do:
Spring xml config:
<tx:annotation-driven/>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
Add #Transactional annotation to CustomerDaoImpl.insertCustomer method
Now your code should work.
Please note that #Transactional annotation should be used in service layer, not in DAO layer like in this example.
#Transactional annotation tells spring to create proxy which "wraps" annotated method with transaction using aspects.
In configuration file
do the change:-
#Configuration
#EnableTransactionManagement <-----Put this line
public PersistenceConfig{
//your code
}
(OR)
#Bean
#Autowired
public HibernateTemplate getHibernateTemplate(SessionFactory session) {
HibernateTemplate hb = new HibernateTemplate();
hb.setCheckWriteOperations(false);
hb.setSessionFactory(session);
return hb;
}

Null EntityManager Spring 4

I'm trying to setup entity manager with Spring 4 and I always get NullPointerException when I try to inject EntityManager with #PersistenceContext annotation.
I have Maven web application. Here's my applicationContext.xml configuration
<bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="EcommercePU">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>com.mysite.ecommerceapp.domain</value>
<value>com.mysite.ecommerceapp.domain.*</value>
<value>com.mysite.ecommerceapp.domain.*.*</value>
<value>com.mysite.ecommerceapp.domain.*.*.*</value>
</list>
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create-drop</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQL9Dialect</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/ecommercedb" />
<property name="username" value="postgres" />
<property name="password" value="test" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEmf" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
applicationContext.xml is located under WEB-INF folder. Because I use NetBeans 8 I added Spring Framework support to my project from project properties -> Frameworks. I'm using EntityManager injection with file called GenericDaoImpl and here's it's code:
public abstract class GenericDaoImpl<E extends EntityClass> implements GenericDao<E> {
private Class<E> entityClass;
#PersistenceContext()
private EntityManager entityManager;
//Constructor
public GenericDaoImpl(final Class<E> entityClass) {
this.entityClass = entityClass;
}
//Getters and Setters
public Class<E> getEntityClass() {
return entityClass;
}
public void setEntityClass(final Class<E> entityClass) {
this.entityClass = entityClass;
}
public EntityManager getEntityManager() {
return entityManager;
}
public void setEntityManager(final EntityManager entityManager) {
this.entityManager = entityManager;
}
public void checkEntityManager() {
System.out.println("em: " + this.entityManager);
}
}
I have one test file where I simply print entity manager with checkEntityManager() method. Whenever I run it I always get null value for EntityManager. What could be wrong? My biggest doubt is that my applicationContext.xml is in wrong place or it is not used anywhere and thus it can't find configuration properties in applicationContext. I have tested moving applicationContext.xml file to resources folder but it didn't helped either. Other questions that I also have are following:
Do I need to have persistence.xml? Since I use Spring 4 with packagesToScan feature I heard that persistence.xml is not required but I'm not sure.
Is it wise to use hibernate to take care only basic entities cruds and other dao queries with JdbcTemplate?
All help would be appreciated.
I finally solved the problem and there were lots of things that has to be done.
When I tested my Entity Manager through JUnit tests I got NullPointerException and reason was the configuration file was incorrect folder.
applicationContext.xml was properly setup except there was a small problem that messed the whole file and that was <property name="persistenceUnitName" value="EcommercePU">. Because I didn't had such persistence unit file in whole project it couldn't find it. When you add that property it doesn't mean that you have created a spring configuration file that has such persistence unit name. It simply means that if you want to provide persistence configurations to your LocalContainerEntityManagerFactory you would refer with that name to your persistence unit. This is not required in Spring 4.
applicationContext.xml had to be moved from WEB-INF to resources folder.
When you would run JUnit tests you should use #Autowired annotation to annotate DAO's.
Dao implementation classes should have #Repository annotation.
#Transactional annotation is required at least for CRUD methods if you are going to use. You can also annotate whole class. If you don't add #Transactional annotation EntityManager wouldn't execute persist, remove, update, find and other methods properly. Remember this is required if you are using Spring configurations.

Spring Data #CreatedDate annotation doesn't work for me

I am working on project where I use Spring Data. I wanted to fill in creationTime field using #CreatedDate annotation instead using method with #PreUpdate or #PrePersist annotation (doing it this way it works perfectly). When I do it with #CreatedDate it just leaves this field blank. I use postgresql database. Documentation is not very helpful.
Do you have any idea how can I fix it? Thank you!
import org.springframework.data.annotation.CreatedDate;
#Entity
#Table(name = "software")
public class Software implements Serializable {
// ...
#Column(name = "creation_time")
#CreatedDate
private Date creationTime;
//...
}
My applicationContext:
<jpa:repositories base-package="path.to.dao"/>
<context:component-scan base-package="path.to.dao"/>
<context:property-placeholder location="classpath:application.properties"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${db.driver}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="packagesToScan" value="path.to.bean"/>
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter" ref="jpaAdapter"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.ejb.naming_strategy">${hibernate.ejb.naming_strategy}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
</bean>
<bean id="jpaAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
I may have been in a similar situation where I wanted the Spring Data JPA #CreatedDate annotation to work, but had no need for the user-level auditing that is otherwise described in their documentation.
To get the annotation-based auditing to work, I had to nonetheless add a class to my project that implemented org.springframework.data.domain.AuditorAware. This is odd because you don't actually seem to use the value returned from the getCurrentAuditor() method that you'll be implementing; mine just returns null.
public class NullAuditorBean implements AuditorAware {
#Override
public Object getCurrentAuditor() {
return null;
}
}
I then needed to reference my "null object" AuditorAware implementation in an entry in my applicationContext to activate the JPA auditing. I had to make sure I did this before the line that specifies the jpa:repositories. This looks something like:
<bean id="auditorBean" class="your.package.subbed.here.NullAuditorBean"/>
<jpa:auditing auditor-aware-ref="auditorBean"/>
I also had to add an orm.xml file, and needed to formally reference it as a property of my entityManagerFactory bean, like so:
<property name="mappingResources">
<value>META-INF/orm.xml</value>
</property>
Make sure this META-INF/orm.xml entry is stored with your compile output (mine is in my WAR under WEB-INF/classes.
That orm.xml file, for the record, contained some boilerplate, which can be found in the answer to this related question.
It was a fair amount of work when I got this working. You may prefer your previous working solution!
This question is quite old, but still relevant. For me the key was this, from the documentation
Since Spring Data MongoDB 1.4 auditing can be enabled by annotating a configuration class with the #EnableMongoAuditing annotation.
For example:
#Configuration
#EnableMongoAuditing
class Config {
/**
* Optional, depending on your needs
*/
#Bean
public AuditorAware<AuditableUser> myAuditorProvider() {
return new AuditorAwareImpl();
}
}
Or, in XML:
<mongo:auditing/>
I have experienced the same issue, but wasn't able to get my head around it.
I have chosen to use Hibernate's #CreationTimestamp instead, and it works like a charm!

No unique bean of type [javax.persistence.EntityManager] is defined

I am using JUnit 4 to test Dao Access with Spring (annotations) and JPA (hibernate). The datasource is configured through JNDI(Weblogic) with an ORacle(Backend). This persistence is configured with just the name and a RESOURCE_LOCAL transaction-type
The application context file contains notations for annotations, JPA config, transactions, and default package and configuration for annotation detection.
I am using Junit4 like so:
ApplicationContext
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="workRequest"/>
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="${database.target}"/>
<property name="showSql" value="${database.showSql}" />
<property name="generateDdl" value="${database.generateDdl}" />
</bean>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>workRequest</value>
</property>
<property name="jndiEnvironment">
<props>
<prop key="java.naming.factory.initial">weblogic.jndi.WLInitialContextFactory</prop>
<prop key="java.naming.provider.url">t3://localhost:7001</prop>
</props>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
JUnit TestCase
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:applicationContext.xml" })
public class AssignmentDaoTest {
private AssignmentDao assignmentDao;
#Test
public void readAll() {
assertNotNull("assignmentDao cannot be null", assignmentDao);
List<Assignment> assignments = assignmentDao.findAll();
assertNotNull("There are no assignments yet", assignments);
}
}
regardless of what changes I make I get:
No unique bean of type [javax.persistence.EntityManager] is defined
Any hint on what this could be. I am running the tests inside eclipse.
Your Spring context has a bean definition using LocalContainerEntityManagerFactoryBean. This creates an EntityManagerFactory, not an EntityManager.
AssignmentDao needs to get itself wired with an EntityManagerFactory.
Alternatively, you can replace the LocalContainerEntityManagerFactoryBean with a LocalEntityManagerFactoryBean, which will create an EntityManager directly. However, you need to be careful with that one, it has some downsides. See that part of the Spring docs for a full explanation of the options.
It's confusing, because the naming conventions of JPA and Spring overlap each other, so naming these classes is a real bugger.

Categories