2011-11-02 2 views
1

이 코드에서는 예외가 표시되지 않습니다. 그것은 잘 실행 아직 내가 전화 목록에 데이터가 반환됩니다. 세션 호출에서 getAll. 이유가 무엇 일 수 있습니다.최대 절전 모드 목록이 비어 있거나 null입니다. 이유는 무엇입니까?

여기 내 세션 통화입니다.

import java.util.List; 

import javax.annotation.Resource; 

import org.apache.log4j.Logger; 
import org.hibernate.Query; 
import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Service; 
import org.springframework.transaction.annotation.Transactional; 
import apps.user.User; 

/** 
* Service for processing Users 
* 
*/ 
@Service("userService") 
@Transactional 
public class UserService { 

protected static Logger logger = Logger.getLogger("service"); 

@Autowired 
@Resource(name="sessionFactory") 
private SessionFactory sessionFactory; 

/** 
    * Retrieves all Users 
    * 
    * @return a list of Users 
    */ 
public List<User> getAll() { 
    logger.debug("Retrieving all Users"); 

    // Retrieve session from Hibernate 
    Session session = sessionFactory.getCurrentSession(); 

    // Create a Hibernate query (HQL) 
    //createQuery("from springapp.domain.Product"); 
    List<User> list= (List<User>) session.createCriteria(User.class).list(); 
    //session.createQuery(" FROM User"); 

    // Retrieve all 
    return list; 
} 

/** 
    * Retrieves a single User 
    */ 
public User get(Integer id) { 
    // Retrieve session from Hibernate 
    Session session = sessionFactory.getCurrentSession(); 

    // Retrieve existing User first 
    User User = (User) session.get(User.class, id); 

    return User; 
} 
/** 
    * Adds a new User 
    */ 
public void add(User User) { 
    logger.debug("Adding new User"); 

    // Retrieve session from Hibernate 
    Session session = sessionFactory.getCurrentSession(); 

    // Save 
    session.save(User); 
} 

/** 
    * Deletes an existing User 
    * @param id the id of the existing User 
    */ 
public void delete(Integer id) { 
    logger.debug("Deleting existing User"); 

    // Retrieve session from Hibernate 
    Session session = sessionFactory.getCurrentSession(); 

    // Retrieve existing User first 
    User User = (User) session.get(User.class, id); 

    // Delete 
    session.delete(User); 
} 

/** 
    * Edits an existing User 
    */ 
public void edit(User User) { 
    logger.debug("Editing existing User"); 

    // Retrieve session from Hibernate 
    Session session = sessionFactory.getCurrentSession(); 

    // Retrieve existing User via id 
    User existingUser = (User) session.get(User.class, User.getUserId()); 

    // Assign updated values to this User 
    existingUser.setFirstName(User.getFirstName()); 
    existingUser.setLastName(existingUser.getLastName()); 
    existingUser.setPassword(existingUser.getPassword()); 

    // Save updates 
    session.save(existingUser); 
} 

여기에 사용자 코드가 있습니다.

import java.io.Serializable; 
import java.sql.Date; 

import javax.persistence.Entity; 
import javax.persistence.GeneratedValue; 
import javax.persistence.Id; 
import javax.persistence.Table; 
import javax.persistence.Column; 
import javax.persistence.GenerationType; 
import javax.validation.constraints.Size; 

import org.hibernate.validator.constraints.NotEmpty; 
import org.springframework.beans.factory.annotation.Autowired; 
/** 
* For a complete reference see 
* <a href="http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/"> 
* Hibernate Annotations Communit Documentations</a> 
*/ 
@Entity 
@Table(name = "tblUser") 
public class User implements Serializable { 

    public User(){ 
    String s=null; 
    } 

    @Column(name = "password") 
private String password; 
    @Column(name = "firstName") 
private String firstName; 
    @Column(name = "middleName") 
private String middleName; 
    @Column(name = "lastName") 
private String lastName; 
    @Column(name = "emailAddress") 
private String emailAddress; 

/** 
    * @return the emailAddress 
    */ 
    public String getEmailAddress() { 
     return emailAddress; 
    } 
    /** 
    * @param emailAddress the emailAddress to set 
    */ 
    public void setEmailAddress(String emailAddress) { 
     this.emailAddress = emailAddress; 
    } 

