Own SpringSecurity UserDetailsService dont load User - Could not obtain transaction-synchronized Session for current thread - spring

I wrote my own SpringSecurity UserDetailsService. I used this tutorial for it.
The only differents between my configuration and that tutorial is, that I have a xml file for spring framework. But my application didn't work:
The problem is, that userDao.load(email); (watch UserDetailsService below) returns null and not an userObject. But if I switch the configuration of SpringSecurity to an inMemoryAuthentication and use userDao.load(email); in another context, the service returns the right user.
Stacktrace:
SCHWERWIEGEND: An internal error occurred while trying to authenticate the user.
org.springframework.security.authentication.InternalAuthenticationServiceException: Could not obtain transaction-synchronized Session for current thread
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:110)
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:132)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:156)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:177)
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:211)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:134)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1014)
at de.nak.cars.dao.UserDAO.load(UserDAO.java:61)
at de.nak.cars.service.impl.UserDetailsServiceImpl.loadUserByUsername(UserDetailsServiceImpl.java:34)
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:102)
... 39 more
UserDetailsService:
#Component
#Qualifier("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
#Autowired
private UserDAO userDao;
#Transactional(readOnly=true)
#Override
public UserDetails loadUserByUsername(final String email)
throws UsernameNotFoundException {
de.name.cars.model.User user = userDao.load(email); //load returns null, saw in debug mode
List<GrantedAuthority> authorities = buildUserAuthority(user.getRoles());
return buildUserForAuthentication(user, authorities);
}
private UserDetails buildUserForAuthentication(de.name.cars.model.User user,
List<GrantedAuthority> authorities) {
return new User(user.getEmail(), user.getPassword(), true, true, true, true, authorities);
}
private List<GrantedAuthority> buildUserAuthority(Set<UserRole> roles) {
Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
for (UserRole role : roles){
setAuths.add(new SimpleGrantedAuthority(role.getRoleName()));
}
List<GrantedAuthority> result = new ArrayList<GrantedAuthority>(setAuths);
return result;
}
}
spring-config.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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="de.nak.cars" />
<!-- The data source -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.h2.Driver"/>
<property name="url"
value="jdbc:h2:Y:/db/nak"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
</bean>
<!-- The session factory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="de.nak.cars.model"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.hbm2ddl.import_files">initial-sql.sql</prop>
</props>
</property>
</bean>
<!-- The transaction manager -->
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- The advice -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- The pointcut definition -->
<aop:config>
<aop:pointcut id="serviceMethods" expression="execution(* de.nak.cars.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods"/>
</aop:config>
</beans>
User.java
#Entity
public class User implements Serializable {
/** Generated version id. */
private static final long serialVersionUID = -5464675373969471720L;
/** The identifier. */
private Long id;
/** The user's firstname. */
private String firstName;
/** The user's lastname. */
private String lastName;
/** The user's student identification number. */
private String email;
/** The user's roles. */
private Set<UserRole> roles;
/** The user's password. */
private String password;
/** Set of user-exam combinations. */
private Set<ExamKey> examKeys = new HashSet<ExamKey>(0);
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "FIRST_NAME", length = 100, nullable = false)
public String getFirstname() {
return firstName;
}
public void setFirstname(String firstName) {
this.firstName = firstName;
}
#Column(name = "LAST_NAME", length = 100, nullable = false)
public String getlastName() {
return lastName;
}
public void setlastName(String lastName) {
this.lastName = lastName;
}
#ManyToMany(fetch = FetchType.LAZY, cascade= CascadeType.ALL)
#JoinTable(name="USER_USERROLE", joinColumns = {
#JoinColumn(name="USER_ID", nullable = false, updatable = false)},
inverseJoinColumns = { #JoinColumn(name="ROLE_ID", nullable = false, updatable = false)})
public Set<UserRole> getRoles() {
return roles;
}
public void setRoles(Set<UserRole> roles) {
this.roles = roles;
}
#Column(name = "EMAIL", nullable = false, unique = true)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name="PASSWORD", nullable = false)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "examKeyId.user")
public Set<ExamKey> getExamKeys() {
return examKeys;
}
public void setExamKeys(Set<ExamKey> examKeys) {
this.examKeys = examKeys;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result
+ ((lastName == null) ? 0 : lastName.hashCode());
result = prime * result + ((lastName == null) ? 0 : email.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
if (!email.equals(other.email))
return false;
return true;
}
#Override
public String toString() {
return "User [id=" + id + ", firstName=" + firstName + ", lastName="
+ lastName + ", email=" + email + ", password=" + password + ", examKeys=" + examKeys
+ "]";
}
}

you need to enable transaction management support. In the guide you followed it was done with #EnableTransactionManagement annotation over AppConfig class. In your case you use xml configuration, so you should add <tx:annotation-driven transaction-manager="txManager" /> inside your spring-config.xml

Related

Unit tests in JUnit failing when I run update/delete commands

I am currently working on an API implementation in Java with spring and hibernate.
I have two tables in my Model package
User and UserDetail which has a OneToMany mapping
#Entity
public class User {
private Long id;
private String userId;
private Set<UserDetail> userDetails;
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "user")
public Set<UserDetail> getUserDetails() {
return userDetails;
}
public void setUserDetail(Set<UserDetail> userDetails) {
this.userDetails = userDetails;
}
}
#Entity
public class User {
private Long id;
private String key;
private String value;
private User user;
#ManyToOne
#JoinColumn(name = "USER_ID", nullable = false)
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
My API looks like this
#Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
public void addUserDetail(AddUserDetailRequest request) {
//... adds the user detail for the userId as request.getUserId()
}
#Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
public void deleteUserDetail(DeleteUserDetailRequest request) {
//... deletes a particular value for a user with userId as request.getUserId() and userDetail key as request.getDeleteKey()
}
I have written Junit test cases to test the addition and deletion of UserDetails for a user, My addUserDetail is working as it should, but when I call the delete the changes are not reflected and they fail.
Below is my test case
#Test
public void testDeletUserDetail() throws Exception {
//GIVEN
String userId = client.newUser().call(getCreateUserRequest()).getId();
client.newAddUserDetail().call(getAddUserDetailRequest(userId, "key1", "value1"));
client.newAddUserDetail().call(getAddUserDetailRequest(userId, "key2", "value2"));
//WHEN
client.newDeteteUserDetail().call(getDeleteUserDetailRequest(userId, "key2"));
//THEN
List<UserDetail> userDetails = client.newGetUserDetail().call(getGetUserDetailRequest(userId));
assertEquals(userDetails.size(), 1); // This check fails and says it has a size of 2 instead of 1.
}
I am using HSQL for testing purposes
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.iiitd.myAPI.model" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="HSQL" />
<property name="generateDdl" value="true" />
<property name="showSql" value="false" />
</bean>
</property>
</bean>
<jdbc:embedded-database id="dataSource" type="HSQL" />
I have two implementation for deleteUserDetail and one of them fails.
// This one works in both jUnit and manual testing
#Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
public void deleteUserDetail(DeleteUserDetailRequest request) {
User user = userRepository.findByUserId(request.getUserId());
if(!CollectionUtils.isEmpty(user.getUserDetail())) {
UserDetail toRemove = null;
for(UserDetail userDetail : user.getUserDetail()) {
if(StringUtils.equals(userDetail.getKey(), request.getDeleteKey())) {
toRemove = userDetail;
}
}
Assert.notNull(toRemove, "Detail user doesn't exist.");
user.getUserDetail().remove(toRemove);
userRepository.save(user);
}
}
//This one doesn't and unit tests fails but manual tests are OK
#Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
public void deleteUserDetail(DeleteUserDetailRequest request) {
UserDetail userDetail = userDetailRepository.getUserDetail();
Assert.notNull(userDetail, "Detail doesn't exists");
userDetailRepository.delete(userDetail);
}
All the repositories extends JpaRepository
Could anyone explain how to circumvent this issue ?
Any help would be appreciated.

Why Lazy Initialization Exception in Hibernate polymorphic Assosiation after making it FetchType.Eagar?

Getting Lazy Initialization Exception even after making FetchType.Eagar
I am trying something like this from spring service class
List<DeviceTree> deviceTree = deviceTreeRepository.findByCustomerId( customerId );
DeviceTree tree = deviceTree.get(0);
Node node = tree.getNode();
if(node instanceof Device){
System.out.println("Device");
Device dev= (Device)node;
System.out.println(dev.getIddevice());
System.out.println(dev.getIp());
}
But getting exception
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:165)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:286)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
at com.abc.collygo.data.entities.Device_$$_jvst69a_3d.getIddevice(Device_$$_jvst69a_3d.java)
at com.abc.collygo.data.services.impl.DeviceTreeService.findAll(DeviceTreeService.java:52)
at com.abc.collygo.core.startup.LoadPdtSplitter.getSplit(LoadPdtSplitter.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.camel.component.bean.MethodInfo.invoke(MethodInfo.java:407)
at org.apache.camel.component.bean.MethodInfo$1.doProceed(MethodInfo.java:278)
at org.apache.camel.component.bean.MethodInfo$1.proceed(MethodInfo.java:251)
at org.apache.camel.component.bean.BeanProcessor.process(BeanProcessor.java:166)
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:105)
at org.apache.camel.component.bean.BeanProcessor.process(BeanProcessor.java:67)
at org.apache.camel.language.bean.BeanExpression$InvokeProcessor.process(BeanExpression.java:189)
at org.apache.camel.language.bean.BeanExpression.evaluate(BeanExpression.java:123)
at org.apache.camel.language.bean.BeanExpression.evaluate(BeanExpression.java:132)
at org.apache.camel.processor.Splitter.createProcessorExchangePairs(Splitter.java:103)
at org.apache.camel.processor.MulticastProcessor.process(MulticastProcessor.java:208)
at org.apache.camel.processor.Splitter.process(Splitter.java:98)
at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:72)
at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:398)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:191)
at org.apache.camel.component.timer.TimerConsumer.sendTimerExchange(TimerConsumer.java:139)
at org.apache.camel.component.timer.TimerConsumer$1.run(TimerConsumer.java:64)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)
Here is my DeviceTree Entity. I have node_id which can either be a device or a logical group. I was trying to implement Hibernate Polymorphic Assosiation .
#Entity
#Table(name = "device_tree")
#NamedQuery(name = "DeviceTree.findAll", query = "SELECT d FROM DeviceTree d")
public class DeviceTree implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "iddevice_tree")
private int iddeviceTree;
#Column(name = "customer_id")
private int customerId;
#Column(name = "is_disabled")
private boolean isDisabled;
private int lft;
#Column(name = "node_id")
private int nodeId;
#Any( fetch=FetchType.EAGER,metaColumn = #Column(name = "node_type_id"))
#AnyMetaDef(idType = "integer", metaType = "integer", metaValues = {
#MetaValue(targetEntity = Device.class, value = "1"),
#MetaValue(targetEntity = LogicalGroup.class, value = "2") })
#JoinColumn(name = "node_id" , insertable=false ,updatable=false)
private Node node;
#Column(name = "node_name")
private String nodeName;
#Column(name = "parent_id")
private Integer parentId;
private int rgt;
// uni-directional many-to-one association to Location
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "location_id")
#Fetch(FetchMode.JOIN)
private Location location;
// uni-directional many-to-one association to NodeType
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "node_type_id")
#Fetch(FetchMode.JOIN)
private NodeType nodeType;
// uni-directional many-to-one association to StatusDetail
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "status_details_id")
#Fetch(FetchMode.JOIN)
private StatusDetail statusDetail;
public DeviceTree() {
}
public int getCustomerId() {
return customerId;
}
public int getIddeviceTree() {
return iddeviceTree;
}
public int getLft() {
return lft;
}
public Location getLocation() {
return location;
}
public int getNodeId() {
return nodeId;
}
public String getNodeName() {
return nodeName;
}
public NodeType getNodeType() {
return nodeType;
}
public int getRgt() {
return rgt;
}
public StatusDetail getStatusDetail() {
return statusDetail;
}
public boolean isDisabled() {
return isDisabled;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public void setDisabled(boolean isDisabled) {
this.isDisabled = isDisabled;
}
public void setIddeviceTree(int iddeviceTree) {
this.iddeviceTree = iddeviceTree;
}
public void setLft(int lft) {
this.lft = lft;
}
public void setLocation(Location location) {
this.location = location;
}
public void setNodeId(int nodeId) {
this.nodeId = nodeId;
}
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
public void setNodeType(NodeType nodeType) {
this.nodeType = nodeType;
}
public void setRgt(int rgt) {
this.rgt = rgt;
}
public void setStatusDetail(StatusDetail statusDetail) {
this.statusDetail = statusDetail;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public Node getNode() {
return node;
}
public void setNode(Node node) {
this.node = node;
}
}
This is my Device class
#Entity
#Table(name = "device")
#Cacheable
#Cache( usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE )
#NamedQuery( name = "Device.findAll", query = "SELECT d FROM Device d" )
public class Device implements Serializable ,Node{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue( strategy = GenerationType.IDENTITY )
private int iddevice;
#Temporal( TemporalType.TIMESTAMP )
#Column( name = "connection_status_update_time" )
private Date connectionStatusUpdateTime;
#Temporal( TemporalType.TIMESTAMP )
#Column( name = "creation_time" )
private Date creationTime;
#Column( name = "customer_id" )
private int customerId;
#Column( name = "description" )
private String description;
#Column( name = "ip" )
private String ip;
#Column( name = "location" )
private String location;
#Column( name = "name" )
private String name;
#Column( name = "port" )
private int port;
#Column( name = "serial_key" )
private String serialKey;
#Temporal( TemporalType.TIMESTAMP )
#Column( name = "system_status_update_time" )
private Date systemStatusUpdateTime;
#Column( name = "user_id" )
private int userId;
#Column( name = "device_firmware_id" )
private int deviceFirmware;
#Column( name = "device_hardware_id" )
private int deviceHardware;
#Column( name = "device_make_id" )
private int deviceMake;
#Column( name = "device_model_id" )
private int deviceModel;
#Column( name = "device_template_id" )
private int deviceTemplateId;
#Column( name = "device_type_id" )
private int deviceType;
#ManyToOne( fetch = FetchType.LAZY )
#JoinColumn( name = "system_status_id" )
#Fetch(FetchMode.JOIN)
private StatusDetail systemStatus;
#Column( name = "system_status_id",insertable=false,updatable=false)
private int systemStatusId;
#Column( name = "connection_status_id" )
private int connectionStatus;
#Column( name = "device_param1" )
private String deviceParam1;
#Column( name = "device_param2" )
private String deviceParam2;
#Column( name = "device_param3" )
private String deviceParam3;
#Column( name = "device_param4" )
private String deviceParam4;
#Column( name = "device_param5" )
private String deviceParam5;
#Column( name = "is_disabled", length = 1, columnDefinition = "BIT" )
private boolean isDisabled;
#Column( name = "suppress_alarm", length = 1, columnDefinition = "BIT" )
private boolean suppressAlarm;
#Column( name = "parent_device_id" )
private Integer parentDeviceId;
#Column( name = "datapoint_set_config_id" )
private Integer datapointSetConfigId;
#OneToMany( mappedBy = "device",fetch = FetchType.EAGER)
#Fetch(FetchMode.JOIN)
private List<DeviceProperties> deviceProperties;
#ManyToOne( fetch = FetchType.LAZY )
#JoinColumn( name = "device_template_id", insertable = false, updatable = false )
#Fetch(FetchMode.JOIN)
private DeviceTemplate deviceTemplate;
public Device() {
}
public int getConnectionStatus() {
return connectionStatus;
}
public Date getConnectionStatusUpdateTime() {
return connectionStatusUpdateTime;
}
public Date getCreationTime() {
return creationTime;
}
public int getCustomerId() {
return customerId;
}
public Integer getDatapointSetConfigId() {
return datapointSetConfigId;
}
public String getDescription() {
return description;
}
public int getDeviceFirmware() {
return deviceFirmware;
}
public int getDeviceHardware() {
return deviceHardware;
}
public int getDeviceMake() {
return deviceMake;
}
public int getDeviceModel() {
return deviceModel;
}
public String getDeviceParam1() {
return deviceParam1;
}
public String getDeviceParam2() {
return deviceParam2;
}
public String getDeviceParam3() {
return deviceParam3;
}
public String getDeviceParam4() {
return deviceParam4;
}
public String getDeviceParam5() {
return deviceParam5;
}
public int getDeviceTemplateId() {
return deviceTemplateId;
}
public int getDeviceType() {
return deviceType;
}
public int getIddevice() {
return iddevice;
}
public String getIp() {
return ip;
}
public String getLocation() {
return location;
}
public String getName() {
return name;
}
public Integer getParentDeviceId() {
return parentDeviceId;
}
public int getPort() {
return port;
}
public String getSerialKey() {
return serialKey;
}
public StatusDetail getSystemStatus() {
return systemStatus;
}
public Date getSystemStatusUpdateTime() {
return systemStatusUpdateTime;
}
public int getUserId() {
return userId;
}
public boolean isDisabled() {
return isDisabled;
}
public boolean isSuppressAlarm() {
return suppressAlarm;
}
public void setConnectionStatus(int connectionStatus) {
this.connectionStatus = connectionStatus;
}
public void setConnectionStatusUpdateTime(Date connectionStatusUpdateTime) {
this.connectionStatusUpdateTime = connectionStatusUpdateTime;
}
public void setCreationTime(Date creationTime) {
this.creationTime = creationTime;
}
public void setCustomerId(int cutomerId) {
customerId = cutomerId;
}
public void setDatapointSetConfigId(Integer datapointSetConfigId) {
this.datapointSetConfigId = datapointSetConfigId;
}
public void setDescription(String description) {
this.description = description;
}
public void setDeviceFirmware(int deviceFirmware) {
this.deviceFirmware = deviceFirmware;
}
public void setDeviceHardware(int deviceHardware) {
this.deviceHardware = deviceHardware;
}
public void setDeviceMake(int deviceMake) {
this.deviceMake = deviceMake;
}
public void setDeviceModel(int deviceModel) {
this.deviceModel = deviceModel;
}
public void setDeviceParam1(String deviceParam1) {
this.deviceParam1 = deviceParam1;
}
public void setDeviceParam2(String deviceParam2) {
this.deviceParam2 = deviceParam2;
}
public void setDeviceParam3(String deviceParam3) {
this.deviceParam3 = deviceParam3;
}
public void setDeviceParam4(String deviceParam4) {
this.deviceParam4 = deviceParam4;
}
public void setDeviceParam5(String deviceParam5) {
this.deviceParam5 = deviceParam5;
}
public void setDeviceTemplateId(int deviceTemplateId) {
this.deviceTemplateId = deviceTemplateId;
}
public void setDeviceType(int deviceType) {
this.deviceType = deviceType;
}
public void setDisabled(boolean isDisabled) {
this.isDisabled = isDisabled;
}
public void setIddevice(int iddevice) {
this.iddevice = iddevice;
}
public void setIp(String ip) {
this.ip = ip;
}
public void setLocation(String location) {
this.location = location;
}
public void setName(String name) {
this.name = name;
}
public void setParentDeviceId(Integer parentDeviceId) {
this.parentDeviceId = parentDeviceId;
}
public void setPort(int port) {
this.port = port;
}
public void setSerialKey(String serialKey) {
this.serialKey = serialKey;
}
public void setSuppressAlarm(boolean suppressAlarm) {
this.suppressAlarm = suppressAlarm;
}
public void setSystemStatus(StatusDetail systemStatus) {
this.systemStatus = systemStatus;
}
public void setSystemStatusUpdateTime(Date systemStatusUpdateTime) {
this.systemStatusUpdateTime = systemStatusUpdateTime;
}
public void setUserId(int userId) {
this.userId = userId;
}
public List<DeviceProperties> getDeviceProperties() {
return deviceProperties;
}
public void setDeviceProperties(List<DeviceProperties> deviceProperties) {
this.deviceProperties = deviceProperties;
}
public DeviceTemplate getDeviceTemplate() {
return deviceTemplate;
}
public void setDeviceTemplate(DeviceTemplate deviceTemplate) {
this.deviceTemplate = deviceTemplate;
}
public int getSystemStatusId() {
return systemStatusId;
}
public void setSystemStatusId(int systemStatusId) {
this.systemStatusId = systemStatusId;
}
}
This is the interface declare for supporting polmorphic assosiation
public interface Node {
}
I have enabled OpenEntityFilter for solving Lazy Initialization in Spring
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<!-- Dispatcher Servlet -->
<servlet>
<servlet-name>collygo-core-config</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>collygo-core-config</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<!-- location of spring xml files -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:collygo-core-config.xml</param-value>
</context-param>
<context-param>
<param-name>contextInitializerClasses</param-name>
<param-value>com.abc.collygo.core.init.CollygoApplicationContextInitializer</param-value>
</context-param>
<!-- the listener that kick-starts Spring -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Try to solve lazy loading -->
<filter>
<filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Camel servlet -->
<servlet>
<servlet-name>CamelServlet</servlet-name>
<servlet-class>org.apache.camel.component.servlet.CamelHttpTransportServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Camel servlet mapping -->
<servlet-mapping>
<servlet-name>CamelServlet</servlet-name>
<url-pattern>/camel/*</url-pattern>
</servlet-mapping>
<!--Spring Security Filters -->
</web-app>
Here is my spring config for Data Acess
<?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"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:repository="http://www.springframework.org/schema/data/repository"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:camel="http://camel.apache.org/schema/spring"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
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
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/data/repository http://www.springframework.org/schema/data/repository/spring-repository.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<!-- Declare a JPA entityManagerFactory -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="jpaDataSource" p:jpaVendorAdapter-ref="hibernateVendor"
p:packagesToScan="com.abc.collygo.data.entities"
p:jpaProperties-ref="hibernateConfig" p:jpaDialect-ref="jpaDialect"
p:persistenceProvider-ref="hibernatePersistence"
p:persistenceUnitName="entityManagerFactory" />
<!-- Declare a datasource that has pooling capabilities -->
<bean id="jpaDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${database.driverClassName}" />
<property name="jdbcUrl" value="${database.url}" />
<property name="user" value="${database.username}" />
<property name="password" value="${database.password}" />
<property name="acquireIncrement" value="1" />
<property name="acquireRetryAttempts" value="3" />
<property name="acquireRetryDelay" value="300" />
<property name="initialPoolSize" value="100" />
<property name="maxPoolSize" value="200" />
<property name="minPoolSize" value="1" />
</bean>
<aop:config proxy-target-class="true">
</aop:config>
<aop:aspectj-autoproxy proxy-target-class="true" />
<tx:annotation-driven mode="aspectj" />
<!-- Declare a Hibernate Vendor -->
<bean id="hibernateVendor"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:showSql="false" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory" />
<!-- Declare a Hibernate Config -->
<util:map id="hibernateConfig">
<entry key="hibernate.hbm2ddl.auto" value="validate" />
<entry key="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<entry key="hibernate.show_sql" value="false" />
<entry key="hibernate.connection.zeroDateTimeBehavior" value="convertToNull" />
<entry key="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory"/>
<entry key="hibernate.cache.use_second_level_cache" value="true"/>
<entry key="hibernate.cache.use_query_cache" value="true"/>
</util:map>
<!-- Declare a JPA Dialect -->
<bean name="jpaDialect"
class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
<bean id="hibernatePersistence" class="org.hibernate.ejb.HibernatePersistence">
</bean>
<!-- Activate Spring Data JPA repository support -->
<jpa:repositories base-package="com.abc.collygo.data.repository"
entity-manager-factory-ref="entityManagerFactory"
transaction-manager-ref="transactionManager">
<!-- <repository:include-filter type="regex" expression="com.gdev.vim.repository.*"/> -->
</jpa:repositories>
</beans>
I am using spring data . Here is my Repository class
#Repository
public interface DeviceTreeRepository extends CrudRepository<DeviceTree, Integer> {
#Query( "SELECT d FROM DeviceTree d where d.customerId=:customerId AND d.iddeviceTree BETWEEN :left AND :right AND d.isDisabled=false" )
List<DeviceTree> getNodes(#Param( "left" ) int left, #Param( "right" ) int rgt,
#Param( "customerId" ) int customerId);
#Query( "SELECT d FROM DeviceTree d FETCH ALL PROPERTIES where d.customerId=:customerId AND d.isDisabled=false" )
List<DeviceTree> findByCustomerId( #Param( "customerId" )int customerId);
#Query( "SELECT d FROM DeviceTree d where d.customerId=:customerId AND d.nodeType.idnodeType=:nodeType AND d.iddeviceTree BETWEEN :left AND :right AND d.isDisabled=false" )
List<DeviceTree> getNodesforNodeType(#Param( "left" ) int left, #Param( "right" ) int right,
#Param( "nodeType" ) int nodeType, #Param( "customerId" ) int customerId);
#Query( "SELECT d FROM DeviceTree d where d.customerId=:customerId AND d.statusDetail.idstatus=:statuslist AND d.iddeviceTree BETWEEN :left AND :right AND d.isDisabled=false" )
List<DeviceTree> getNodesforStatus(#Param( "left" ) int left, #Param( "right" ) int right,
#Param( "statuslist" ) List<Integer> statuslist,
#Param( "customerId" ) int customerId);
#Query( "SELECT d FROM DeviceTree d where d.customerId=:customerId AND d.nodeType.idnodeType=:nodeTypeId AND d.isDisabled=false")
List<DeviceTree> findByNodeTypeId(#Param( "nodeTypeId" )int nodeTypeId,#Param( "customerId" ) int customerId);
#Query( "SELECT d FROM DeviceTree d where d.customerId=:customerId AND d.nodeType.idnodeType in :nodeTypes AND d.isDisabled=false")
List<DeviceTree> findByNodeType(#Param( "nodeTypes" )List<Integer> nodeTypes,#Param( "customerId" ) int customerId);
}

JPA no session when calling child

I am using spring-data-jpa and JPA repositories
here is my source code
<beans:bean id="producerService" class="cz.services.RepositoryProducerService" />
<jpa:repositories base-package="cz.repository" />
<beans:bean id="myEmf"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="packagesToScan" value="cz.models" />
<beans:property name="jpaVendorAdapter">
<beans:bean
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</beans:property>
<beans:property name="jpaProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<beans:bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<beans:property name="entityManagerFactory" ref="myEmf" />
</beans:bean>
<beans:bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url"
value="jdbc:mysql://localhost:3306/mydb?zeroDateTimeBehavior=convertToNull&characterEncoding=UTF-8" />
<beans:property name="username" value="root" />
<!--<property name="password" value="test" /> -->
<beans:property name="password" value="test"></beans:property>
</beans:bean>
and here is my entity and repository classes:
package cz.models;
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
/**
* The persistent class for the users database table.
*
*/
#Entity
#Table(name="users")
#NamedQuery(name="User.findAll", query="SELECT u FROM User u")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private int enabled;
private String password;
private String username;
//bi-directional many-to-one association to Authority
#OneToMany(mappedBy="user")
private List<Authority> authorities;
//bi-directional many-to-one association to Room
#OneToMany(mappedBy="user")
private List<Room> rooms;
//bi-directional many-to-one association to UsersData
#OneToMany(mappedBy="user")
private List<UsersData> usersData;
public User() {
}
....
public List<Room> getRooms() {
return this.rooms;
}
and here are User Repository:
public void setRooms(List<Room> rooms) {
this.rooms = rooms;
}
public Room addRoom(Room room) {
getRooms().add(room);
room.setUser(this);
return room;
}
public Room removeRoom(Room room) {
getRooms().remove(room);
room.setUser(null);
return room;
}
public List<UsersData> getUsersData() {
return this.usersData;
}
public void setUsersData(List<UsersData> usersData) {
this.usersData = usersData;
}
public UsersData addUsersData(UsersData usersData) {
getUsersData().add(usersData);
usersData.setUser(this);
return usersData;
}
public UsersData removeUsersData(UsersData usersData) {
getUsersData().remove(usersData);
usersData.setUser(null);
return usersData;
}
}
and userRepository:
public interface UserRepository extends JpaRepository<User, Integer> {
#Transactional
#Query("select u from User u WHERE u.enabled = 1 ")
public List<User> findAllactiveUsers();
#Transactional
#Query("select u from User u WHERE u.username = :username ")
public User findByUsername(#Param("username")String username);
}
and my service for spring security:
#Service
public class MyUserDetailsService implements UserDetailsService {
#Resource
UserRepository repositoryUser;
#Resource
AuthorityRepository repositoryAuthority;
public UserDetails loadUserByUsername(String username) {
System.out.println("start");
cz.models.User userModel = null;
UserDetails userDetail = null;
try{
userModel = repositoryUser.findByUsername(username);
// User user = userModel;
System.out.println(userModel.getUsername());
List<Authority> authorities = repositoryAuthority.findAllByUser(userModel);
// repositoryUserData.findAll();
System.out.println(userModel.getAuthorities().size());
Collection<SimpleGrantedAuthority> collectionAuthorities = new ArrayList<SimpleGrantedAuthority>();
for (int i = 0; i < authorities.size(); i++) {
collectionAuthorities.add(new SimpleGrantedAuthority(authorities
.get(i).getAuthority()));
}
userDetail = new User(userModel.getUsername(),
userModel.getUsername(), collectionAuthorities);
}catch(Exception e){
e.printStackTrace();
}
return userDetail;
}
}
The problem is: when I want call - this peace of code:
userModel.getAuthorities()
which call child (fk in db). I have exception :
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
When I add second repository Authorities I do not have this no session problem. But I do not want create every time method in my repository.
List<Authority> authorities = repositoryAuthority.findAllByUser(userModel);
I have to use hibernate.LazyInitialization instead of eanger.(and some stable)
I saw a lot of post with this problem with JPA, but nothing work for me :(
Use a query that fetches the data you want so that it is there when you need it.
#Query("select u from User u left join fetch u.authorities WHERE u.username = :username ")
public User findByUsernameFetchAuthorities(#Param("username")String username);
Using findByUsernameFetchAuthorities when you want to access the authorities will cause them to be pre-fetched, avoiding the error and keeping them lazily fetched for every other query.

Spring: Illegally attempted to associate a proxy with two open Sessions

I have a page to create taxis which consist on a simple form to fill my database. This class and the dao were autogenerated by hibernate tools. When I post my code and it's called the persist method then I get a PersistException The code:
Controller.java
#Controller
#RequestMapping(value="/session/taxi")
public class TaxiController {
private final Log log = LogFactory.getLog(getClass());
#Autowired
private UserManager userManager;
#Autowired
private TaxiManager taxiManager;
/**
* Returns the create taxi page.
* #param model the model on which to map.
* #return A String reference to jsp.
*/
#RequestMapping(value="/create", method=RequestMethod.GET)
public String createTaxi(ModelMap model){
//Add the current business and city to this taxi. It can not be modified
Taxi taxi = taxiManager.createDefaultTaxi();
TaxiPassword taxiPass = new TaxiPassword();
taxiPass.setTaxi(taxi);
model.addAttribute("newTaxi", taxiPass);
return "taxi/createtaxi";
}
/**
* Add a new taxi to the database.
* #param taxiPassword the taxi to be added.
* #param result the result of binding taxi from the model.
* #param redirectAttributes attributes to show messages when redirect.
* #return a string that refers to jsp page.
*/
#RequestMapping(value="/create", method=RequestMethod.POST)
public String addNewTaxi(#ModelAttribute("newTaxi") #Valid TaxiPassword taxiPassword, BindingResult result,
final RedirectAttributes redirectAttributes){
String newPage = "";
Taxi taxi = taxiPassword.getTaxi();
//Check password is correct
if (!result.hasErrors()){
//Set the password as md5
taxi.setPassword(SecurityUtils.getMD5Password(taxi.getPassword()));
//Persist it
taxiManager.persistTaxi(taxiPassword.getTaxi());
newPage = "redirect:/session/taxi/viewtaxi";
}else{
newPage = "taxi/createtaxi";
}
return newPage;
}
}
Taxi.java
#Entity
#Table(name = "taxi", catalog = "takeme", uniqueConstraints = #UniqueConstraint(columnNames = "username"))
public class Taxi implements java.io.Serializable {
#NotNull
#Size(min=1, max=20)
#Digits(integer = 15, fraction = 0)
private String idLicense;
#Valid
private City city;
#Valid
private Business business;
#NotNull
#Nif
private String dni;
#NotNull
#Size(min=3, max=50)
private String username;
#Size(min=5, max=50)
private String password;
#NotNull
#Size(min=1, max=50)
private String name;
#NotNull
#Size(min=1, max=45)
private String surname;
#NotNull
#Size(min=1, max=30)
private String phone;
#NotNull
private boolean creditCardAvailability;
#NotNull
private boolean taxiAdapted;
#NotNull
private boolean bigTaxi;
#NotNull
private boolean availability;
private Double latitude;
private Double longitude;
private byte[] photo;
#NotNull
private boolean state;
private Set<Booking> bookings = new HashSet<Booking>(0);
private Set<MobileClientRateTaxi> mobileClientRateTaxis = new HashSet<MobileClientRateTaxi>(
0);
public Taxi() {
}
public Taxi(String idLicense, City city, Business business, String dni,
String username, String password, String name, String surname,
String phone, boolean creditCardAvailability, boolean taxiAdapted,
boolean bigTaxi, boolean availability, boolean state) {
this.idLicense = idLicense;
this.city = city;
this.business = business;
this.dni = dni;
this.username = username;
this.password = password;
this.name = name;
this.surname = surname;
this.phone = phone;
this.creditCardAvailability = creditCardAvailability;
this.taxiAdapted = taxiAdapted;
this.bigTaxi = bigTaxi;
this.availability = availability;
this.state = state;
}
public Taxi(String idLicense, City city, Business business, String dni,
String username, String password, String name, String surname,
String phone, boolean creditCardAvailability, boolean taxiAdapted,
boolean bigTaxi, boolean availability, Double latitude,
Double longitude, byte[] photo, boolean state,
Set<Booking> bookings,
Set<MobileClientRateTaxi> mobileClientRateTaxis) {
this.idLicense = idLicense;
this.city = city;
this.business = business;
this.dni = dni;
this.username = username;
this.password = password;
this.name = name;
this.surname = surname;
this.phone = phone;
this.creditCardAvailability = creditCardAvailability;
this.taxiAdapted = taxiAdapted;
this.bigTaxi = bigTaxi;
this.availability = availability;
this.latitude = latitude;
this.longitude = longitude;
this.photo = photo;
this.state = state;
this.bookings = bookings;
this.mobileClientRateTaxis = mobileClientRateTaxis;
}
#Id
#Column(name = "id_license", unique = true, nullable = false, length = 20)
public String getIdLicense() {
return this.idLicense;
}
public void setIdLicense(String idLicense) {
this.idLicense = idLicense;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id_city", nullable = false)
public City getCity() {
return this.city;
}
public void setCity(City city) {
this.city = city;
}
// More autogenerated setters and getters...
}
TaxiDao.java
#Repository(value = "taxiDAO")
public class TaxiDAOImpl implements TaxiDAO{
private final Log log = LogFactory.getLog(getClass());
#PersistenceContext(unitName = "takemePU", type = PersistenceContextType.EXTENDED)
private EntityManager entityManager;
#Transactional(readOnly = false)
public void persist(Taxi transientInstance) {
log.debug("Persisting taxi instance: " + transientInstance.getIdLicense());
try {
entityManager.persist(transientInstance);
log.debug("Persist successful");
} catch (RuntimeException re) {
log.error("Persist failed: ", re);
throw re;
}
}
#Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW)
public void remove(Taxi persistentInstance) {
log.debug("Removing taxi instance: " + persistentInstance.getIdLicense());
try {
entityManager.remove(persistentInstance);
log.debug("Remove successful");
} catch (RuntimeException re) {
log.error("Remove failed: ", re);
throw re;
}
}
#Transactional(readOnly = false, propagation=Propagation.REQUIRES_NEW)
public Taxi merge(Taxi detachedInstance) {
log.debug("Merging taxi instance: " + detachedInstance.getIdLicense());
try {
Taxi result = entityManager.merge(detachedInstance);
log.debug("Merge successful");
return result;
} catch (RuntimeException re) {
log.error("Merge failed: ", re);
throw re;
}
}
#Transactional(readOnly = true)
public Taxi findById(String id) {
log.debug("Getting taxi instance with id: " + id);
try {
Taxi instance = entityManager.find(Taxi.class, id);
log.debug("Get successful");
return instance;
} catch (RuntimeException re) {
log.error("Get failed: ", re);
throw re;
}
}
#Transactional(readOnly = true)
public Taxi findByUsername(String username) {
log.debug("Getting taxi instance with id: " + username);
try {
Taxi instance = entityManager.find(Taxi.class, username);
log.debug("Get successful");
return instance;
} catch (RuntimeException re) {
log.error("Get failed: ", re);
throw re;
}
}
#SuppressWarnings("unchecked")
#Transactional(readOnly = true)
public List<Taxi> getTaxiList() {
return entityManager.createQuery("select taxi from Taxi taxi").getResultList();
}
#SuppressWarnings("unchecked")
#Transactional(readOnly = true)
public List<Taxi> getTaxisByBusiness(String idBusiness) {
return entityManager.createQuery("select taxi from Taxi taxi where taxi.business.idBusiness='"+ idBusiness+"'").getResultList();
}
}
Here is the stacktrace:
javax.persistence.PersistenceException: org.hibernate.HibernateException: illegally attempted to associate a proxy with two open Sessions
org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1235)
org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1168)
org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1174)
org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:674)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:366)
com.sun.proxy.$Proxy90.persist(Unknown Source)
com.hp.unileon.takeme.dao.TaxiDAOImpl.persist(TaxiDAOImpl.java:36)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
com.sun.proxy.$Proxy100.persist(Unknown Source)
com.hp.unileon.takeme.service.SimpleTaxiManager.persistTaxi(SimpleTaxiManager.java:19)
com.hp.unileon.takeme.controller.TaxiController.addNewTaxi(TaxiController.java:112)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:183)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
If you need any configuration files to know what I am doing wrong tell me, I think it's huge amount of code for now (it has been simplified). Thanks.
UPDATE: my application context is:
<!-- Bean used by the daos to connect and make transactions with the database -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory"/>
<!-- Activate the annotation driven configurations making useful #Transaction annotations -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- Scans the classpath of this application for #Components to deploy as beans -->
<context:component-scan base-package="com.hp.unileon.takeme.service" />
<context:component-scan base-package="com.hp.unileon.takeme.dao" />
<!-- Holding properties for database connectivity -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- Enabling annotation driven configuration like #Component-->
<context:annotation-config/>
<!-- Selects the database data source giving username password and nedded parameters
to connect on it. You can change those parameters easily on /classes/messages.properties -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- Element that loads tables on the database into object entities and so on -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource"
p:jpaVendorAdapter-ref="jpaAdapter">
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
</property>
<!-- This persistence unit can be found on /main/resources/META-INF/persistence.xml -->
<property name="persistenceUnitName" value="takemePU"></property>
</bean>
<!-- Enable hibernate to perform the database operations -->
<bean id="jpaAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:database="${jpa.database}"
p:showSql="${jpa.showSql}"/>
The problem is related to PersistenceContextType.EXTENDED. When I get nested objects from database that use extended persistence context, they open a new session and then are returned by the entityManager. So, if I use them in the same request and try to add to the Taxi entity those nested objects, City and Business belongs to a non clossed session (because scope is EXTENDED) and Taxi belongs to the new session. Persist method does not allow the use of this kind of behabiour because proxy lazy evaluation objects belong to different sessions.
The solution I've finally found is using OpenEntityManagerInViewFilter, that joins all the transactions in the same session. To do it you only have to add this pieze of code in your web.xml.
<filter>
<filter-name>openEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
<init-param>
<param-name>entityManagerFactoryBeanName</param-name>
<param-value>entityManagerFactory</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>openEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

