org.hibernate.QueryException: The collection was unreferenced - spring

Please find the java class xml files.
package com.example;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestHibernateFilter {
#SuppressWarnings("unchecked")
public static void main(String... strings) {
ApplicationContext context = new ClassPathXmlApplicationContext("sravan.xml");
SessionFactory factory = context.getBean(SessionFactory.class);
Session session = factory.openSession();
Family family = (Family)session.get(Family.class, 1);
//Set<Person> persons = family.getMembers();
//System.out.println("persons "+persons);
List<Person> entityList = session.createFilter(family.getMembers(), "where id > :id").setInteger("id", 0).list();
List<String> entityNames = session.createFilter(entityList, "select firstName").list();
System.out.println("names are "+entityNames);
}
}
<?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:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.2.xsd
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.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<tx:annotation-driven transaction-manager="transactionManager"/>
<context:annotation-config />
<context:component-scan base-package="com.example" />
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.p6spy.engine.spy.P6SpyDriver" />
<property name="url" value="jdbc:mysql://localhost/sravan"/>
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="packagesToScan" value="com.example"></property>
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="show_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
</beans>
if i run main method am getting org.hibernate.QueryException: The collection was unreferenced exception. am i missing any configuration?? and explain me about exception

Related

Error when setting 2 DataBases without bean annotation using SpringData