    /** 
    * @param lastLoginDate the lastLoginDate to set 
    */ 
@Id 
@NotEmpty 
@Column(name="userId") 
private String userId; 

//private int userAccessLevel; 
/** 
* @return the userId 
* 
public String getUserId() { 
    return userId; 
} 
** 
* @param userId the userId to set 
* 
public void setUserId(String userId) { 
    this.userId = userId; 
} 
/** 
* @return the password 
*/ 
public String getPassword() { 
    return password; 
} 
/** 
* @param password the password to set 
*/ 
public void setPassword(String password) { 
    this.password = password; 
} 
/** 
* @return the firstName 
*/ 
public String getFirstName() { 
    return firstName; 
} 
/** 
* @param firstName the firstName to set 
*/ 
public void setFirstName(String firstName) { 
    this.firstName = firstName; 
} 
/** 
* @return the middleName 
*/ 
public String getMiddleName() { 
    return middleName; 
} 
/** 
* @param middleName the middleName to set 
*/ 
public void setMiddleName(String middleName) { 
    this.middleName = middleName; 
} 
/** 
* @return the lastName 
*/ 
public String getLastName() { 
    return lastName; 
} 
/** 
* @param lastName the lastName to set 
*/ 
public void setLastName(String lastName) { 
    this.lastName = lastName; 
} 
/** 
* @return the userAccessLevel 
* 
public int getUserAccessLevel() { 
    return userAccessLevel; 
} 
*/ 
/** 
* @param userAccessLevel the userAccessLevel to set 
* 
public void setUserAccessLevel(int userAccessLevel) { 
    this.userAccessLevel = userAccessLevel; 
}*/ 
public void setUserId(String userId) { 
    this.userId = userId; 
} 
public String getUserId() { 
    return userId; 
} 

} 

은 지금은 존재하지 않는 htblUser 같은 완전히 관련이없는 테이블을 가리 키도록 @Table을 변경하는 경우에도, 나는 어떤 오류가 표시되지 않습니다. 주석이 달린 모든 코드를 연결하는 구성입니다. 여기
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:p="http://www.springframework.org/schema/p" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
     xmlns:context="http://www.springframework.org/schema/context" 
     xsi:schemaLocation=" 
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd 
    "> 
<!-- Load Hibernate related configuration --> 

<tx:annotation-driven transaction-manager="transactionManager" /> 
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 
    destroy-method="close" 
    p:url="jdbc:mysql://localhost/TestDb" 
    p:driverClassName="com.mysql.jdbc.Driver" 
    p:username="root" 
    p:password="******" 
    p:initialSize="1" 
    p:maxActive="5" 

    /> 
    <bean id="sessionFactory" 
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" 

    p:configLocation="/WEB-INF/spring/appServlet/hibernate-cfg.xml"> 
    <property name="dataSource" ref="dataSource" /> 
     <property name="annotatedClasses"> 
      <list> 
       <value>apps.user.User</value> 
      </list> 
     </property> 
    </bean> 



<!-- Declare a transaction manager--> 
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" 
      p:sessionFactory-ref="sessionFactory" />  
    </beans> 

mysql_persistence_info.xml

여기 apoconfigg.xml

<?xml version="1.0" encoding="UTF-8"?> 
<beans:beans xmlns="http://www.springframework.org/schema/mvc" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:beans="http://www.springframework.org/schema/beans" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 

    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure --> 

    <!-- Enables the Spring MVC @Controller programming model --> 
    <annotation-driven /> 
    <!-- Activates various annotations to be detected in bean classes --> 
    <context:annotation-config /> 
    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory --> 
    <resources mapping="/resources/**" location="/resources/" /> 

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --> 
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
     <beans:property name="prefix" value="/WEB-INF/views/" /> 
     <beans:property name="suffix" value=".jsp" /> 
    </beans:bean> 

     <!-- Imports user-defined @Controller beans that process client requests --> 

    <context:component-scan base-package="apps" /> 

