I am trying to build a simple form with mysql spring hibernate framework but it is giving errors.I cant figure out why model.hibernateUtil is not initialized. please help me.
Here is code for hibernateUtil :-
package model;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
public class HibernateUtil
{
private static final SessionFactory sessionFactory;
static
{
try
{
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
}
catch (Throwable ex)
{
System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
}
and this is the code for the controller
package controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.HibernateUtil;
import org.hibernate.Session;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
public class UserController implements Controller
{
#Override
public ModelAndView handleRequest(HttpServletRequest hsr, HttpServletResponse hsr1) throws Exception
{
ModelAndView mv = new ModelAndView("user");
String out = "All User Details: ";
try
{
Session session HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
List result = session.createQuery("from Users").list();
mv.addObject("users", result);
session.getTransaction().commit();
}
catch (Exception e)
{
e.printStackTrace();
}
mv.addObject("message", out);
return mv;
}
}
These are the exceptions/errors that are coming.
org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class model.HibernateUtil
org.springframework.web.servlet.DispatcherServlet.triggerAfterCompletionWithError(DispatcherServlet.java:1284)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:965)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
and
java.lang.NoClassDefFoundError: Could not initialize class model.HibernateUtil
controller.UserController.handleRequest(UserController.java:18)
org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:50)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
Please help me I am just a rookie. The database connectivity and all required drivers are in perfect working order.
The name of my database is User and it has 3 attributes by the names UserID, UserName, Password.
Related
I want to add test for spring redirect. First I want to see response object. Here is question for same test : Test redirection Spring
#SpringBootTest
#AutoConfigureMockMvc
public class UserControllerTests {
#Autowired
private MockMvc mockMvc;
#Test
#WithMockUser(username = "myuser", authorities = "admin")
void whenAcceptShouldRedirectRoot() throws Exception {
this.mockMvc.perform(get("/user")).andDo(MockMvcResultHandlers.print());
}
}
#Controller
public class UserController {
#GetMapping("/user")
public String user() {
return "redirect:/user/general";
}
}
And I got the following error
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: Cannot send redirect - response is already committed
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:670)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:72)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:779)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
This is the Database connection java file which will connect to mysql local databse
package com.example.dao;
import java.sql.Connection;
import java.sql.DriverManager;
public class Database {
public Connection getConnection() throws Exception
{
Connection connection = null;
try
{
String connectionURL = "jdbc:mysql://localhost:3306/test1";
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL,
"root", "root");
}
catch (Exception e)
{
e.printStackTrace();
}
return connection;
}
}
This is the web service file for getting and adding up the candidates using com.perpule/hello/plain to get simple hello message & /getCandidate to get all list of candidates
package com.example.webservice;
import java.util.ArrayList;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;
import org.apache.http.HttpServerConnection;
import com.example.dao.Candidate;
import com.example.model.CandidateManager;
import com.google.gson.Gson;
#Path("/hello")
public class SayHello {
ArrayList<Candidate> candidateArr= new ArrayList<Candidate>();
#Context
UriInfo uriInfo;
#Context
Request request;
#GET
#Path("/plain")
#Produces(MediaType.TEXT_PLAIN)
public String sayHelloPlain()
{
return "hello ";
}
#GET
#Path("/candidates")
#Produces(MediaType.TEXT_PLAIN)
public String CandidateList()
{
String candidates=null ;
try {
candidateArr= new CandidateManager().getCandidates();
Gson gson=new Gson();
candidates=gson.toJson(candidateArr);
}catch (Exception e) {
e.printStackTrace();
}
return candidates;
}
#POST
#Path("/addCandidates")
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
#Produces(MediaType.TEXT_PLAIN)
public void submitCandidates(#FormParam("name") String name,
#FormParam("pass") String pass,
#FormParam("phone") String phone, #FormParam("email") String
email,#FormParam("city") String city)
{
Candidate candidate =new Candidate();
candidate.setName(name);
candidate.setPass(pass);
candidate.setPhone(phone);
candidate.setCity(city);
candidate.setEmail(email);
CandidateManager candidateManager=new CandidateManager();
try {
candidateManager.addCandidates(candidate);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Model class
package com.example.model;
import java.sql.Connection;
import java.util.ArrayList;
import com.example.dao.Access;
import com.example.dao.Candidate;
import com.example.dao.Database;
public class CandidateManager {
public ArrayList<Candidate> getCandidates() throws Exception
{
ArrayList<Candidate> candidateList = new ArrayList<Candidate>();
Database db= new Database();
Connection con=db.getConnection();
Access access=new Access();
candidateList=access.getCandidates(con);
return candidateList;
}
public void addCandidates(Candidate candidate) throws Exception
{
// ArrayList<Candidate> candidateData = new ArrayList<Candidate>();
Database db= new Database();
Connection con=db.getConnection();
new Access().addCandidates(con,candidate);
}
}
This is the DAO class for execueteQuery purpose : code for addCandidate is here
package com.example.dao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
public class Access {
ResultSet rs=null;
public ArrayList<Candidate> getCandidates(Connection connection) throws
SQLException{
ArrayList<Candidate> candidateList =new ArrayList<Candidate>();
String sql="select * from candidate";
PreparedStatement psmt =connection.prepareStatement(sql);
rs=psmt.executeQuery();
try {
while(rs.next())
{
Candidate candidateObj = new Candidate();
candidateObj.setName(rs.getString("name"));
candidateObj.setPass(rs.getString("pass"));
candidateObj.setEmail(rs.getString("email"));
candidateObj.setPhone(rs.getString("phone"));
candidateObj.setCity(rs.getString("city"));
candidateList.add(candidateObj);
}
}catch (SQLException e) {
e.printStackTrace();
}
return candidateList;
}
public void addCandidates(Connection connection, Candidate candidate)
throws SQLException
{
String sql="insert into candidate values(?,?,?,?,?)";
try {
PreparedStatement preparedStatement
=connection.prepareStatement(sql);
// preparedStatement.executeQuery();
preparedStatement.setString(1, candidate.name);
preparedStatement.setString(2, candidate.pass);
preparedStatement.setString(3, candidate.phone);
preparedStatement.setString(4, candidate.city);
preparedStatement.setString(5, candidate.phone);
preparedStatement.execute();
connection.close();
}catch (Exception e) {
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
}
}
I have created a web project and created an EJB(interface: LibrarySessionBeanRemote.java and class: LibrarySessionBean). I have deployed the war file on JBoss 7.1 server. Below is the code of both files:
LibrarySessionBeanRemote.java
package com.practice.stateless;
import java.util.List;
import javax.ejb.Remote;
#Remote
public interface LibrarySessionBeanRemote {
void addBook(String bookName);
List<String> getBooks();
}
LibrarySessionBean.java
package com.practice.stateless;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
#Stateless
public class LibrarySessionBean implements LibrarySessionBeanRemote {
List<String> bookShelf;
public LibrarySessionBean() {
bookShelf = new ArrayList<String>();
}
#Override
public void addBook(final String bookName) {
bookShelf.add(bookName);
}
#Override
public List<String> getBooks() {
return bookShelf;
}
}
I am trying to call the EJB locally inside main method, below is the code:
LibrarySessionBeanTest2
package com.practice.stateless.test;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.practice.stateless.LibrarySessionBean;
import com.practice.stateless.LibrarySessionBeanRemote;
public class LibrarySessionBeanTest2 {
public static LibrarySessionBeanRemote doLookup() throws NamingException {
final Properties jndiProp = new Properties();
jndiProp.put(Context.INITIAL_CONTEXT_FACTORY,
"org.jboss.naming.remote.client.InitialContextFactory");
jndiProp.put(Context.PROVIDER_URL, "remote://localhost:4447");
jndiProp.put(Context.SECURITY_PRINCIPAL, "username");
jndiProp.put(Context.SECURITY_CREDENTIALS, "password");
final String appName = "";
final String moduleName = "StatelessExample";
final String distinctName = "";
final String beanName = LibrarySessionBean.class.getSimpleName();
final String viewClassName = LibrarySessionBeanRemote.class.getName();
final Context ctx = new InitialContext(jndiProp);
final String jndiName = "ejb:" + appName + "/" + moduleName + "/"
+ distinctName + "/" + beanName + "!" + viewClassName;
// jndiName = "java:global/StatelessExample/LibrarySessionBean";
return (LibrarySessionBeanRemote) ctx.lookup(jndiName);
}
public static void invokeStatelessBean() throws NamingException {
final LibrarySessionBeanRemote librarySessionBeanRemote = doLookup();
librarySessionBeanRemote.addBook("book 1");
for (final String book : librarySessionBeanRemote.getBooks()) {
System.out.println(book);
}
}
public static void main(final String[] args) {
try {
invokeStatelessBean();
} catch (final NamingException e) {
e.printStackTrace();
}
}
}
After running the LibrarySessionBeanTest2 class I am getting below error:
javax.naming.NameNotFoundException: ejb:/StatelessExample//LibrarySessionBean!com.practice.stateless.LibrarySessionBeanRemote -- service jboss.naming.context.java.jboss.exported.ejb:.StatelessExample."LibrarySessionBean!com.practice.stateless.LibrarySessionBeanRemote"
at org.jboss.as.naming.ServiceBasedNamingStore.lookup(ServiceBasedNamingStore.java:97)
at org.jboss.as.naming.NamingContext.lookup(NamingContext.java:178)
at org.jboss.naming.remote.protocol.v1.Protocol$1.handleServerMessage(Protocol.java:127)
at org.jboss.naming.remote.protocol.v1.RemoteNamingServerV1$MessageReciever$1.run(RemoteNamingServerV1.java:73)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
I am new to EJB 3 so I don't know whether I am using JNDI name correctly or not. It would be great if somebody can help me to fix this problem.
Now issue has been fixed by adding two more properties, please find them below:
jndiProp.put("jboss.naming.client.ejb.context", true);
jndiProp.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
SOLVED : Go through comments/chat
I am using Spring 4.1.1 with annotation based configuration. While trying to use eclipselink with spring, i get error on merge method stating No transaction is currently active
Following is the stacktrace:
javax.persistence.TransactionRequiredException:
Exception Description: No transaction is currently active
at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionWrapper.throwCheckTransactionFailedException(EntityTransactionWrapper.java:87)
at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionWrapper.checkForTransaction(EntityTransactionWrapper.java:50)
Exception occured at : javax.persistence.TransactionRequiredException:
Exception Description: No transaction is currently active
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.checkForTransaction(EntityManagerImpl.java:2041)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.flush(EntityManagerImpl.java:863)
at com.cdl.box.dao.GenericDao.merge(GenericDao.java:61)
at com.cdl.box.dao.GenericDao$$FastClassBySpringCGLIB$$9e11ea6a.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
at com.cdl.box.dao.PersonDao$$EnhancerBySpringCGLIB$$51ee0a8f.merge(<generated>)
at com.cdl.box.service.person.PersonService.addPerson(PersonService.java:23)
at com.cdl.box.service.person.PersonService$$FastClassBySpringCGLIB$$dbc06f33.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:266)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
at com.cdl.box.service.person.PersonService$$EnhancerBySpringCGLIB$$35eaf713.addPerson(<generated>)
at com.cdl.box.controller.PersonController.add(PersonController.java:55)
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:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
WebConfig.java
#EnableWebMvc
#Configuration
#ComponentScan("com.myapp")
#PropertySource(value = "classpath:application.properties")
#EnableTransactionManagement(proxyTargetClass=true)
public class WebConfig extends WebMvcConfigurerAdapter{
#Bean
public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
#Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
System.out.println("UrlBasedViewResolver........");
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
#Bean
MultipartResolver multipartResolver() {
MultipartResolver resolver = new StandardServletMultipartResolver();
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
System.out.println("In Resouce Handler");
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/defaultTheme/");
}
}
DBConfig.java
import java.util.Properties;
import javax.sql.DataSource;
import org.eclipse.persistence.platform.database.DatabasePlatform;
import org.eclipse.persistence.platform.database.MySQLPlatform;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableLoadTimeWeaving;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver;
import org.springframework.instrument.classloading.SimpleLoadTimeWeaver;
import org.springframework.orm.jpa.JpaDialect;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect;
import org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.jolbox.bonecp.BoneCPDataSource;
#Configuration
#EnableTransactionManagement(proxyTargetClass = true)
#EnableLoadTimeWeaving
public class DBConfig {
#Value("${jdbc.driverClassName}")
private String driverClassName;
#Value("${jdbc.url}")
private String url;
#Value("${jdbc.username}")
private String username;
#Value("${jdbc.password}")
private String password;
#Value("${eclipselink.persistenceUnitName}")
private String persistenceUnitName;
#Bean()
public DataSource getDataSource() {
BoneCPDataSource ds = new BoneCPDataSource();
System.out.println("Driver Name : " + driverClassName);
System.out.println("Url : " + url);
ds.setDriverClass(driverClassName);
ds.setJdbcUrl(url);
ds.setUsername(username);
ds.setPassword(password);
ds.setMaxConnectionsPerPartition(5);
ds.setMinConnectionsPerPartition(2);
ds.setAcquireIncrement(2);
return ds;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(getDataSource());
em.setJpaDialect(jpaDialect());
em.setPackagesToScan("com.myapp.model", "com.myapp.model.person");
em.setPersistenceUnitName(persistenceUnitName);
DatabasePlatform dp = new MySQLPlatform();
em.setJpaVendorAdapter(getEclipseLinkJpaVendorAdapter());
//em.setLoadTimeWeaver(new SimpleLoadTimeWeaver());
em.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
return em;
}
#Bean
public EclipseLinkJpaVendorAdapter getEclipseLinkJpaVendorAdapter() {
EclipseLinkJpaVendorAdapter vendorAdapter = new EclipseLinkJpaVendorAdapter();
vendorAdapter.setDatabasePlatform("org.eclipse.persistence.platform.database.MySQLPlatform");
vendorAdapter.setGenerateDdl(false);
vendorAdapter.setShowSql(true);
return vendorAdapter;
}
#Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());
return transactionManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor() {
return new PersistenceExceptionTranslationPostProcessor();
}
#Bean
public JpaDialect jpaDialect() {
return new EclipseLinkJpaDialect();
}
}
WebInitializer.java
import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class WebInitializer implements WebApplicationInitializer{
public void onStartup(ServletContext servletContext) throws ServletException {
// TODO Auto-generated method stub
System.out.println("In WebApplicationInitializer.....");
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
// Manage the lifecycle of the root application context
servletContext.addListener(new ContextLoaderListener(rootContext));
servletContext.setInitParameter("contextConfigLocation", "<NONE>");
rootContext.register(DBConfig.class);
rootContext.register(WebConfig.class);
rootContext.setServletContext(servletContext);
ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
servlet.setMultipartConfig(new MultipartConfigElement("/img", 1024*1024*5, 1024*1024*5*5, 1024*1024));
}
}
Fetching the data works perfectly. Error occurs during insert/update using eclipselink.
I went through lot of posts & applied all suggestions. But unfortunately it is not working. I am not sure what I am missing. Do you see anything wrong with the configuration ? Please suggest me what I am doing wrong here.
EDIT:
Following is my service class with #Transactional.
import java.util.List;
import org.eclipse.persistence.queries.ReadAllQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.myapp.dao.PersonDao;
import com.myapp.model.person.Person;
#Service
#Transactional(propagation=Propagation.REQUIRED)
public class PersonService {
#Autowired
private PersonDao personDao;
public void addPerson(Person person) {
Person p = personDao.merge(person);
System.out.println(p.getCity());
}
public void updatePerson(Person person) {
personDao.persist(person);
}
public Person getPerson(int id) {
return personDao.findById(id);
}
public void deletePerson(int id) {
personDao.deleteById(id);
}
public List<Person> getPersons(int first, int rows){
ReadAllQuery readAllQuery = new ReadAllQuery(Person.class);
readAllQuery.setJPQLString("SELECT OBJECT(per) FROM Person per");
return personDao.executeReadAllQuery(readAllQuery, first, rows);
}
}
With #Transactional on service class I get following error while I start Tomcat
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'personController' defined in file [D:\Hemraj-Dev\apache-tomcat-7.0.56\webapps\yourbox\WEB-INF\classes\com\myapp\controller\PersonController.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [com.myapp.service.person.PersonService]: : Error creating bean with name 'personService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.myapp.dao.PersonDao com.myapp.service.person.PersonService.personDao; nested exception is java.lang.IllegalArgumentException: Can not set com.myapp.dao.PersonDao field com.myapp.service.person.PersonService.personDao to com.sun.proxy.$Proxy25; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.myapp.dao.PersonDao com.myapp.service.person.PersonService.personDao; nested exception is java.lang.IllegalArgumentException: Can not set com.myapp.dao.PersonDao field com.myapp.service.person.PersonService.personDao to com.sun.proxy.$Proxy25
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:751)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1133)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1036)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:505)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:725)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4992)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5492)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.myapp.dao.PersonDao com.myapp.service.person.PersonService.personDao; nested exception is java.lang.IllegalArgumentException: Can not set com.myapp.dao.PersonDao field com.myapp.service.person.PersonService.personDao to com.sun.proxy.$Proxy25
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1204)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1081)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1006)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:904)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:815)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:743)
... 24 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.myapp.dao.PersonDao com.myapp.service.person.PersonService.personDao; nested exception is java.lang.IllegalArgumentException: Can not set com.myapp.dao.PersonDao field com.myapp.service.person.PersonService.personDao to com.sun.proxy.$Proxy25
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:555)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 36 more
Caused by: java.lang.IllegalArgumentException: Can not set com.myapp.dao.PersonDao field com.myapp.service.person.PersonService.personDao to com.sun.proxy.$Proxy25
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:164)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:168)
at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:81)
at java.lang.reflect.Field.set(Field.java:741)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:551)
... 38 more
EDIT2:
I have replaced new stacktarce on top of question for No Transaction is currently active error. Following is my DAOs.
PersonDao.java:
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.myapp.model.person.Person;
#Repository("personDao")
public class PersonDao extends GenericDao<Person, Integer> {
#Override
public int deleteById(Integer id) {
Query q = getEntityManager().createQuery(
"delete from Employees where employeeId = :id");
q.setParameter("id", id);
return q.executeUpdate();
}
}
GenericDao.java
public class GenericDao<E, ID extends Serializable>{
private final Class<E> persistentClass;
protected EntityManager entityManager;
private EntityManagerFactory emf;
#PersistenceContext(unitName = "cdlbox")
private EntityManager em;
#Value("${eclipselink.persistenceUnitName}")
private String persistenceUnitName;
#SuppressWarnings("unchecked")
public GenericDao() {
this.persistentClass = (Class<E>) ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
}
protected Class<E> getEntityClass() {
return persistentClass;
}
protected EntityManager getEntityManager(){
return em;
}
public E merge(E entity) {
E e = null;
try{
e = em.merge(entity);
em.flush();
}catch (Exception ex) {
System.out.println("Exception occured at : " + ex);
ex.printStackTrace();
}
return e;
}
public void persist(E entity) {
em.persist(entity);
}
public void remove(E entity) {
em.remove(entity);
}
public E findById(ID id) {
return em.find(getEntityClass(), id);
}
#SuppressWarnings("unchecked")
public List<E> executeNamedQuery(String queryName,
Map<String, Object> parameterMap) {
Query query = em.createNamedQuery(
queryName);
if (parameterMap != null) {
for (String param : parameterMap.keySet()) {
query.setParameter(param, parameterMap.get(param));
}
}
return query.getResultList();
}
public List<E> executeNamedQuery(String queryName) {
return executeNamedQuery(queryName, null);
}
#SuppressWarnings("unchecked")
public int getCount(String countField, Expression expr) {
ReportQuery query = new ReportQuery(getEntityClass(), null);
query.setSelectionCriteria(expr);
query.addCount("count", query.getExpressionBuilder().get(countField)
.distinct());
List<ReportQueryResult> result = (List<ReportQueryResult>) getSession().executeQuery(query);
ReportQueryResult reportQueryResult = result.get(0);
BigDecimal count = (BigDecimal) reportQueryResult.getResults().get(0);
return count.intValueExact();
}
protected Session getSession() {
//EntityManagerImpl has to be imported as org.eclipse.persistence.internal.jpa.EntityManagerImpl
Session session = ((EntityManagerImpl) em).getActiveSession();
return session;
}
public List<E> executeReadAllQuery(ReadAllQuery readAllQuery, int first,
int rows) {
readAllQuery.setFirstResult(first);
readAllQuery.setMaxRows(first + rows);
return executeDatabaseQuery(readAllQuery);
}
#SuppressWarnings("unchecked")
public List<E> executeDatabaseQuery(DatabaseQuery q) {
List<E> resultList = (List<E>) getSession().executeQuery(q);
return resultList;
}
public int deleteById(ID id) {
// TODO Auto-generated method stub
return 0;
}
}
EDIT3:
Got this exception while using #PersistenceContext
If you are using EclipseLink and JOTM running on Tomcat then in the persistence.xml, I guess you forgot the property:
<properties>
<property name="eclipselink.target-server" value="org.eclipse.persistence.transaction.jotm.JotmTransactionController"/>
</properties>
Does anyone know if there is a Spring MVC mapping view for Gson? I'm looking for something similar to org.springframework.web.servlet.view.json.MappingJacksonJsonView.
Ideally it would take my ModelMap and render it as JSON, respecting my renderedAttributes set in the ContentNegotiatingViewResolver declaration
We plan to use Gson extensively in the application as it seems safer and better than Jackson. That said, we're getting hung up by the need to have two different JSON libraries in order to do native JSON views.
Thanks in advance!
[cross-posted to Spring forums]
aweigold got me most of the way there, but to concretely outline a solution for Spring 3.1 Java based configuration, here's what I did.
Grab GsonHttpMessageConverter.java from the spring-android-rest-template project.
Register your GsonHttpMessageConverter with the message converters in your MVC config.
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new GsonHttpMessageConverter());
}
}
The Spring docs outline this process, but aren't crystal clear. In order to get this to work properly, I had to extend WebMvcConfigurerAdapter, and then override configureMesageConverters. After doing this, you should be able to do the following in your controller method:
#Controller
public class AppController {
#RequestMapping(value = "messages", produces = MediaType.APPLICATION_JSON_VALUE)
public List<Message> getMessages() {
// .. Get list of messages
return messages;
}
}
And voila! JSON output.
I would recommend to extend AbstractView just like the MappingJacksonJsonView does.
Personally, for JSON, I prefer to use #Responsebody, and just return the object rather than a model and view, this makes it easier to test. If you would like to use GSON for that, just create a custom HttpMessageConverter like this:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;
import com.vitalimages.string.StringUtils;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.stereotype.Component;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.sql.Timestamp;
#Component
public class GSONHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private GsonBuilder gsonBuilder = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
.registerTypeAdapter(Timestamp.class, new GSONTimestampConverter());
public GSONHttpMessageConverter() {
super(new MediaType("application", "json", DEFAULT_CHARSET));
}
#Override
protected boolean supports(Class<?> clazz) {
// should not be called, since we override canRead/Write instead
throw new UnsupportedOperationException();
}
#Override
public boolean canRead(Class<?> clazz, MediaType mediaType) {
return MediaType.APPLICATION_JSON.isCompatibleWith(mediaType);
}
public boolean canWrite(Class<?> clazz, MediaType mediaType) {
return MediaType.APPLICATION_JSON.isCompatibleWith(mediaType);
}
public void registerTypeAdapter(Type type, Object serializer) {
gsonBuilder.registerTypeAdapter(type, serializer);
}
#Override
protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
try {
Gson gson = gsonBuilder.create();
return gson.fromJson(StringUtils.convertStreamToString(inputMessage.getBody()), clazz);
} catch (JsonParseException e) {
throw new HttpMessageNotReadableException("Could not read JSON: " + e.getMessage(), e);
}
}
#Override
protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
Type genericType = TypeToken.get(o.getClass()).getType();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputMessage.getBody(), DEFAULT_CHARSET));
try {
// See http://code.google.com/p/google-gson/issues/detail?id=199 for details on SQLTimestamp conversion
Gson gson = gsonBuilder.create();
writer.append(gson.toJson(o, genericType));
} finally {
writer.flush();
writer.close();
}
}
}
And then add it to your converter list in your handler adapter like this:
#Bean
public HandlerAdapter handlerAdapter() {
final AnnotationMethodHandlerAdapter handlerAdapter = new AnnotationMethodHandlerAdapter();
handlerAdapter.setAlwaysUseFullPath(true);
List<HttpMessageConverter<?>> converterList = new ArrayList<HttpMessageConverter<?>>();
converterList.addAll(Arrays.asList(handlerAdapter.getMessageConverters()));
converterList.add(jibxHttpMessageConverter);
converterList.add(gsonHttpMessageConverter);
handlerAdapter.setMessageConverters(converterList.toArray(new HttpMessageConverter<?>[converterList.size()]));
return handlerAdapter;
}