Autowiring not working for #Repository - spring

I am trying to create a Simple REST service that stores data in the db. This is a sample architecture going from REST controller to a MVC-Controller, which instantiates an Entity and tries to store it in the db via an autowired Repository.
The REST service is correctly invoked and replies what it has to; however, storing the entity fails and the autowired repository is null.
Can somebody help?
My REST service:
#RestController
#RequestMapping("/coord")
public class CoordService {
#RequestMapping(value = "/{name}", method = RequestMethod.GET)
public String getMuseo(#PathVariable String name) {
String result = "Hello " + name + ", I am saving on the db.";
new CoordController().saveCoord();
return result;
}
}
My application business logic (controller in MVC):
#Component
public class CoordController {
#Autowired
private CoordRepository coordRepository;
public void saveCoord() {
System.out.println("Ok controller");
Coord cg = new Coord();
System.out.println("Ok new");
cg.setCoord("xyz");
cg.setId(1L);
if (coordRepository == null) {
System.out.println("REP NULL!");
} else
coordRepository.save(cg);
System.out.println("Ok save()");
}
}
My Entity:
#Entity
#Configurable
public class Coord extends IdentifiableEntity {
#NotNull
private String coord;
public String getCoord() {
return this.coord;
}
public void setCoord(String coord) {
this.coord = coord;
}
}
My Repository:
#Repository
public interface CoordRepository extends
JpaSpecificationExecutor<Coord>,
JpaRepository<Coord, Long> {
}
My 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:context="http://www.springframework.org/schema/context"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx"
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-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<context:property-placeholder location="classpath*:spring/*.properties" />
<context:component-scan base-package="com.lh.clte" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${database.driverClassName}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.username}" />
<property name="password" value="${database.password}" />
<property name="initialSize" value="3" />
<property name="maxActive" value="10" />
</bean>
<tx:annotation-driven mode="proxy"
transaction-manager="transactionManager" />
<bean class="org.springframework.orm.jpa.JpaTransactionManager"
id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
id="entityManagerFactory">
<property name="persistenceUnitName" value="persistenceUnit" />
<property name="dataSource" ref="dataSource" />
</bean>
<jpa:repositories base-package="com.lh.clte.repository" />
</beans>
My persistence.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<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="persistenceUnit"
transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy" />
<property name="hibernate.connection.charSet" value="UTF-8" />
</properties>
</persistence-unit>
</persistence>