    <beans:import resource="mysql_persistence_info.xml" /> 
</beans:beans> 

내 UserLoginController.java

import java.util.Iterator; 
import java.util.List; 

import javax.annotation.Resource; 
import javax.validation.Valid; 

import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Controller; 
import org.springframework.ui.Model; 
import org.springframework.ui.ModelMap; 
import org.springframework.validation.BindingResult; 
import org.springframework.web.bind.annotation.ModelAttribute; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.RequestParam; 
import org.springframework.web.bind.annotation.SessionAttributes; 
import apps.services.UserService; 
import apps.user.User; 

@Controller 
@SessionAttributes 

    //@RequestMapping() 
    public class UserLoginController { 
    @Resource(name="userService") 
    @Autowired 
    private UserService userService; 
    protected static Logger logger = null;//Logger.getLogger("controller"); 
    public UserLoginController(){ 

    } 

    /** 
     * Handles and retrieves all users and show it in a JSP page 
     * 
     * @return the name of the JSP page 
     */ 
     @RequestMapping(value = "/users", method = RequestMethod.GET) 
     public String getUsers(Model model) { 

     logger.debug("Received request to show all users"); 

     // Retrieve all users by delegating the call to UserService 
     List<User> users = userService.getAll(); 

     // Attach users to the Model 
     model.addAttribute("users", users); 

     // This will resolve to /WEB-INF/jsp/userspage.jsp 
     return "userspage"; 
    } 

     /** 
     * Retrieves the add page 
     * 
     * @return the name of the JSP page 
     */ 
     @RequestMapping(value = "https://stackoverflow.com/users/add", method = RequestMethod.GET) 
     public String getAdd(Model model) { 
     logger.debug("Received request to show add page"); 

     // Create new User and add to model 
     // This is the formBackingOBject 
     model.addAttribute("userAttribute", new User()); 

     // This will resolve to /WEB-INF/jsp/addpage.jsp 
     return "addpage"; 
    } 

     /** 
     * Adds a new user by delegating the processing to UserService. 
     * Displays a confirmation JSP page 
     * 
     * @return the name of the JSP page 
     */ 
     @RequestMapping(value = "https://stackoverflow.com/users/add", method = RequestMethod.POST) 
     public String add(@ModelAttribute("userAttribute") User user) { 
     logger.debug("Received request to add new user"); 

     // The "userAttribute" model has been passed to the controller from the JSP 
     // We use the name "userAttribute" because the JSP uses that name 

     // Call UserService to do the actual adding 
     userService.add(user); 

     // This will resolve to /WEB-INF/jsp/addedpage.jsp 
     return "addedpage"; 
    } 

     /** 
     * Deletes an existing user by delegating the processing to UserService. 
     * Displays a confirmation JSP page 
     * 
     * @return the name of the JSP page 
     */ 
     @RequestMapping(value = "https://stackoverflow.com/users/delete", method = RequestMethod.GET) 
     public String delete(@RequestParam(value="id", required=true) Integer id, 
        Model model) { 

     logger.debug("Received request to delete existing user"); 

     // Call UserService to do the actual deleting 
     userService.delete(id); 

     // Add id reference to Model 
     model.addAttribute("id", id); 

     // This will resolve to /WEB-INF/jsp/deletedpage.jsp 
     return "deletedpage"; 
    } 

     /** 
     * Retrieves the edit page 
     * 
     * @return the name of the JSP page 
     */ 
     @RequestMapping(value = "https://stackoverflow.com/users/edit", method = RequestMethod.GET) 
     public String getEdit(@RequestParam(value="id", required=true) Integer id, 
        Model model) { 
     logger.debug("Received request to show edit page"); 

     // Retrieve existing User and add to model 
     // This is the formBackingOBject 
     model.addAttribute("userAttribute", userService.get(id)); 

     // This will resolve to /WEB-INF/jsp/editpage.jsp 
     return "editpage"; 
    } 

     /** 
     * Edits an existing user by delegating the processing to UserService. 
     * Displays a confirmation JSP page 
     * 
     * @return the name of the JSP page 
     */ 
     @RequestMapping(value = "https://stackoverflow.com/users/edit", method = RequestMethod.POST) 
     public String saveEdit(@ModelAttribute("userAttribute") User user, 
        @RequestParam(value="id", required=true) String id, 
        Model model) { 

     logger.debug("Received request to update user"); 

     // The "userAttribute" model has been passed to the controller from the JSP 
     // We use the name "userAttribute" because the JSP uses that name 

     // We manually assign the id because we disabled it in the JSP page 
     // When a field is disabled it will not be included in the ModelAttribute 
     user.setUserId(id); 

     // Delegate to UserService for editing 
     userService.edit(user); 

     // Add id reference to Model 
     model.addAttribute("id", id); 

     // This will resolve to /WEB-INF/jsp/editedpage.jsp 
     return "editedpage"; 
    } 


