在spring mvc中我想用hibernate将数据保存到mysql数据库中,并且想要通过电子邮件获取数据。
在我的数据库中,我有表users表和字段: - (id(bigint),name(varchar),username(varchar),password(varchar))
我有控制器:
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String signup(@Valid @ModelAttribute("user") User user,HttpServletRequest request,
HttpServletResponse response,BindingResult result) {
userService.addUser(user.getName(),user.getUsername(),user.getEmail(),user.getPassword());
java.util.List<User> user1== userService.getUserinfo(user.getEmail());
userService.display(user1);
}
UserDao.java是:
public interface UserDao {
public void saveUser ( User user );
public List<User> getUserinfo(String email);
}
UserDaoImpl是:
@Transactional
@Repository("userDao")
public class UserDaoImpl implements UserDao {
public void saveUser(User user) {
sessionFactory.getCurrentSession().save(user);
}
public List<User> getUserinfo(String email) {
String hql = "select * from users where email = :email";
List<User> users = new ArrayList<User>();
users = (List<User>) sessionFactory.getCurrentSession().createSQLQuery(hql)
.setParameter("email", email).uniqueResult();
return users;
}
}
UserService.java是:
public interface UserService {
User addUser(String name, String username, String email, String password);
public List<User> getUserinfo(String email);
}
UserServiceImpl是:
public class UserServiceImpl implements UserService {
@Transactional(propagation = Propagation.REQUIRED)
public User addUser(String name, String username, String email, String password) {
User user = new User(name,username, email,password);
userDao.saveUser(user);
return user;
}
public List<User> getUserinfo(String email) {
return userDao.getUserinfo(email);
}
}
User.java是:
@Entity
@Table(name = "users")
public class User {
@Column(name = "id")
private long userId;
@Column(name = "name")
private String Name;
@Column(name = "username")
private String username;
@Column(name = "email")
private String email;
@Column(name = "password")
private String password;
//constructors
//setters and getters
}
数据存储在数据库中,但是当我获取时 错误显示为:
com.news.User cannot be cast to java.util.List
答案 0 :(得分:1)
问题在于:
sessionFactory.getCurrentSession().get(User.class, email);
此get
需要一个类名和一个“ID”(在您的情况下,用户ID为Long
)。您可能应该使用some kind of request通过电子邮件查找用户。
答案 1 :(得分:1)
异常的消息非常明确。 User类的ID是Long类型,您通过将其电子邮件作为String类型的参数传递来尝试通过ID获取User。那可能无法奏效。
如果您的目标是通过电子邮件查找用户,则需要查询,例如
select u from User u where u.email = :email
答案 2 :(得分:0)
摘录
sessionFactory.getCurrentSession().createSQLQuery(hql).setParameter("email", email).uniqueResult();
返回一个对象。 (https://docs.jboss.org/hibernate/orm/3.2/api/org/hibernate/Query.html#uniqueResult())
您应该将其更改为
User user = (User)sessionFactory.getCurrentSession().createSQLQuery(hql)
.setParameter("email", email).uniqueResult();
此外,在获取单个用户的信息之后,是否必须将方法的返回类型更改为User。你不需要那里的名单