I do not see any exception in this piece of code. It runs fine yet when it returns there is no data in the List I call. getAll in the session call. What could be the reason.
这里是我的会议呼吁。
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;
}
}
Now even if I change the @Table to point to a completely irrelevant table like htblUser which does not exist, I do not see any failures. Here is my config that ties in all the annotated code. mysql_persistence_info.xml
<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>
页: 1
<?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>
我 用户行长
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 = "/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 = "/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 = "/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 = "/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 = "/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";
}
这里是家房总经理,是网关的切入点。
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";
}
}
Thanks Dhiren