我的项目有问题。当我浏览http://localhost:8080/user/form
以在直接http://localhost:8080/user/list
之后填写用户信息以显示列表用户时,会出现以下错误:
Hibernate:插入userdat(密码,生日,年龄,性别, 用户名)值s(?,?,?,?,?)2016年3月25日上午5:05:04 org.hibernate.engine.jdbc.spi.SqlExceptionHelper $ STANDAR dWarningHandler logWarning WARN:SQL警告代码:10000,SQLState: 01J01 2016年3月25日上午5:05:04 org.hibernate.engine.jdbc.spi.SqlExceptionHelper $ STANDAR dWarningHandler logWarning警告:数据库'D:\ PROJECTSPRING \ userdb' 没有创建,连接使得存在于数据库中。 3月25日, 2016年5:05:04 AM org.hibernate.hql.internal.QueryTranslatorFactoryInitiat或 initiateService INFO:HHH000397:使用ASTQueryTranslatorFactory Hibernate:选择user0_.username作为username1_0_,user0_.password as password2_ 0_,user0_.birthday as birthday3_0_,user0_.age as age4_0_, user0_.gender as gen der5_0_ from userdat user0_ Mar 25,2016 5:05:04 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExce ptions 警告:SQL错误:20000,SQLState:22005 2016年3月25日上午5:05:04 org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExce ptions ERROR: 尝试从数据中获取类型为'byte []'的数据值 'VARCHAR'类型的值。 [警告] org.springframework.web.util.NestedServletException:Request 处理失败;嵌套异常是 org.hibernate.exception.DataException:无法执行que ry 在org.springframework.web.servlet.FrameworkServlet.processRequest(Frame workServlet.java:973) 在org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServl) et.java:852) 在javax.servlet.http.HttpServlet.service(HttpServlet.java:687) 在org.springframework.web.servlet.FrameworkServlet.service(FrameworkSer
此处归档CustomContextLoaderListener.java
public class CustomContextLoaderListener extends ContextLoaderListener{
@Override
public void contextDestroyed(ServletContextEvent event) {
// TODO Auto-generated method stub
System.out.println("hibernate shutdown database");
try {
DriverManager.getConnection("jdbc:derby:D:/PROJECTSPRING/userdb;shutdown=true");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("\n Spring-MVC application destroyed \n");
super.contextDestroyed(event);
}
@Override
public void contextInitialized(ServletContextEvent event) {
// TODO Auto-generated method stub
System.out.println("\n Spring-MVC application inited \n");
try {
createTable();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.contextInitialized(event);
}
public void createTable() throws SQLException{
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
Connection connection = DriverManager.getConnection("jdbc:derby:D:/PROJECTSPRING/userdb;create=true");
createTableNotExist(connection,"userdat", "create table userdat"
+ "(username varchar(1000) primary key,"
+ "password varchar(1000),birthday date,"
+ "age integer,gender varchar(100))");
// createTableNotExist(connection,"subject","create table subject"
// + "(id bigint primary key generated always as identity(start with 1,increment by 1),"
// + "title varchar(1000),student integer,score integer)" );
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void createTableNotExist(Connection connection,
String tableName,String createTableSQL) throws SQLException{
DatabaseMetaData dbmd = connection.getMetaData();
ResultSet rs = dbmd.getTables(null, null,tableName.toUpperCase(), null);
if (rs.next()){
System.out.println("Table" + rs.getString("TABLE_NAME") + "already exists");
return;
}
System.out.println("anh yeu em");
Statement statement = connection.createStatement();
statement.execute(createTableSQL);
System.out.println("\n\n executed" + createTableSQL + "\n\n");
statement.close();
}
}
此处归档UserRestServiceController.java
@Controller
public class UserRestServiceController {
@Autowired
private UserDao userDao;
@Autowired
private View jsonView;
@RequestMapping(value="/user/form",method = RequestMethod.GET)
public ModelAndView user() {
// System.out.println("anh yeu em ");
ModelAndView model = new ModelAndView("UserForm", "User", new User());
model.addObject("allgender", Gender.values());
return model;
}
@RequestMapping(value="/user/save", method = RequestMethod.POST)
public ModelAndView saveUser(@ModelAttribute("User") User user,BindingResult result){
ModelAndView model = new ModelAndView();
System.out.println("anh yeu em ");
if (result.hasErrors()){
model = new ModelAndView("UserForm","User",user);
model.addObject("errors",result);
return model;
}
userDao.save(user);
model = new ModelAndView("redirect:/user/list");
return model;
}
@RequestMapping(value="/user/list",method = RequestMethod.GET)
public ModelAndView listUser(){
ModelAndView model = new ModelAndView();
List<User> listUser = userDao.listUsers();
model = new ModelAndView("UserList","Users",listUser);
return model;
}
@RequestMapping(value="/user/json/{username}")
public ModelAndView loadUser(@PathVariable("username")String name){
return new ModelAndView(jsonView,"data",userDao.loadUser(name));
}
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
}
此处归档UserDaoImpl.java
@Repository
public class UserDaoImpl implements UserDao{
@Autowired
public LocalSessionFactoryBean sessionFactory;
@Override
public void save(User user) {
// TODO Auto-generated method stub
Session session = sessionFactory.getObject().openSession();
session.save(user);
session.flush();
session.close();
}
@Override
public void update(User user) {
// TODO Auto-generated method stub
}
@Override
public List<User> listUsers() {
// TODO Auto-generated method stub
Session session = sessionFactory.getObject().openSession();
Query query = session.createQuery("from User");
return (List<User>)query.list();
}
@Override
public void delete(User user) {
// TODO Auto-generated method stub
Session session = sessionFactory.getObject().openSession();
session.delete(user);
}
@Override
public User loadUser(String username) {
// TODO Auto-generated method stub
Session session = sessionFactory.getObject().openSession();
Query query = session.createQuery("from User "
+ "where username = :user_name");
query.setParameter("user_name",username);
return (User) query.uniqueResult();
}
}
此处归档User.java
@Entity
//@Table(name = "user",uniqueConstraints={@UniqueConstraint(columnNames="username")})
public class User {
// @Column(name = "gender", nullable = false)
// @Enumerated(EnumType.STRING)
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// @Column(name = "username", unique = true, nullable = false)
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
// @Column(name = "password", nullable = false)
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
// @Column(name = "birthday", nullable = false)
public Date getBirthDay() {
return birthDay;
}
public void setBirthDay(Date birthDay) {
this.birthDay = birthDay;
}
// @Column(name="age", nullable = false)
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
private String userName;
private String passWord;
private Date birthDay;
private Integer age;
private Gender gender;
}
此处提交Gender.java文件
public enum Gender {
MALE("Male"),
FEMALE("Female"),
OTHER("Other");
private String name;
private Gender(String name) {
this.name = name;
}
public String getGender(){
return this.name;
}
此处归档User.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="edu.java.spring.service.user.model.User" table="userdat">
<id name="userName" column="username"/>
<property name="passWord" column="password"/>
<property name="birthDay" column="birthday"/>
<property name="age" column="age"/>
<property name="gender" column="gender" />
</class>
</hibernate-mapping>
答案 0 :(得分:1)
当您使用Hibernate编写select语句时,您可以在HQL中编写它,但不能在SQL中编写。它们之间的主要区别之一是,在HQL中,您编写类名和字段名,在sql中您将使用表名和列名。
您的实体的类名可能是User
,而表名是userdat
。因此,正确的HQL语句将是:from User
(大写U!)而不是from userdat
@Override
public List<User> listUsers() {
// TODO Auto-generated method stub
Session session = sessionFactory.getObject().openSession();
Query query = session.createQuery("from User");
return (List<User>)query.list();
}
顺便说一下public User loadUser(String username)
根据您修改过的问题 (顺便说一下。如果此修改改变了问题的性质,下次再提出新问题而不是更改旧问题)
首先让我说,我想知道现在有人仍然使用hbm.xml文件而不是注释,但也许你有一些很好的理由。 ...
当我将hbm.xml与(注释掉的)注释进行比较时,只有一件事可能会导致像你一样的问题:它是枚举。在注释中,枚举通过其名称(字符串/ varchar)进行映射,但在hbm.xml中,它通过其序数(整数)进行映射。所以试试吧。检查用于枚举的列是否为整数列,如果不是则为1。如果您可以/不想更改列类型,则需要更改映射。根据谷歌的一些研究,通过xml通过名称映射枚举很奇怪:(重要的是12
,它是varchar的内部表示!)
<property name="gender" length="30">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">full.qualifiey.name.for.Gender</param>
<param name="type">12</param>
</type>
</property>
答案 1 :(得分:1)