I have problem when i try configure 2 dataSources in my xml applicationContext.xml.
The examples i find reffer using bean annotation for configuration.
i need configuration in xml in my actual architecture.
I saw tutorial:
http://www.baeldung.com/spring-data-jpa-multiple-databases
and
https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-two-datasources
But i don't solve my problem, the method used in this Spring page use annotation. I can't use annotation, my configuration is there in xml.
When i try apply seconf datasource has error.
Before add second datasource, work's fine!
When add second datasource don't work.
My applicationContext.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jee="http://www.springframework.org/schema/jee"
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-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-4.2.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"
default-autowire="byName" default-lazy-init="true">
<context:annotation-config />
<context:component-scan base-package="br.com.myProject" />
<jpa:repositories base-package="br.com.myProject.ged.repository"/>
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean" scope="singleton">
<property name="jndiName" value="java:jboss/datasources/sgedDS" />
<property name="resourceRef" value="true" />
</bean>
<bean id="dataSourceNurer" class="org.springframework.jndi.JndiObjectFactoryBean" scope="singleton">
<property name="jndiName" value="java:jboss/datasources/nurerDS" />
<property name="resourceRef" value="true" />
</bean>
<!-- ************** ENTITY MANAGER SGED ******************** -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="packagesToScan" value="br.com.myProject.ged.entity" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">false</prop>
</props>
</property>
</bean>
<!-- ************** ENTITY NURER NURER ******************** -->
<bean id="entityManagerFactoryNurer" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="packagesToScan" value="br.com.myProject.ged.entity" />
<property name="dataSource" ref="dataSourceNurer" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">false</prop>
</props>
</property>
</bean>
<!-- ******** SGED ******** -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- ******** NURER ******** -->
<bean id="transactionManagerNurer" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryNurer" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" /> <!-- SGED -->
<tx:annotation-driven transaction-manager="transactionManagerNurer" /> <!-- NURER -->
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
<map>
<entry key="view">
<bean class="br.com.myProject.ged.spring.SpringViewScope" />
</entry>
</map>
</property>
</bean>
</beans>
My Bean Service layer:
#Transactional (transactionManager = "transactionManager2")
public List<DataBase2Entity> getAll(){
return nurerSituacaoIdrRepository.findAll();
// return new ArrayList<DataBase2Entity>();
}
#Transactional (transactionManager = "transactionManager")
public List<DataBaseEntity> getAll(){
return nurerSituacaoIdrRepository.findAll();
// return new ArrayList<DataBaseEntity>();
}
My BaseDao.java
public abstract class BaseDao<T> {
private Class<T> entityClass;
#PersistenceContext(unitName = "entityManagerFactory")
private EntityManager em;
#PersistenceContext(unitName = "entityManagerFactoryNurer")
private EntityManager emNurer;
#SuppressWarnings("unchecked")
public BaseDao() {
this.entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
...
UPDATE : 02/10/2017
ERROR execution time:
Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Error setting property values
I use same entityManagerFactory or create another entityManagerFactory (see BaseDao.java).
This seems to be an issue with XML.
I see there is a . (dot) at the end on line no #105
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>.
Remove the dot and try again.

Spring not able to resolve property

I am using spring 4 and using the PropertySourcesPlaceholderConfigurer for 2 configuration files.My xml is:
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<tx:annotation-driven />
<context:component-scan
base-package="com.a2bnext.controller,com.a2bnext.dao,com.a2bnext.service,com.a2bnext.util"/>
<mvc:annotation-driven />
<bean id="propertyConfigurer"
class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/database.properties</value>
<value>/WEB-INF/app.properties</value>
</list>
</property>
<property name="location" value="/WEB-INF/database.properties" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="initialSize" value="${jdbc.initialSize}" />
<property name="maxActive" value="${jdbc.maxActive}" />
<property name="minIdle" value="${jdbc.minIdle}" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop
key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="format_sql">true</prop>
<prop key="use_sql_comments">true</prop>
<prop key="use_jdbc_metadata_defaults">false</prop>
</props>
</property>
<property name="packagesToScan" value="com.a2bnext.entity" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- <bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean> -->
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<bean id="tilesViewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles3.TilesView
</value>
</property>
<property name="order" value="0"/>
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1048576"/>
</bean>
</beans>
In my Service class I am using:
package com.a2bnext.service;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile;
import com.a2bnext.dao.A571DAO;
import com.a2bnext.dao.ReceivingNumberDAO;
import com.a2bnext.entity.A571;
import com.a2bnext.entity.ReceivingNumber;
#Service
public class FileUploadServiceImpl implements FileUploadService {
#Value("${supporting.documents.location}")
private String supportingDocumentsLocation;
#Override
#Transactional
public Map getResponse(MultipartFile multipartFile) throws IOException {
System.out.println("Documents location is :"+supportingDocumentsLocation);
HashMap<String, Object> map = new HashMap<String, Object>();
Long size = multipartFile.getSize();
String originalFileName=multipartFile.getOriginalFilename();
String contentType = multipartFile.getContentType();
InputStream inputStream = multipartFile.getInputStream();
byte[] bytes = IOUtils.toByteArray(inputStream);
if(size>(5*1024*1024))
{
map.put("fileoriginalsize", size);
map.put("msg", "failed");
map.put("reason", "File size cannot be greater than 5MB");
return map;
}
String newFileName=generateFileName();
// Create the file on server
File serverFile = new File("D:"+File.separator+"Uploads"+ File.separator + newFileName);
BufferedOutputStream outputStream = new BufferedOutputStream(
new FileOutputStream(serverFile));
outputStream.write(bytes);
outputStream.close();
map.put("fileoriginalsize", size);
map.put("contenttype", contentType);
map.put("base64", new String(Base64Utils.encode(bytes)));
map.put("name", newFileName);
return map;
}
}
My app.properties file :
supporting.documents.location = D:\uploads
However when I start the application I get the error:
Could not resolve placeholder 'supporting.documents.location' in string value "${supporting.documents.location}"
Please suggest why I am getting the error.Thanks.
You define the locations property, but then you overwrite it with the location property. So nothing in app.properties is loaded:
<property name="locations">
<list>
<value>/WEB-INF/database.properties</value>
<value>/WEB-INF/app.properties</value>
</list>
</property>
<property name="location" value="/WEB-INF/database.properties" />

Error: No mapping found for HTTP request with URI . How fix it?

I have a problem with my project. When i browser http://localhost:8080/user/form to display UserForm then occur following error:
WARNING: No mapping found for HTTP request with URI [/user/form] in
DispatcherSe rvlet with name 'userservice'
Here file UserRestServiceController.java
package edu.java.spring.service.user.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import edu.java.spring.service.user.dao.UserDao;
import edu.java.spring.service.user.model.User;
#Controller
public class UserRestServiceController {
#Autowired
private UserDao userDao;
#Autowired
private View jsonView;
#RequestMapping(value="/user/form,",method = RequestMethod.GET)
public ModelAndView user(){
// System.out.println("anh yeu em ");
return new ModelAndView("UserForm","User",new User());
}
#RequestMapping(value="/user/json/{username}")
public ModelAndView loadUser(#PathVariable("username")String name){
return new ModelAndView(jsonView,"data",userDao.loadUser(name));
}
}
Here file userservice-servlet.xml
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd ">
<context:component-scan base-package="edu.java.spring.service.user.controller"></context:component-scan>
<context:component-scan base-package="edu.java.spring.service.user.dao"></context:component-scan>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="order" value="1" />
<property name="suffix" value=".jsp" />
<property name="prefix" value="/user/" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.DerbyDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="mappingLocations">
<list>
<value>classpath:User.hbm.xml</value>
</list>
</property>
<property name="packagesToScan" value="edu.java.spring.service.user.model" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.apache.derby.jdbc.EmbeddedDriver" />
<property name="url"
value="jdbc:derby:D:\PROJECTSPRING\userdb;create=true" />
<property name="username" value="" />
<property name="password" value="" />
</bean>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
<property name="contentType" value="text/plain"/>
</bean>
</beans>
Add #RequestMapping(value="/user") at your class level and remove that part of the path at method level

org.hibernate.HibernateException: save is not valid without active transaction

I have a problem to save the data with hibernate from Spring.
When I save data get error:
Exception in thread "main" org.hibernate.HibernateException: save is not valid without active transaction
https://gist.github.com/RuzievBakhtiyor/f3009dbc6a9c31090b59
Spring beans config:
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
">
<import resource="hibernate.xml"/>
<import resource="dataSource.xml"/>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<context:component-scan base-package="neron" />
Hibernate config bean:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="neron.models" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
DataSource config bean:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="123456789" />
</bean>
</beans>
TestDao:
package neron.dao.Impl;
import neron.dao.TestDao;
import neron.models.Test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
#Transactional
#Repository("testDao")
public class TestDaoImpl implements TestDao {
SessionFactory sessionFactory;
#Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
private Session getCurrentSession()
{
return (Session)sessionFactory.getCurrentSession();
}
public void save(Test test) {
getCurrentSession().save(test);
}
public Test findById(int id) {
return (Test) getCurrentSession().get(Test.class,id);
}
}
You need to do db update operation (insert, update, delete) within transaction boundary .
Session session = getCurrentSession();
Transaction trans = session.beginTransaction(); //begin transaction
//db operation
session.save(test)
trans.commit(); //end transaction
OR
For annotation support, in your spring config bean, add this
<tx:annotation-driven transaction-manager="transactionManager" mode="proxy" proxy-target-class="true" />
Remove this tag from sessionFactory -> hibernateProperties
<property name="hibernate.current_session_context_class">thread</property>

SpringMVC on Heroku won't persist with DataBase

I am just starting with a Spring Application on Heroku. Till now everything seems to be working pretty fine, but I cant add anything to the Database. I am not sure if I need to change anything in the WebInterface at Heroku or at my Configurationfiles?
I can connect to my DB and also my Queries work (no Exception though), but the Result of the Query is empty.
If I call the addBooking() from the Service, the new Booking won't get written to the DB (As far as I can tell). The Query in getAvailableBookings() does not get any entries.
Maybe you will be able to find any mistake or am I missing anything?
MyServiceImpl:
import java.util.Date;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.stuttgart.fahrrad.controller.BookingController;
import org.stuttgart.fahrrad.model.Booking;
import com.example.model.Person;
#Service
public class BookingServiceImpl implements BookingService {
static Logger logger = Logger.getLogger(BookingServiceImpl.class.getName());
#PersistenceContext
EntityManager em;
#Override
public void addBooking(Booking booking) {
logger.info("Persisting a booking to the DB!");
em.persist(booking);
}
#Override
#Transactional
public int getAvailableBookings(Date bookingDay) {
CriteriaQuery<Booking> c = em.getCriteriaBuilder().createQuery(Booking.class);
Root<Booking> from = c.from(Booking.class);
return em.createQuery(c).getResultList().size();
}
My applicationContext:
<?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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:annotation-config />
<context:component-scan base-package="org.stuttgart.fahrrad" />
<mvc:annotation-driven/>
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="dataSource" ref="dataSource"/>
</bean>
<beans profile="default">
<jdbc:embedded-database id="dataSource"/>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
</beans>
<beans profile="prod">
<bean class="java.net.URI" id="dbUrl">
<constructor-arg value="#{systemEnvironment['DATABASE_URL']}"/>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="url" value="#{ 'jdbc:postgresql://' + #dbUrl.getHost() + #dbUrl.getPath() }"/>
<property name="username" value="#{ #dbUrl.getUserInfo().split(':')[0] }"/>
<property name="password" value="#{ #dbUrl.getUserInfo().split(':')[1] }"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<!-- change this to 'verify' before running as a production app -->
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
</beans>
</beans>
You do not have #Transactional applied to your addBooking method.

Resources