Spring JPA Repository Autowire Issue

I followed a youtube video tutorial for setting up a Spring JPA project but im still having issues with my Spring JPA project and was hoping someone could help.
http://www.youtube.com/watch?v=kM7Gr3XTzIg
The main problem seems to be Autowiring my JPARepository. I have tested that my entityManager / persistence unit works via the following test code (it pulls back the expected record).
public class CheckEntityManagerWorksTest {
private static Logger logger = Logger.getLogger(CheckEntityManagerWorksTest.class.getName());
private static EntityManagerFactory emFactory;
private static EntityManager em;
#BeforeClass
public static void setUp() throws Exception {
try {
logger.info("Building JPA EntityManager for unit tests");
emFactory = Persistence.createEntityManagerFactory("pu");
em = emFactory.createEntityManager();
} catch (Exception ex) {
ex.printStackTrace();
fail("Exception during JPA EntityManager instanciation.");
}
}
#AfterClass
public static void tearDown() throws Exception {
logger.info("Shuting down Hibernate JPA layer.");
if (em != null) {
em.close();
}
if (emFactory != null) {
emFactory.close();
}
}
#Test
public void testPersistence() {
try {
em.getTransaction().begin();
Integer id = 51;
Accounts account = em.find(Accounts.class, id);
assertNotNull(account);
System.out.println("Account username: " + account.getUsername());
em.getTransaction().commit();
} catch (Exception ex) {
em.getTransaction().rollback();
ex.printStackTrace();
fail("Exception during testPersistence");
}
}
}
As i said that test works for connecting to the database, etc. but the test below fails with a autowire exception (stack trace at very bottom of page):
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("**/applicationContext.xml")
public class AccountsRepositoryTest {
#Autowired
AccountsRepository repo;
#Test
public void testAccountsRepository() {
assertNotNull(repo.findOne(51));
}
}
Below is my setup.
Persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="pu">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.connection.url" value="jdbc:derby://localhost:1527/craigtest"/>
<property name="hibernate.connection.password" value="craigtest"/>
<property name="hibernate.connection.driver_class" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="hibernate.connection.username" value="craigtest"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect" />
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
ApplicationContext.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:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<bean id="myEmf" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="pu"/>
</bean>
<bean id="myTxManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEmf"/>
</bean>
<jpa:repositories base-package="com.mycompany.jpaspring.repositories" />
</beans>
My Repository:
package com.mycompany.jpaspring.repositories;
import com.mycompany.jpaspring.entity.Accounts;
import org.springframework.data.jpa.repository.JpaRepository;
public interface AccountsRepository extends JpaRepository<Accounts, Integer>{
}
My Entity:
package com.mycompany.jpaspring.entity;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "ACCOUNTS")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Accounts.findAll", query = "SELECT a FROM Accounts a"),
#NamedQuery(name = "Accounts.findById", query = "SELECT a FROM Accounts a WHERE a.id = :id"),
#NamedQuery(name = "Accounts.findByUsername", query = "SELECT a FROM Accounts a WHERE a.username = :username"),
#NamedQuery(name = "Accounts.findByFirstname", query = "SELECT a FROM Accounts a WHERE a.firstname = :firstname"),
#NamedQuery(name = "Accounts.findByLastname", query = "SELECT a FROM Accounts a WHERE a.lastname = :lastname")})
public class Accounts implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "ID")
private Integer id;
#Basic(optional = false)
#Column(name = "USERNAME")
private String username;
#Column(name = "FIRSTNAME")
private String firstname;
#Column(name = "LASTNAME")
private String lastname;
public Accounts() {
}
public Accounts(Integer id) {
this.id = id;
}
public Accounts(Integer id, String username) {
this.id = id;
this.username = username;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Accounts)) {
return false;
}
Accounts other = (Accounts) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.mycompany.jpaspring.entity.Accounts[ id=" + id + " ]";
}
}
Stack trace:
-------------------------------------------------------------------------------
Test set: com.mycompany.jpaspring.AccountsRepositoryTest
-------------------------------------------------------------------------------
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.797 sec <<< FAILURE!
testAccountsRepository(com.mycompany.jpaspring.AccountsRepositoryTest) Time elapsed: 0.507 sec <<< ERROR!
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.mycompany.jpaspring.AccountsRepositoryTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.mycompany.jpaspring.repositories.AccountsRepository com.mycompany.jpaspring.AccountsRepositoryTest.repo; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.mycompany.jpaspring.repositories.AccountsRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:374)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:312)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:284)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
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:601)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.mycompany.jpaspring.repositories.AccountsRepository com.mycompany.jpaspring.AccountsRepositoryTest.repo; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.mycompany.jpaspring.repositories.AccountsRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:513)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:92)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
... 32 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.mycompany.jpaspring.repositories.AccountsRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:947)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:816)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:730)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:485)
... 34 more
Everything seems to be fine to me, except for this line:
#ContextConfiguration("**/applicationContext.xml")
Do you really need to import multiple xml files?
In which folder is the applicationContext.xml exactly?
Could you try replacing the above with a full path reference? Something like this:
#ContextConfiguration("classpath:/com/.../application-context.xml")

Resources