Your problem is here
new CoordController().saveCoord();
You need to autowire your CoordController into your CoordService. By using new CoordController(), you are creating an instance of CoordController not managed by spring so its fields are not autowired.
#RestController
#RequestMapping("/coord")
public class CoordService {
#Autowired
private CoordController coordController;
#RequestMapping(value = "/{name}", method = RequestMethod.GET)
public String getMuseo(#PathVariable String name) {
String result = "Hello " + name + ", I am saving on the db.";
coordController.saveCoord();
return result;
}
}
By the way, your CoordService class should be named CoordController since its a controller (it has the #RestController annotation!) and your CoordController should be CoordService since it contains business logic.

Related

Unable to use Repository class of spring data jpa on a class method in Quartz why?

I'm developing multiple-jobs-in-quartz-spring-example which is combination of Spring + Quartz + Spring Data JPA. I'm looking to developed a code which will run in 5 sec, it will hit to DB and fetches a records from DB.
I am close to making it working but I see small problem. In my JobA.class, why don't I get an instance of CustomerRepository.java? It's always null and thats why code unable to hit to DB.
Source code at: http://www.github.com/test512/multiple-jobs-in-quartz-spring-example.gi‌​t.
JobA.java
#Service
public class JobA extends QuartzJobBean {
private CustomerRepository customerRepository = null;
#Autowired
public JobA(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}
public JobA() { }
#Override
protected void executeInternal(JobExecutionContext executionContext) throws JobExecutionException {
System.out.println("~~~~~~~ Job A is runing ~~~~~~~~");
Trigger trigger = executionContext.getTrigger();
System.out.println(trigger.getPreviousFireTime());
System.out.println(trigger.getNextFireTime());
getCustomerList();
}
private List<Customer> getCustomerList(){
List<Customer> customers = customerRepository.findAll();
for (Customer customer : customers) {
System.out.println("------------------------------");
System.out.println("ID : "+customer.getId());
System.out.println("NAME : "+customer.getName());
System.out.println("STATUS : "+customer.getStatus());
}
return customers;
}
}
Customer.java
#Entity
#Table(name="customer")
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="ID")
private Long id;
#Column(name="NAME")
private String name;
#Column(name="STATUS")
private String status;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
CustomerRepository.java
public interface CustomerRepository extends JpaRepository<Customer, Long>{
}
dataSourceContext.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:jdbc="http://www.springframework.org/schema/jdbc"
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
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">
<context:property-placeholder location="classpath:database.properties"/>
<!-- <jdbc:initialize-database data-source="dataSource" enabled="true">
<jdbc:script location="classpath:db-schema.sql" />
<jdbc:script location="classpath:db-test-data.sql" />
</jdbc:initialize-database> -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${mysql.driver.class.name}" />
<property name="url" value="${mysql.url}" />
<property name="username" value="${mysql.username}" />
<property name="password" value="${mysql.username}" />
</bean>
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
<property name="database" value="MYSQL"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
<!-- spring based scanning for entity classes-->
<property name="packagesToScan" value="com.mkyong.*"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"/>
</beans>
Spring-Quartz.xml
<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"
xmlns:repository="http://www.springframework.org/schema/data/repository"
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
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/data/repository http://www.springframework.org/schema/data/repository/spring-repository.xsd">
<import resource="classpath:dataSourceContext.xml"/>
<jpa:repositories base-package="com.mkyong.repository" />
<context:component-scan base-package="com.mkyong.*" />
<context:annotation-config />
<bean id="jobA" class="com.mkyong.job.JobA" />
<bean id="jobB" class="com.mkyong.job.JobB" />
<bean id="jobC" class="com.mkyong.job.JobC" />
<bean id="autowiredA" class="com.mkyong.job.JobASpringBeanJobFactory" />
<!-- ~~~~~~~~~ Quartz Job ~~~~~~~~~~ -->
<bean name="JobA" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="com.mkyong.job.JobA" />
</bean>
<bean name="JobB" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="com.mkyong.job.JobB" />
</bean>
<bean name="JobC" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="com.mkyong.job.JobC" />
</bean>
<!-- ~~~~~~~~~~~ Cron Trigger, run every 5 seconds ~~~~~~~~~~~~~ -->
<bean id="cronTriggerJobA" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="JobA" />
<property name="cronExpression" value="0/5 * * * * ?" />
</bean>
<bean id="cronTriggerJobB" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="JobB" />
<property name="cronExpression" value="0/5 * * * * ?" />
</bean>
<bean id="cronTriggerJobC" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="JobC" />
<property name="cronExpression" value="0/5 * * * * ?" />
</bean>
<!-- ~~~~~~~~~~~~~~~~ Scheduler bean Factory ~~~~~~~~~~~~~~~~ -->
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="jobFactory" ref="autowiredA"/>
<property name="triggers">
<list>
<ref bean="cronTriggerJobA" />
<!-- <ref bean="cronTriggerJobB" />
<ref bean="cronTriggerJobC" /> -->
</list>
</property>
</bean>
</beans>
JobASpringBeanJobFactory.java
public class JobASpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {
private transient AutowireCapableBeanFactory beanFactory;
#Override
public void setApplicationContext(final ApplicationContext context) {
beanFactory = context.getAutowireCapableBeanFactory();
}
#Override
protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
final Object job = super.createJobInstance(bundle);
beanFactory.autowireBean(job);
return job;
}
}
App.java
public class App {
public static void main(String[] args) throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Quartz.xml");
}
}
Going through the following link http://codrspace.com/Khovansa/spring-quartz-with-a-database/ should help.
Quoting from the above link,
Quartz creates a new job instance on each invocation. It means that Quartz jobs are not regular Spring beans and we can't expect the Spring magic to take an effect automatically (and Spring's 'JobDetailFactoryBean' is not smart enough to do it for us). So we'll have to implement our own job factory that would overwrite the default SpringBeanJobFactory.
So you need to have a custom SpringBeanJobFactory by extending SpringBeanJobFactory & implementing ApplicationContextAware and finally invoke beanFactory.autowireBean(job)

