Я пытался использовать Spring и Hibernate вместе. На данный момент я пытаюсь заставить Hibernate создавать таблицы автоматически. Согласно документации и примерам, которые я нашел в Интернете, этого можно достичь, установив hibernate.hbm2ddl.auto
в create
, create-drop
или update
. По какой-то причине это не работает. Ниже, где я объявляю свои бобы (в \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;
}
...
Кто-нибудь может указать мне правильное направление? Есть пропущенная настройка или я что-то не так сделал? Я использую версию MySQL 5.1.58-1ubuntu1
на платформе Ubuntu x64 с пружиной 3.1 и hibernate 3.6.10.
Спасибо.
РЕДАКТИРОВАТЬ: 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)
Edit:
Согласно предложению 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, чего не происходит в этом случае.