    @RequestMapping("/account") 
    // public String updateAccount (
      public String processupdate(@ModelAttribute("user") User user, 
    BindingResult result, Model model){ 

       // @ModelAttribute("userLogin") User userLogin, 
//    Model model) { 

      // use fooService to save the changes contained <span class="searchterm4">in</span> the foo object 
      //fooService.saveFoo(foo); 
     System.out.println("inside here /account .."); 

     //model.addAttribute("userAdminLogin", userLogin); 
     return "home"; 
     } 

     @RequestMapping(value="/home" , method = RequestMethod.GET) 
    //@ModelAttribute("user") 
     public String process(@ModelAttribute("user") User user, 
    BindingResult result, Model model){ 
     // public String get(final ModelMap model) { 
      System.out.println("inside here get returning model .."); 
      List<User> users = userService.getAll(); 
       User userObj= null; 
      // Attach users to the Model 
      //model.addAttribute("users", users); 
      Iterator<User> iterate= users.iterator(); 
      while(iterate.hasNext()) { 
       userObj=iterate.next(); 
       if (userObj.getUserId().equals("dhirenjoshi")){ 
        break; 
       } 

      } 

     model.addAttribute("user", userObj); 
     return "home"; 
     } 

     @RequestMapping(method = RequestMethod.POST) 
     //final User user, final BindingResult result, 
     public String processSubmit(@ModelAttribute("user") User user, 
    BindingResult result, Model model){ 
     //public String post(Model mv) { 

      String test=" inside here"; 

      return "success"; 
     } 

는 여기에 웹 응용 프로그램의 진입 점입니다 HomePageController이다.

import java.text.DateFormat; 
import java.util.Date; 
import java.util.Locale; 

import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.stereotype.Controller; 
import org.springframework.ui.Model; 
import org.springframework.web.bind.annotation.ModelAttribute; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 

/** 
* Handles requests for the application home page. 
*/ 
@Controller 
public class HomeController { 

    private static final Logger logger = LoggerFactory.getLogger(HomeController.class); 

    /** 
    * Simply selects the home view to render by returning its name. 
    */ 
    @RequestMapping(value="/", method=RequestMethod.GET) 
    public String home(Locale locale, Model model) { 
     logger.info("Welcome home! the client locale is "+ locale.toString()); 

     Date date = new Date(); 
     DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale); 

     String formattedDate = dateFormat.format(date); 

     model.addAttribute("serverTime", formattedDate); 
     model.addAttribute("today", formattedDate); 
     return "home"; 
    } 


} 

덕분에 디렌

+1

DB를 확인 했습니까? 테이블에 데이터가 있습니까? – ManuPK

+0

예 해당 테이블에 사용할 수있는 데이터가 있습니다. 흥미롭게도 사용자 객체의 @Table의 이름을 변경하면 실패하지 않으므로 해당 테이블로 이동하는 것입니다. 내 추가 사용자 코드를 참조하십시오. – djoshi

+0

nativeSQL과 HQL을 사용해보고 거기서 얻은 것을 확인하십시오. – ManuPK

답변

3

내가 문제를 발견했다 생각합니다.

체크하여 hibernate-cfg.xml가이 로 설정되어있는 경우 갱신 변화를 만들어 하나 개의 속성 hbm2ddl.auto있을 것입니다.

<property name="hbm2ddl.auto">update</property>

이 설정 here에 대해 자세히 알아보십시오.

+0

마누가 마침내 성공했습니다. 너는 옳다. 나는 이것을 가지고있다. 을 만듭니다. 이제 업데이트로 변경하면이 웹 사이트를 사용하여 테이블에 새 사용자 엔터티를 추가 할 수 없다는 뜻입니까? – djoshi

+0

** create **는 쿼리가 실행될 때마다 테이블을 생성한다는 것을 의미합니다. 따라서 처음으로 ** 업데이트 **가되어야합니다. – ManuPK