我一直在尝试使用Spring和Hibernate。目前我正在尝试让Hibernate自动创建表。根据我在网上找到的文档和示例,将hibernate.hbm2ddl.auto
设置为create
,create-drop
或update
可以实现这一点。由于某种原因,这是行不通的。下面是我宣布我的bean(在\WEB-INF\dispatcher-servlet.xml
中):
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/MY_SHOP" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<list>
<value>com.crimsonwing.dto.UserDTO</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
这就是我宣布我的DTO的方式:
@Entity
@Table(name = "USER", uniqueConstraints = @UniqueConstraint(columnNames = { "EMAIL", "UID" }))
public class UserDTO implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
// Validation Annotation
@Size(min = 8, max = 30, message = "User name must be between 8 and 30 characters long.")
// Database Anotation
@Column(name = "NAME", insertable = true, updatable = true, nullable = false)
private String name;
// Validation Annotation
@NumberFormat(style = Style.NUMBER)
@Min(1)
@Max(99)
// Database Anotation
@Column(name = "AGE", insertable = true, updatable = true, nullable = false)
private int age;
// Validation Annotation
@UniqueEmail
@Email(message = "Email is incorrect format.")
@NotEmpty(message = "Email cannot be left empty")
// Database Anotation
@Column(name = "EMAIL", insertable = true, updatable = true, nullable = false)
private String email;
// Database Anotation
@Id
@Column(name = "UID", insertable = false, updatable = false, nullable = false)
@GeneratedValue()
private String userUID;
public UserDTO(String name, int age, String email)
{
super();
this.name = name;
this.age = age;
this.email = email;
}
public UserDTO()
{
/* WILL BE USED BY HIBERNATE */
}
...
这就是我尝试访问数据库的方式:
@Repository
public class UserDAOImpl implements IUserDAO
{
@Resource
private HibernateTemplate hibernateTemplate;
@Override
public bbolean userExists(String userEmail)
{
UserDTO user = new UserDTO();
user.setEmail(userEmail);
DetachedCriteria detachedCriteria = DetachedCriteria.forClass(user.getClass());
return (this.hibernateTemplate.findByCriteria(detachedCriteria).size() > ) ? true : false;
}
...
任何人都可以指出我正确的方向吗?是否缺少设置或我做错了什么?我在带有spring 3.1和hibernate 3.6.10的Ubuntu x64平台上使用MySQL版本5.1.58-1ubuntu1
。
感谢。
编辑:为完整性添加了Stacktrace:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'MY_SHOP.USER' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3609)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2002)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2163)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2624)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2127)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2293)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1953)
at org.hibernate.loader.Loader.doQuery(Loader.java:802)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:274)
at org.hibernate.loader.Loader.doList(Loader.java:2542)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2276)
at org.hibernate.loader.Loader.list(Loader.java:2271)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:119)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1716)
at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:347)
at org.springframework.orm.hibernate3.HibernateTemplate$36.doInHibernate(HibernateTemplate.java:1056)
at org.springframework.orm.hibernate3.HibernateTemplate$36.doInHibernate(HibernateTemplate.java:1)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406)
at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
at org.springframework.orm.hibernate3.HibernateTemplate.findByCriteria(HibernateTemplate.java:1046)
at org.springframework.orm.hibernate3.HibernateTemplate.findByCriteria(HibernateTemplate.java:1039)
at com.crimsonwing.dao.impl.UserDAOImpl.userExists(UserDAOImpl.java:36)
at com.crimsonwing.service.impl.UserServiceImpl.userExists(UserServiceImpl.java:28)
at com.crimsonwing.facades.impl.UserFacadeImpl.userExists(UserFacadeImpl.java:34)
at com.crimsonwing.validator.uniqueemail.impl.UniqueEmailValidator.isValid(UniqueEmailValidator.java:26)
at com.crimsonwing.validator.uniqueemail.impl.UniqueEmailValidator.isValid(UniqueEmailValidator.java:1)
at org.hibernate.validator.engine.ConstraintTree.validateSingleConstraint(ConstraintTree.java:278)
at org.hibernate.validator.engine.ConstraintTree.validateConstraints(ConstraintTree.java:153)
at org.hibernate.validator.engine.ConstraintTree.validateConstraints(ConstraintTree.java:117)
at org.hibernate.validator.metadata.MetaConstraint.validateConstraint(MetaConstraint.java:84)
at org.hibernate.validator.engine.ValidatorImpl.validateConstraint(ValidatorImpl.java:452)
at org.hibernate.validator.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:397)
at org.hibernate.validator.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:361)
at org.hibernate.validator.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:313)
at org.hibernate.validator.engine.ValidatorImpl.validate(ValidatorImpl.java:139)
at org.springframework.validation.beanvalidation.SpringValidatorAdapter.validate(SpringValidatorAdapter.java:101)
at org.springframework.validation.DataBinder.validate(DataBinder.java:722)
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.validateIfApplicable(ModelAttributeMethodProcessor.java:154)
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:107)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:74)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:155)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:117)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:900)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:827)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
编辑:
根据parasietje的建议,这是由此产生的HQL:
Hibernate: select this_.UID as UID2_0_, this_.AGE as AGE2_0_, this_.EMAIL as EMAIL2_0_, this_.NAME as NAME2_0_ from USER this_
我没有得到任何其他HQL。如果我没记错的话,在创建表时,你也可以看到生成的HQL语句,这不是这种情况下发生的事情。
答案 0 :(得分:2)
架构MY_SHOP
是否真的存在,我的理解是Hibernate不会创建架构,它只会在现有架构下创建类。
因此,如果没有,请尝试创建模式,并尝试在表注释中添加模式。
@Entity
@Table(name = "USER", , schema="MY_SHOP", uniqueConstraints = @UniqueConstraint(columnNames = { "EMAIL", "UID" }))
public class UserDTO implements Serializable
{