entity manager not correctly injected by spring and gives java.lang.NullPointerException [duplicate]

This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 6 years ago.
I'm a newbie at using frameworks in JAVA EE
so when I'm trying to call a method of the entity manager
it throws a java.lang.NullPointerException
so I want to what I wrote
this is an example of my dao implementation
#Repository
#Transactional
public class IUserDAOImpl implements IUserDAO{
#PersistenceContext
private EntityManager em;
public void addUser(User u) {
em.persist(u);
}
}
this is my service
#Service
public class IUserServiceImpl implements IUserService {
#Autowired
private IUserDAO dao = new IUserDAOImpl();
public void setDao(IUserDAO dao) {
this.dao = dao;
}
public void addUser(User u) {
dao.addUser(u);
}
this is my action class
public class ConnectionAction extends ActionSupport {
User c = new User("a","b","c",11,"d",true);
#Autowired
public IUserService service;
public String execute() throws Exception {
service.addUser(c);
return SUCCESS;
}
the web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="struts_blank" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Struts Blank</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<context-param>
<param-name>contextConfiguration</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
the applicationContext.xml (although it's really messed up so if you noticed sometihng wrong plz tell)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:tx="http://www.springframework.org/schema/tx" 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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="dao"
class="com.iticsys.GBO.dao.IUserDAOImpl">
</bean>
<bean id="service"
class="com.iticsys.GBO.services.IUserServiceImpl">
<property name="dao" ref="dao"></property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/GBO1" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="persistenceUnitManager"
class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocations">
<value>classpath*:META-INF/persistence.xml</value>
</property>
<property name="defaultDataSource" ref="dataSource"> </property>
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="persistenceUnitManager"></property>
<property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml" />
<property name="persistenceUnitName" value="persistenceUnit" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<context:annotation-config></context:annotation-config>
<context:component-scan base-package="com.iticsys.GBO.dao" />
</beans>
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="persistenceUnit"
transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/GBO1" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
and thank you so much in advance
In implementation of class IUserDAOImpl you should instantiate the Object of EntityManager like
private EntityManager em = new EntityManager(/*constructor parameter if any*/);
or You can assign a reference of Object of EntityManager that you can create in your other subclasses like IUserServiceImpl, ConnectionAction.
For that you can add a method in your class IUserDAOImpl which receive that reference.like,
public void setEntityManager(EntityManager em_ref ){ em = em_ref;}
public class HibernateUtil {
static Logger logger = Logger.getLogger(HibernateUtil.class);
private static final String FAILED_TO_CREATE_SESSION_FACTORY_OBJECT = "Failed to create sessionFactory object.";
private static final SessionFactory sessionFactory = buildSessionFactory();
private static ServiceRegistry serviceRegistry;
private static SessionFactory buildSessionFactory() {
try {
Configuration configuration = new Configuration();
configuration.configure("./hibernate.cfg.xml");
configuration.addAnnotatedClass(Calzz.class);
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
return configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
logger.debug(FAILED_TO_CREATE_SESSION_FACTORY_OBJECT + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}

Entities not persisting in integration tests (Hibernate + Spring Roo ActiveRecord )

After much hassle I'm here for help. I am not able to persist data to development database (and also Embedded database) from a test case. When I run the test case without asserting it passes without any exception. I using Spring Roo generated entities. With the same application context configuration I'm able to save data to the database from Spring controller. So I'm convinced that I don't have any problem with my entities.
#TransactionConfiguration(defaultRollback=false)
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration({ "/META-INF/spring/applicationContext.xml" })
#Transactional
public class UserServiceTest {
#Rollback(false)
#Test
public void test() {
Role role = new Role();
role.setRolename("ROLE_ADMIN");
// No Exception here on trying to persist
role.persist();
// Getting Exception here.. "No transaction is in progress"
// role.flush();
// Getting "No entity found for query exception"
assertEquals(Role.findRolesByRolenameEquals("ROLE_ADMIN").getSingleResult().getRolename(), "ROLE_ADMIN");
}
}
My applicationContext.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:neo4j="http://www.springframework.org/schema/data/neo4j"
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:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/data/neo4j http://www.springframework.org/schema/data/neo4j/spring-neo4j.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
">
<context:property-placeholder location="classpath*:META-INF/spring/*.properties" />
<context:spring-configured />
<context:component-scan base-package="com.company">
<context:exclude-filter expression=".*_Roo_.*"
type="regex" />
<context:exclude-filter expression="org.springframework.stereotype.Controller"
type="annotation" />
</context:component-scan>
<bean class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" id="dataSource">
<property name="driverClassName" value="${testDatabase.driverClassName}" />
<property name="url" value="${testDatabase.url}" />
<property name="username" value="${testDatabase.username}" />
<property name="password" value="${testDatabase.password}" />
<property name="testOnBorrow" value="true" />
<property name="testOnReturn" value="true" />
<property name="testWhileIdle" value="true" />
<property name="timeBetweenEvictionRunsMillis" value="1800000" />
<property name="numTestsPerEvictionRun" value="3" />
<property name="minEvictableIdleTimeMillis" value="1800000" />
<property name="validationQuery" value="select 1 from INFORMATION_SCHEMA.TABLES" />
</bean>
<bean class="org.springframework.orm.jpa.JpaTransactionManager"
id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven mode="aspectj"
transaction-manager="transactionManager" proxy-target-class="true" />
<bean
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
id="entityManagerFactory">
<property name="persistenceUnitName" value="persistenceUnitTest" />
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
My Persistence.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="persistenceUnitTest"
transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.company.domain.User</class>
<class>com.company.domain.Role</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<property name="hibernate.hbm2ddl.auto" value="none" />
<property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.DefaultNamingStrategy" />
<property name="hibernate.connection.charSet" value="UTF-8" />
</properties>
</persistence-unit>
</persistence>
EDIT: Added Persistence logic
My Persistence logic in Role_Roo_Jpa_ActiveRecord.aj
// WARNING: DO NOT EDIT THIS FILE. THIS FILE IS MANAGED BY SPRING ROO.
// You may push code into the target .java compilation unit if you wish to edit any member(s).
package com.company.domain;
import com.company.domain.Role;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.transaction.annotation.Transactional;
privileged aspect Role_Roo_Jpa_ActiveRecord {
#PersistenceContext
transient EntityManager Role.entityManager;
public static final EntityManager Role.entityManager() {
EntityManager em = new Role().entityManager;
if (em == null) throw new IllegalStateException("Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)");
return em;
}
public static long Role.countRoles() {
return entityManager().createQuery("SELECT COUNT(o) FROM Role o", Long.class).getSingleResult();
}
public static List<Role> Role.findAllRoles() {
return entityManager().createQuery("SELECT o FROM Role o", Role.class).getResultList();
}
public static Role Role.findRole(Integer roleId) {
if (roleId == null) return null;
return entityManager().find(Role.class, roleId);
}
public static List<Role> Role.findRoleEntries(int firstResult, int maxResults) {
return entityManager().createQuery("SELECT o FROM Role o", Role.class).setFirstResult(firstResult).setMaxResults(maxResults).getResultList();
}
#Transactional
public void Role.persist() {
if (this.entityManager == null) this.entityManager = entityManager();
this.entityManager.persist(this);
}
#Transactional
public void Role.remove() {
if (this.entityManager == null) this.entityManager = entityManager();
if (this.entityManager.contains(this)) {
this.entityManager.remove(this);
} else {
Role attached = Role.findRole(this.roleId);
this.entityManager.remove(attached);
}
}
#Transactional
public void Role.flush() {
if (this.entityManager == null) this.entityManager = entityManager();
this.entityManager.flush();
}
#Transactional
public void Role.clear() {
if (this.entityManager == null) this.entityManager = entityManager();
this.entityManager.clear();
}
#Transactional
public Role Role.merge() {
if (this.entityManager == null) this.entityManager = entityManager();
Role merged = this.entityManager.merge(this);
this.entityManager.flush();
return merged;
}
}
I tried both MySql and Hsqldb database with the same code. But no luck.
I also have another problem. In case of development I didn't have to specify Role and User classes in persistence.xml. If I don't specify them in test configuration I'm getting exceptions.
Roo lets you to configure the persistence engine as many times as you need, try to reconfigure your persistence settings from Roo shell using persistence setup command
In your applicationContext.xml you specified the context:component-scan base-package to com.campus but your entities are on com.company.domain.
Have you changed the main package after the web mvc command?
Try to set applicationContext.xml like this:
<context:component-scan base-package="com.company">
<context:exclude-filter expression=".*_Roo_.*"
type="regex" />
<context:exclude-filter expression="org.springframework.stereotype.Controller"
type="annotation" />
</context:component-scan>
Afther that, I think you can remove the class tags from persistencie.xml.
You need the flush in there. The insert statement doesn't get executed until flush is called.
And the findRolesByRolenameEquals method cannot read the object you have saved from the hibernate session as it uses a query to load the object
If you comment out the assert, and let the test finish, you should be able to see the record in the db as flush should occur when the transaction is complete, is that not the case?
I got it working by removing component-scan from my applicationContext.xml. Now I'm able to persist data into the database(both MySql and Hsqldb) from the test case. Now the test case is passing and the data is seen in the database.
<context:component-scan base-package="com.company">
<context:exclude-filter expression=".*_Roo_.*"
type="regex" />
<context:exclude-filter expression="org.springframework.stereotype.Controller"
type="annotation" />
</context:component-scan>
I still could not make out why this solved my problem. I am still finding a valid explanation here.
My other problem is still there. I had to manually put Role and User classes in persistence.xml.

Spring #Autowired is not working for #WebService annotated class

Getting null pointer while trying to autowire.
Creating a Web application and using following webservices:
WebServiceEndpoint.java
#WebService
#Component
public class ChannelMapWebServiceEndpoint {
#Autowired
ChannelMapWebService webservice;
public ChannelMapInfo4[] getMaps() throws RemoteException {
return this.webservice.getMaps();
}
}
ChannelMapsebserviceImpl.java
#Service
public class ChannelMapWebServiceImpl implements ChannelMapWebService {
public ChannelMapInfo4[] getMaps() throws RemoteException {
System.out.println("hi");
}
}
application context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="ccad" />
<context:component-scan base-package="channelmapwebservice" />
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>/WEB-INF/jdbc.properties</value>
</property>
</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}"/>
</bean>
</beans>
I am getting the autowired object webservice as null while trying to connect through SoapUI.
The ChannelMapWebServiceEndpoint object serving your request class is not instantiated (and managed) by Spring, which is why Spring can't autowire any dependencies.
See the accepted answer for this question:
How to make an #WebService spring aware

Spring + JPA in standalone application doesn't save data in database

I am using
Spring 3.1.1
JPA 2
H2
Hibernate
in standalone Java application. When I run the application, the transaction is executed and when I query the data, the data is retrieved. But the data is not saved when the application is closed.
Please help me.
Here is spring configuration,
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml" />
</bean>
<bean id="sharedEntityManager"
class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
</beans>
Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
version="1.0">
<persistence-unit name="sling">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.sling.data.Trend</class>
<class>com.sling.data.Gc</class>
<properties>
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.connection.driver_class" value="org.h2.Driver" />
<property name="hibernate.connection.url" value="jdbc:h2:sling;DB_CLOSE_DELAY=-1" />
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
</properties>
</persistence-unit>
</persistence>
DAO class,
#Repository
public class GcDao {
#PersistenceContext
private EntityManager em;
public GcDao() {
}
#Transactional
public void add(Gc gc){
em.persist(gc);
}
#SuppressWarnings("unchecked")
#Transactional(readOnly = true)
public List<Gc> getGc(){
String queryText = " from Gc";
Query query = em.createQuery(queryText);
return query.getResultList();
}
}
I believe you still need to add context:component-scan on your dao package before your tx:anotation-driven element.
<context:component-scan base-package="com.sling.dao" />
<tx:annotation-driven />

Resources