I am trying to get an object from my database using Spring REST API. The problem is that I am not receiving the content correctly.
My log output:
/hello
Hibernate: select this_.id as id0_0_, this_.countryCode as countryC2_0_0_ from Country this_ where this_.countryCode=?
Found: at
And the controller I use:
import java.util.Iterator;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.mahlzeit.datamodel.HibernateTest;
import com.mahlzeit.datamodel.address.Country;
#RestController
public class HelloWorldController {
#RequestMapping(value = "/hello")//, method = RequestMethod.GET)
public Country hello(ModelMap model) {
System.out.println("/hello");
HibernateTest hbt = new HibernateTest();
Session session = hbt.sessionFactory.openSession();
Criteria cr = session.createCriteria(Country.class);
cr.add(Restrictions.eq("countryCode", "at"));
List<Country> queryAustria = cr.list();
if (queryAustria.isEmpty() == true) {
System.err.println("at not found");
return null;
}
Country austria = null;
for (Iterator<Country> iterator = queryAustria.iterator(); iterator
.hasNext();) {
Country country = (Country) iterator.next();
if (country.getCountryCode().equals("at")) {
austria = country;
break;
}
}
System.out.println("Found: "+ austria.getCountryCode());
return austria;
}
}
So, I am getting back my desired object from Hibernate but what I am actually getting back is
HTTP Status 404
This is Country.java:
#Entity
public class Country implements Serializable {
private static final long serialVersionUID = -2060021861139912774L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
#NotNull
#Column(length=2,unique=true)
private String countryCode;
// Setter & Getter ..
}
Config file:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.mahlzeit.server.mobile" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
If you are using the InternalResourceViewResolver then Spring will try to resolve the View based on view name that you are passing. So it will look for the file /WEB-INF/austria.jsp assuming the controller is returning the value as "austria". So that is the reason you are getting 404 error.
So to fix the issue, add <mvc:annotation-driven /> in Spring configuration file.
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.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">
<context:component-scan base-package="com.mahlzeit.server.mobile" />
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
Also you need to have the JSON related Jars in your classpath -- WEB-INF/lib folder:
jackson-core-asl-1.9.13.jar & jackson-mapper-asl-1.9.13.jar
Related
i want to have something like a plugin system for Spring which are accessible through an REST endpoint.
So I was thinking I could simply implement a controller module as #RestController bean and add it to my beans definition.
Unfortunately I cannot figure out how to configure a #RestController and #RequestMapping using XML.
So far I think I have configured the a
This is my main class:
package me.example.app;
import org.springframework.context.ApplicationContext;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.context.annotation.*;
import java.lang.System;
import java.util.Properties;
#SpringBootApplication
#RestController
#ImportResource({"classpath:applicationContext.xml"})
public class GettingstartedApplication {
public GettingstartedApplication() {
System.out.println("INIT Application");
}
#RequestMapping("/")
String home() {
return "Hello World!";
}
public static void main(String[] args) {
ApplicationContext applicationContext = SpringApplication.run(GettingstartedApplication.class, args);
}
}
This is my resources/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:util="http://www.springframework.org/schema/util" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<bean id="xmlStringBean1" class="java.lang.String">
<constructor-arg value="stringBean1" />
</bean>
<bean id="xmlController" class="me.tom.app.XMLController">
<constructor-arg value="xmlControllerArg" />
</bean>
<bean id="testSimpleUrlHandlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<util:map id="emails" map-class="java.util.HashMap">
<entry key="/xml" value="xmlController"/>
</util:map>
</property>
</bean>
</beans>
This is my XMLController.java
package me.example.app;
public class XMLController{
public XMLController(String arg) {
System.out.println("INIT XMLController");
}
String home() {
return "XMLController";
}
}
I am trying to migrate a project from a traditional (working) Java servlet application to Spring MVC in the NetBeans IDE, but my program absolutely refuses to ping the Controller. On the client side, I see the following 404 errors:
index.do?displayType=table:1 Failed to load resource: the server responded with a status of 404 (Not Found)
index.do?displayType=table:1 Failed to load resource: the server responded with a status of 404 (Not Found)
I invoke the controller methods like so:
$.get("index.do","displayType=table", function( data ) {
jstring = JSON.parse(data.substr(12).slice(0, -1));
});
$.get("index.do","displayType=pivot",function(unparsedJSON) {});
$.post("index.do","jsonString=" + JSON.stringify(hot.getData()));
Below are my controller and xml configuration files:
MappingControl.java
package controllers;
import infoLoader.JsonWriter;
import infoLoader.getJSON;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.springframework.http.HttpMethod.GET;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
#Controller
#RequestMapping("/")
public class MappingControl {
#RequestMapping(value="/index.do", method=RequestMethod.GET)
public String populatePivotAndSheet(#RequestParam("displayType") String type) {
String returnedJSON = "";
try {
returnedJSON = getJSON.getJSON(type);
} catch (Exception ex) {
System.out.println("Unable to retrieve JSON");
}
return returnedJSON;
}
#RequestMapping(value="/index.do", method=RequestMethod.POST)
public void deliverSheet(#RequestParam("jsonString") String writableJSON) {
String returnedJSON = "";
JsonWriter.writeJSON(writableJSON);
}
}
applicationContext.xml
<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
</beans>
dispatcher-servlet.xml
<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd" xmlns:mvc="http://www.springframework.org/schema/mvc">
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<!--
Most controllers will use the ControllerClassNameHandlerMapping above, but
for the index controller we are using ParameterizableViewController, so we must
define an explicit mapping for it.
-->
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<!--
The index controller.
-->
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
<mvc:resources mapping="/resources/**" location="/resources" />
<context:component-scan base-package="controllers" />
</beans>
I've been building this based on the default Spring-MVC template provided by NetBeans, so if any of you believe the template is poorly formatted and should be changed in some way, I would appreciate any input you might have.
Thanks so much for your time, guys, and let me know if anything is unclear.
You need add #ResponseBody to your method,due to in your case,you want to return the json data,if you missing #ResponseBody it will return to the view page,however you do not specify any view page in your code,thus will cause 404 error
#ResponseBody
#RequestMapping(value="/index.do", method=RequestMethod.GET)
public String populatePivotAndSheet(#RequestParam("displayType") String type) {
String returnedJSON = "";
try {
returnedJSON = getJSON.getJSON(type);
} catch (Exception ex) {
System.out.println("Unable to retrieve JSON");
}
return returnedJSON;
}
#ResponseBody
#RequestMapping(value="/index.do", method=RequestMethod.POST)
public void deliverSheet(#RequestParam("jsonString") String writableJSON) {
String returnedJSON = "";
JsonWriter.writeJSON(writableJSON);
}
Facing problem in calling a REST Controller with Json. Getting 404 error. But not able to find the problem. The Controller is defined. No Spelling mistake.
P.S. To use REST do we need configuration in web.xml or servlet-config.xml .
I have jackson-databind and jax-rs in dependencies.
NewBie in Spring Angular . Need help.
I am trying to call '/addintoexp' controller File
File : expense.js
'use strict';
var addexp=angular.module('emsExpenseApp',[ ]);
addexp.controller('addExpCtrl',[ '$scope', '$http', '$location' ,function($scope,$http,$location){
console.log("Reached the Angular controller");
var vm=this;
vm.expense={};
vm.expense.expense_name="GROFERS MONTHLY";
// add-expense button implementation
vm.submit=function(){
console.log("Inside Submit Function");
console.log(vm.expense);
$http({
method: 'POST',
url: addintoexp,
data: vm.expense,
dataType: 'application/json',
headers: {'Content-Type': 'application/json'}
}).success(function(response) {
alert(' Success ');
console.dir(response);
//alert('Success');
// redirect path
//$location.path('dashboard/users');
}).error(function(response){
alert('Error');
});
}
}]);
File: ExpenseController.java
package com.ems.controller;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.ems.model.Expense;
import com.ems.model.User;
import com.sun.media.jfxmedia.logging.Logger;
/**
*
* #author Ankit
*
* In this controller , methods like add_expense, del_expense, view_expense, edit_expense
* all accordingly to the user_id
*
*
*
*/
#RestController
public class ExpenseController {
#RequestMapping(value="/add-exp", method=RequestMethod.GET)
public ModelAndView addExpense(){
ModelAndView m=new ModelAndView("add-expense");
return m;
}
/*
#RequestMapping(value="/addintoexp", method=RequestMethod.POST)
public String addExpense(#RequestParam("exp-name") String expname,
#RequestParam("exp-desc") String expdesc,
#RequestParam("exp-amount") String expamount,
#RequestParam("exp-date") String expdate,
#RequestParam("exp-notes") String expnotes,
#RequestParam("exp-category") String expcategory
){
System.out.println(
" Expense Name : "+expname +
" Expense Desc : "+expdesc +
" Expense Amount : " +expamount+
" Expense Date : "+expdate+
" Expense Notes : "+expnotes+
" Expense Category : "+expcategory
);
return "redirect:/add-exp.html";
}
*/
//404 Error getting for this controller
#RequestMapping(value = "/addintoexp",method = RequestMethod.POST,headers="Accept=application/json")
public ResponseEntity<Void> addexpenser(#RequestBody Expense e){
System.out.println("Inside the Adding Exp Controller. Hurrah. REST is working");
System.out.println(e.getExpense_name());
System.out.println(e.getExpense_category());
System.out.println(e.getExpense_desc());
HttpHeaders header = new HttpHeaders();
return new ResponseEntity<Void>(header,HttpStatus.CREATED);
}
//Rest API Add Expense
}
File: web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<servlet>
<servlet-name>expTrackerServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/servlet-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>expTrackerServlet</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<display-name>Archetype Created Web Application</display-name>
</web-app>
File: Servlet-Config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:resources location="/static" mapping="/static/**"/>
<mvc:annotation-driven/>
<context:component-scan base-package="com.ems"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="expenseDaoImpl" class="com.ems.dao.ExpenseDaoImpl">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="loginDaoImpl" class="com.ems.dao.LoginDaoImpl">
<property name="dataSource" ref="dataSource" />
</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/exms" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
I'm struggling to implement a WatchServiceDirectoryScanner. I want to use the scanner to monitor new file uploads to a directory + sub directories. This will exist as part of a Spring boot MVC microservice. I can do this using Java 7's WatchService but would prefer a spring file integration style, AOP style
I have it registered as a #Bean in my app config but I'm struggling to figure out how to have it poll and scan a directory and then call... something (a message endpoint?) when a file is detected. Is anyone able to point me in the right direction for even conceptually how this is done. I cannot find an example implementation of this anywhere.
http://docs.spring.io/spring-integration/reference/html/files.html#_watchservicedirectoryscanner
http://docs.spring.io/spring-integration/api/org/springframework/integration/file/DefaultDirectoryScanner.html#listFiles-java.io.File-
here is my Spring appConfig:
public class appConfig {
#Bean
public DirectoryScanner scanner() {
return new WatchServiceDirectoryScanner("/uploads/test");
}
}
# create one configuration file and bind an input file channel here
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-file="http://www.springframework.org/schema/integration/file"
xmlns:int-mail="http://www.springframework.org/schema/integration/mail"
xmlns:int-stream="http://www.springframework.org/schema/integration/stream"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/integration/mail http://www.springframework.org/schema/integration/mail/spring-integration-mail.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/file http://www.springframework.org/schema/integration/file/spring-integration-file.xsd
http://www.springframework.org/schema/integration/stream http://www.springframework.org/schema/integration/stream/spring-integration-stream.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">
<int:annotation-config />
<int:channel id="cfpFileIn"></int:channel>
<int-file:inbound-channel-adapter id="cfpFileIn"
directory="${cfp.flight.data.dir}" auto-startup="true" scanner="csvDirScanner">
<int:poller fixed-delay="${cfp.flight.data.dir.polling.delay}"></int:poller>
</int-file:inbound-channel-adapter>
<bean id="csvDirScanner"
class="org.springframework.integration.file.WatchServiceDirectoryScanner">
<constructor-arg index="0" value="${cfp.flight.data.dir}" />
<property name="filter" ref="csvCompositeFilter" />
<property name="autoStartup" value="true" />
</bean>
<bean id="csvCompositeFilter"
class="org.springframework.integration.file.filters.CompositeFileListFilter">
<constructor-arg>
<list>
<bean
class="org.springframework.integration.file.filters.SimplePatternFileListFilter">
<constructor-arg value="*.csv" />
</bean>
<ref bean="persistentFilter" />
</list>
</constructor-arg>
</bean>
<bean id="persistentFilter"
class="org.springframework.integration.file.filters.FileSystemPersistentAcceptOnceFileListFilter">
<constructor-arg index="0" ref="metadataStore" />
<constructor-arg index="1" name="prefix" value="" />
<property name="flushOnUpdate" value="true" />
</bean>
<bean name="metadataStore"
class="org.springframework.integration.metadata.PropertiesPersistingMetadataStore">
<property name="baseDirectory" value="${metadata.dir}"></property>
</bean>
</beans>
import java.io.File;
import java.util.concurrent.locks.ReentrantLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.stereotype.Component;
#Component
public class BatchJobScheduler {
private static final Logger logger = LoggerFactory.getLogger(BatchJobScheduler.class);
#Autowired
protected JobLauncher jobLauncher;
#Autowired
#Qualifier(value = "job")
private Job job;
#ServiceActivator(inputChannel = "cfpFileIn")
public void run(File file) {
String fileName = file.getAbsolutePath();
logger.info("BatchJobScheduler Running #################"+fileName);
JobParameters jobParameters = new JobParametersBuilder().addString(
"input.file", fileName).toJobParameters();
try {
JobExecution execution = jobLauncher.run(job,
jobParameters);
logger.info(" BatchJobScheduler Exit Status : " + execution.getStatus() +"::"+execution.getAllFailureExceptions());
} catch (JobExecutionAlreadyRunningException | JobRestartException
| JobInstanceAlreadyCompleteException
| JobParametersInvalidException e) {
logger.error(" BatchJobScheduler Exit Status : Exception ::",e);
}
}
}
I am using Spring and integrating with hibernate 4 as persistence Provider, here what i ma trying is to do crud operation
on student Entity,
All my select operations are working fine, but add and update operation are not working,
My persistence.xml,
<?xml version="1.0" encoding="UTF-8"?>
<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="forSpring" transaction-type="JTA">
<class>com.entity.Student</class>
</persistence-unit>
</persistence>
My Spring-bean.xml,
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jee="http://www.springframework.org/schema/jee"
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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="com.*" />
<jee:jndi-lookup id="datasourceId" jndi-name="jdbc/myPrac" resource-ref="true" />
<bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager" />
<!-- Spring integration with JPA -->
<bean id="vendorAdaptor-inj" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="DERBY" />
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
</bean>
<bean id="entityMgrFactory-inj" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="datasourceId" />
<property name="persistenceUnitName" value="forSpring" />
<property name="jpaVendorAdapter" ref="vendorAdaptor-inj" />
</bean>
</beans>
This is my StudentDAO,
package com.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.entity.Student;
#Repository("studentSpringDao-inj")
#Transactional(value="txManager",readOnly=true)
public class StudentSpringDAO {
#PersistenceContext(unitName="forSpring")
private EntityManager em;
public EntityManager getEm() {
return em;
}
public void setEm(EntityManager em) {
this.em = em;
}
public List<Student> getStudentList() throws Exception{
System.out.println(" \n\n\n LOADING... \n\n\n ");
String query = "select s from Student s order by s.studentId desc";
TypedQuery<Student> studentQuery = em.createQuery(query,Student.class);
return studentQuery.getResultList();
}
public Integer latestStudent() throws Exception{
String query = "select max(s.studentId) from Student s";
TypedQuery<Integer> studentQuery = em.createQuery(query,Integer.class);
return studentQuery.getResultList().get(0);
}
#Transactional(value="txManager",readOnly=false,propagation=Propagation.REQUIRES_NEW)
public Student saveStudent(Student student) throws Exception{
return em.merge(student);
}
}
Just for the information, i am using jndi look-up name "jdbc/myPrac" to look-up the datasource,
Can you help me out with this, do i am missing any configuration in spring-bean.xml
#Transactional(value="txManager",readOnly=true)
What do you think readOnly=true means and have you tried it with readOnly=false?
replace the class org.springframework.transaction.jta.JtaTransactionManager
with org.springframework.orm.jpa.JpaTransactionManager and add tx:annotation-driven