2014-12-04 4 views
0

최대 절전 모드와 스프링을 배우려고합니다. 가장 먼저하고 싶은 것은 Hibernate를 사용하여 데이터베이스로부터 데이터를 얻는 것이다.최대 절전 모드를 사용하여 데이터베이스에서 모든 데이터를 가져올 수 없습니다.

데이터베이스에서 모든 데이터를 가져 오려고하지만 null 포인터 예외가 발생합니다.

내 코드는 다음과 같습니다. (com.hopyar.dao 패키지 아래)

City.java

@Entity 
@Table(name = "Cities") 
public class City implements Serializable{ 

    private static final long serialVersionUID = 2637311781100429929L; 

    @Id 
    @GeneratedValue 
    @Column(name = "c_id") 
    int id; 

    @Column(name = "c_name") 
    String name; 

    public int getId() { 
     return id; 
    } 

    public void setId(int id) { 
     this.id = id; 
    } 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 
} 

CityService.java

@Service 
public class CityService { 

    @PersistenceContext 
    private EntityManager em; 

    @Transactional 
    public List<City> getAllCities(){ 
     List<City> result = em.createQuery("Select c From Cities c", City.class) 
       .getResultList(); // This is where I get the exeption. 
     System.out.println(); 
     return result; 
    } 
} 

스프링의 context.xml (com.hopyar.service 패키지 아래) (웹 애플리케이션 아래/WEB-INF) com.hopyar.test 패키지 아래

<?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" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd 
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> 

    <!-- Enable annotation-based Spring MVC controllers (eg: @Controller annotation) --> 
    <mvc:annotation-driven/> 

    <!-- Classpath scanning of @Component, @Service, etc annotated class --> 
    <context:component-scan base-package="com.hopyar" /> 

    <!-- Resolve view name into jsp file located on /WEB-INF --> 
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
    <property name="prefix" value="/WEB-INF/" /> 
    <property name="suffix" value=".jsp" /> 
    </bean> 

    <!-- MySQL Datasource with Commons DBCP connection pooling --> 
    <bean class="org.apache.commons.dbcp.BasicDataSource" id="dataSource"> 
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/> 
    <property name="url" value="jdbc:mysql://localhost:3306/myproject"/> 
    <property name="username" value="username"/> 
    <property name="password" value="password"/> 
    </bean> 

    <!-- EntityManagerFactory --> 
    <bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory"> 
    <property name="persistenceUnitName" value="persistenceUnit"/> 
    <property name="dataSource" ref="dataSource"/> 
    </bean> 

    <!-- Transaction Manager --> 
    <bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager"> 
    <property name="entityManagerFactory" ref="entityManagerFactory"/> 
    </bean> 

    <!-- Enable @Transactional annotation --> 
    <tx:annotation-driven/> 

</beans> 

Main.java()

,
public class Main { 

    public static void main(String[] args) { 
     CityService service = new CityService(); 

     List<City> cities = service.getAllCities(); 

     System.out.println(cities.size()); 

    } 

} 
+0

는 "주"java.lang.NullPointerException이 스레드에서 – Pracede

+0

예외 스택 트레이스를하시기 바랍니다 붙여 넣기 com.hopyar.service.CityService.getAllCities (CityService.java:21) \t com.hopyar.test.Main.main에서에서 \t (Main.java:17) 그냥 아무것도 아니지만 – xxlali

+0

PersistenceContext 대신 Autowired를 시도하십시오. – Pracede

답변

3

servicenew CityService()으로 인스턴스화합니다. 이는 스프링을 우회하기 때문에 잘못되었습니다. 즉, 주석이 처리되지 않고 em이 null임을 의미합니다. 봄 컨텍스트에서 service을 가져와야합니다.

CityService service = applicationContext.getBean("cityService"); 
+0

또는 몇 가지 Spring 테스트 기능을 사용하여 JUnitTest를 생성하십시오. 이것은 당신을 위해 모든 것을 연결합니다. –

+0

나는 생각을 가지고있다. 도와 주셔서 감사합니다. – xxlali

+0

@xxlali 문제 없습니다. 도움이 되니 기쁩니다. –

1

CityService에서 자동 주 석을 사용하려고하면 Spring이이를 인스턴스화합니다.

관련 문제