`
mywayscut
  • 浏览: 25431 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

spring中service中findAll无法取到值的问题

阅读更多
IcreaderService.java
package gate.service;

import gate.SessionFactory.HibernateSessionFactory;
import gate.dao.AdminDAO;
import gate.dao.IcreaderDAO;
import gate.model.Icreader;
import gate.service.VO.IcreaderVO;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class IcreaderService {
	public List<IcreaderVO> findAllIcreader() throws IllegalAccessException, InvocationTargetException{
		IcreaderDAO con = new IcreaderDAO();
		List<IcreaderVO> list = new ArrayList<IcreaderVO>();
		Iterator<Icreader> item = con.findAll().iterator();
		while(item.hasNext()){
			Icreader co = (Icreader)item.next();
			IcreaderVO cov = new IcreaderVO();
			
			BeanUtils.copyProperties(cov, co);
			list.add(cov);
		}
		HibernateSessionFactory.closeSession();
		return list;
	}
	public void saveIcreader(IcreaderVO cov) throws IllegalAccessException, InvocationTargetException{
		IcreaderDAO con = new IcreaderDAO();
		Icreader co = new Icreader();
		BeanUtils.copyProperties(co, cov);
		con.save(co);
	}
	public void deleteIcreader(Long cid){
		IcreaderDAO con = new IcreaderDAO();
		Icreader co = new Icreader();
		co.setId(cid);
		con.delete(co);
	}
	public void editIcreader(IcreaderVO cov) throws IllegalAccessException, InvocationTargetException{
		IcreaderDAO con = new IcreaderDAO();
		Icreader co = new Icreader();
		BeanUtils.copyProperties(co, cov);
		con.update(co);
	}
	public IcreaderVO getIcreaderByID(Long cid) throws IllegalAccessException, InvocationTargetException{
		IcreaderDAO con = new IcreaderDAO();
		Icreader co = con.findById(cid);
		IcreaderVO cov = new IcreaderVO();
		BeanUtils.copyProperties(cov, co);
		return cov;
	}

}

IcreaderDAO.java
package gate.dao;

import gate.model.Icreader;

import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class IcreaderDAO extends HibernateDaoSupport implements IIcreaderDAO {
	private static final Log log = LogFactory.getLog(IcreaderDAO.class);
	//property constants
	public static final String CARDNO = "cardno";
	public static final String ACCOUNTNO = "accountno";
	public static final String STUDENTCODE = "studentcode";
	public static final String NAME = "name";
	public static final String SEX = "sex";
	public static final String DEPTNO = "deptcode";
	public static final String TYPENO = "typeno";
	public static final String EXPIREDDATE = "expireddate";
	public static final String FLAG = "flag";

	public void save(Icreader transientInstance) {
		log.debug("saving Icreader instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(Icreader persistentInstance) {
		log.debug("deleting Icreader instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public void update(Icreader icreader) {
		log.debug("deleting Icreader instance");
		try {
			getHibernateTemplate().update(icreader);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public Icreader findById(java.lang.Long id) {
		log.debug("getting Icreader instance with id: " + id);
		try {
			Icreader instance = (Icreader) getHibernateTemplate().get(
					"com.hibernate.demo.Icreader", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(Icreader instance) {
		log.debug("finding Icreader instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {

		log.debug("finding Icreader instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from Icreader as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}

	}

	public List findByCardno(Object cardno) {
		return findByProperty(CARDNO, cardno);
	}

	public List findByAccountno(Object accountno) {
		return findByProperty(ACCOUNTNO, accountno);
	}

	public List findByStudentcode(Object studentcode) {
		return findByProperty(STUDENTCODE, studentcode);
	}

	public List findByName(Object name) {
		return findByProperty(NAME, name);
	}

	public List findBySex(Object sex) {
		return findByProperty(SEX, sex);
	}

	public List findByTypeno(Object typeno) {
		return findByProperty(TYPENO, typeno);
	}

	public List findByDeptno(Object deptno) {
		return findByProperty(DEPTNO, deptno);
	}

	public List findByExpireddate(Object expireddate) {
		return findByProperty(EXPIREDDATE, expireddate);
	}

	public List findByFlag(Object flag) {
		return findByProperty(FLAG, flag);
	}

	public List findAll() {
		log.debug("finding all Icreader instances");
		try {
			String queryString = "from Icreader";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}

	}

	public Icreader merge(Icreader detachedInstance) {
		log.debug("merging Icreader instance");
		try {
			Icreader result = (Icreader) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}

	}

	public void attachDirty(Icreader instance) {
		log.debug("attaching dirty Icreader instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(Icreader instance) {
		log.debug("attaching clean Icreader instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}
}


Test.java
package gate.dao;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext; 

import java.util.List; 

import gate.model.Admin;
import gate.dao.AdminDAO;

public class Test {
    public static void main(String args[]) {
        ApplicationContext ctx = new FileSystemXmlApplicationContext(
                "src/applicationContext.xml");//载入Spring框架应用程序上下文中的信息
        AdminDAO test = (AdminDAO) ctx.getBean("AdminDAO");//获取DAO
        try { 
            List list=(List)(test.findAll());
            for(int i=0;i<list.size();i++){
            	Admin f=(Admin)(list.get(i));
                System.out.println("i:"+f.getName());
            }
        } catch (Exception e) { 
            System.err.println(e);
        }
    } 

}




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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.microsoft.jdbc.sqlserver.SQLServerDriver" />
		<property name="url" value="jdbc:microsoft:sqlserver://xxx.xxx.xxx.xxx:1433" />
		<property name="username" value="xxxx" />
	</bean>
	
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" destroy-method="close">
		<property name="dataSource" ref="dataSource" />
		<property name="mappingResources">
			<list>
			<value>gate/model/Admin.hbm.xml</value>
			<value>gate/model/Icreader.hbm.xml</value>
			<value>gate/model/Loginlog.hbm.xml</value>
			<value>gate/model/Operator.hbm.xml</value>
			<value>gate/model/Oplog.hbm.xml</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">
					org.hibernate.dialect.SQLServerDialect
				</prop>
			</props>
		</property>
	</bean>

	<bean id="IcreaderDAO" class="gate.dao.IcreaderDAO">
       <property name="sessionFactory">
            <ref bean="sessionFactory" />
        </property>
    </bean>
    <bean id="OplogDAO" class="gate.dao.OplogDAO">
       <property name="sessionFactory">
            <ref bean="sessionFactory" />
        </property>
    </bean>
    <bean id="AdminDAO" class="gate.dao.AdminDAO">
       <property name="sessionFactory">
            <ref bean="sessionFactory" />
        </property>
    </bean>
    <bean id="OperatorDAO" class="gate.dao.OperatorDAO">
       <property name="sessionFactory">
            <ref bean="sessionFactory" />
        </property>
    </bean>
    <bean id="LoginlogDAO" class="gate.dao.LoginlogDAO">
       <property name="sessionFactory">
            <ref bean="sessionFactory" />
        </property>
    </bean>
</beans>


icreader-servlet.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>
	<!-- 视图 -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />	
		<property name="prefix" value="/WEB-INF/jsp/"/>
		<property name="suffix" value=".jsp"/>
	</bean>
	

	
	<!-- 控制器 -->
    <bean id="listicreader" class="gate.web.ListIcreaderControllor" />
    <bean id="addicreader" class="gate.web.AddIcreaderControllor" >
    	<property name="sessionForm" value="true" />
    	<property name="commandName" value="icreaderform" />
    	<property name="commandClass" value="gate.web.model.IcreaderForm" />
    	<property name="formView" value="addicreader" />
    	<property name="successView" value="list" />
  
    </bean>
    <bean id="editicreader" class="gate.web.EditIcreaderControllor" >
    	<property name="sessionForm" value="true" />
    	<property name="commandName" value="icreaderform1" />
    	<property name="commandClass" value="gate.web.model.IcreaderForm" />
    	<property name="formView" value="editicreader" />
    	<property name="successView" value="list" />
    </bean>    
    <bean id="deleteicreader" class="gate.web.DeleteIcreaderControllor" />
    <!-- url映射 -->
	<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
		<property name="mappings" > 
             <props> 
                 <prop key="/list">listicreader</prop> 
                 <prop key="/add">addicreader</prop>
                 <prop key="/edit">editicreader</prop> 
                 <prop key="/delete">deleteicreader</prop>
             </props> 
         </property> 
	</bean>
</beans>



ListIcreaderControllor
package gate.web;

import gate.service.IcreaderService;
import gate.service.VO.IcreaderVO;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class ListIcreaderControllor implements Controller {

	public ModelAndView handleRequest(HttpServletRequest arg0,
			HttpServletResponse arg1) throws Exception {
		IcreaderService c = new IcreaderService();
		Map<String, Object> myModel = new HashMap<String, Object>();
		List<IcreaderVO> l = c.findAllIcreader();
		myModel.put("icreaderlist", l);
		
		return new ModelAndView("list", "model", myModel);
	}

}


奇怪的是,在Test.java中测试findAll()就可以取到值,但在web下面访问就报NullPointerException异常.
16:11:05,921 ERROR IcreaderDAO:139 - find all failed
java.lang.NullPointerException
at gate.dao.IcreaderDAO.findAll(IcreaderDAO.java:137)
at gate.service.IcreaderService.findAllIcreader(IcreaderService.java:21)
at gate.web.ListIcreaderControllor.handleRequest(ListIcreaderControllor.java:22)
at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:875)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:809)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:571)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:501)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:96)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:833)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:639)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1285)
at java.lang.Thread.run(Unknown Source)
16:11:05,937 ERROR [icreader]:253 - Servlet.service() for servlet icreader threw exception
java.lang.NullPointerException
at gate.dao.IcreaderDAO.findAll(IcreaderDAO.java:137)
at gate.service.IcreaderService.findAllIcreader(IcreaderService.java:21)
at gate.web.ListIcreaderControllor.handleRequest(ListIcreaderControllor.java:22)
at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:48)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:875)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:809)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:571)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:501)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:96)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:833)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:639)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1285)
at java.lang.Thread.run(Unknown Source)
分享到:
评论

相关推荐

    spring3 mvc 注解action dao service 实例教程

    ### Spring 3 MVC 注解Action DAO Service 实例教程 #### 一、Spring 3 MVC 注解概述 Spring框架自诞生以来一直致力于为复杂的软件工程问题提供简洁且非侵入式的解决方案。随着版本的演进,Spring 2.0 引入了定制...

    ssh(structs,spring,hibernate)框架中的上传下载

     文件数据存储在Blob类型的FILE_CONTENT表字段上,在Spring中采用OracleLobHandler来处理Lob字段(包括Clob和Blob),由于在程序中不需要引用到oracle数据驱动程序的具体类且屏蔽了不同数据库处理Lob字段方法上的...

    spring mvc + jpa 集成实例(有带包)

    3. **Repository接口**:定义操作数据库的方法,Spring Data JPA会自动生成实现,例如`findAll()`、`save()`、`findById()`等。 4. **Service层**:业务逻辑处理,通常会注入Repository并调用其方法,对数据进行增删...

    springCloud.docx

    public List&lt;Dept&gt; findAll(); } ``` 这里使用了 MyBatis 的注解来映射 SQL 语句,实现了部门数据的基本 CRUD 操作。 **DeptService.java** ```java public interface DeptService { public boolean add(Dept ...

    DWR+JPA DWR直接访问SERVICE层,并直接处理DAO返回的BEAN.doc

    为了解决这个问题,我们需要在`web.xml`中配置Spring的`OpenEntityManagerInViewFilter`。这个过滤器保持EntityManager在请求生命周期内开放,使得懒加载(lazy-loading)能在DWR调用结束后仍然有效。 配置`...

    HibernateSpringStruts2整合开发中的一个分页显示方案.doc

    在这个特定的分页显示方案中,开发者使用了这三种技术来解决在大型数据集展示时的分页问题。 1. **DAO层**: DAO(Data Access Object)层负责与数据库的交互。在这个例子中,`MemberDao`接口定义了两个关键方法,...

    SpringMVC+JPA+Spring+maven框架搭建

    return userRepository.findAll(); } // 其他业务逻辑方法 } ``` 最后,在控制器层,如`UserController.java`,处理HTTP请求: ```java @RestController @RequestMapping("/users") public class ...

    分页dao+service.rar

    return myEntityRepository.findAll(pageable); } ``` 6. **前端展示**: 前端通常需要渲染分页导航,如“上一页”、“下一页”、页码等。通过HTTP请求,传递当前页和每页大小到后台,获取相应的分页数据。 7....

    SSM的整合案例

    在Service接口中定义方法,比如`findAll()`,然后在实现类中注入Mapper接口并调用相应的方法。 Controller层是接收HTTP请求并返回响应的部分。在这里,你可以创建一个处理GET请求的控制器方法,例如`@...

    SpringBoot+JPA

    在实际开发中,可能还需要考虑分页查询、条件查询、事务管理、异常处理等问题,这些都可以通过Spring Data JPA的扩展或Spring Boot的特性来轻松解决。此外,JPA还支持 Criteria 查询、Querydsl 等高级查询方式,...

    SpringBoot如何整合SpringDataJPA

    return deptRepository.findAll(); } } 六、总结 本文主要介绍了如何将SpringBoot与SpringDataJPA进行整合。我们首先添加了相关依赖,然后配置了数据源和JPA,接着创建了实体类和Repository,最后使用Repository...

    JEE与Spring Boot代码性能比较分析

    但当涉及到事务管理和数据库操作时,如`save()`和`findAll()`,Spring Boot的这种行为可能导致性能损失,因为它可能不遵循预设的事务隔离级别和传播属性。相比之下,JavaEE在调整这些设置后,能够更好地控制事务行为...

    springboot-jpa-demo202010211912.zip

    例如,`findAll()`表示查询所有,`findById(Long id)`表示根据ID查找等。 7. **复杂查询与自定义SQL** - 使用`@Query`注解编写原生的JPA或HQL(Hibernate Query Language)查询。 - 实现`...

    springboot利用jpa连接hibernate用法2

    - **读取(Read)**: 可以通过`findById()`获取单个实体,`findAll()`获取所有实体,或者使用自定义的JPA查询方法。 - **更新(Update)**: 修改实体属性后,调用`save()`方法,Hibernate会更新对应记录。 - **...

    mongotest.zip

    最后,我们可以通过 Spring 的依赖注入来使用这个 Repository,在 Service 或 Controller 类中进行实际的数据操作。例如,我们可以创建一个简单的 CRUD 控制器来展示如何使用这个 Repository: ```java import org....

    Springboot2 实现简单的增删改查

    在本文中,我们将深入探讨如何在Spring Boot 2框架中使用JDBC和MyBatis实现数据的简单增删改查操作。Spring Boot以其简洁的配置和快速开发特性,已经成为Java领域中非常流行的微服务框架。而MyBatis作为一款优秀的...

    datajpa代码生成.zip

    这些接口继承自SpringData JPA提供的基类,如JpaRepository或CrudRepository,从而提供了一套标准的方法,如findAll、findById、save、delete等。 3. **Service类生成**:这部分代码通常包含业务逻辑,自动生成的...

    SpringBoot与PageHelper的整合示例详解.docx

    - 物理分页:通过数据库的LIMIT或OFFSET实现分页查询,避免了内存中存储大量数据导致性能问题。 - 动态SQL支持:可以根据条件动态生成分页语句,灵活调整分页参数。 - 多种分页参数:支持多种方式设置分页参数,...

    visit-jugkl-20150813-springdata-repositories:该存储库包含我的Spring数据存储库的幻灯片和示例代码-2015年8月8日在JUG Kaiserslaitern进行的最佳实践演讲

    在Repository接口中,可以定义带有特定注解的方法,如`@Query`来执行自定义SQL,或者使用JPA的CRUD操作(创建、读取、更新、删除)和预定义的方法名,如`findAll()`、`findById()`等。 4. Spring Data JPA: 如果...

    SpringJPA

    - **基本查询**:通过Repository接口的默认方法实现增删改查操作,如`findAll()`, `findById()`, `save()`, `delete()`等。 - **自定义查询**:在Repository接口中定义自己的查询方法,方法名遵循特定的命名规则,...

Global site tag (gtag.js) - Google Analytics