已解决:浏览评论/聊天
我正在使用Spring 4.1.1和基于注释的配置。在尝试使用带弹簧的eclipselink时,我在merge
方法上遇到错误{1}}
以下是 stacktrace:
No transaction is currently active
WebConfig.java
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)
DBConfig.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/");
}
}
WebInitializer.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();
}
}
获取数据非常有效。使用eclipselink进行插入/更新时出错。
我经历过很多帖子&amp;应用了所有建议。但不幸的是它没有用。我不确定我错过了什么。你看到配置有什么问题吗?请告诉我这里我做错了什么。
修改
以下是我的@Transactional服务类。
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));
}
}
对于服务类的@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);
}
}
Tomcat
EDIT2:
我已针对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
错误替换了新的stacktarce问题。以下是我的DAO。
PersonDao.java:
No Transaction is currently active
GenericDao.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();
}
}
EDIT3:
使用 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;
}
}
答案 0 :(得分:0)
如果您在EclipseLink and JOTM
上使用Tomcat
,那么在persistence.xml中,我猜您忘记了property
:
<properties>
<property name="eclipselink.target-server" value="org.eclipse.persistence.transaction.jotm.JotmTransactionController"/>
</properties>