【发布时间】:2015-11-01 02:36:41
【问题描述】:
我是数据库和服务器端编程的新手,事实上,这是我第一次这样做。我在 hsql 中的 schema.sql 定义为:
DROP TABLE User IF EXISTS;
DROP TABLE Favor IF EXISTS;
CREATE TABLE User (
userId BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1) NOT NULL,
username VARCHAR(100) NOT NULL,
password VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
mobile BIGINT NOT NULL,
PRIMARY KEY (userId)
);
CREATE TABLE Favor (
favorId BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1) NOT NULL,
favorName VARCHAR(100) NOT NULL,
favorDesc VARCHAR(1000) NOT NULL,
datePosted TIMESTAMP NOT NULL,
compensation VARCHAR(200) NOT NULL,
dateExpiring TIMESTAMP NOT NULL,
posterId BIGINT NOT NULL,
acceptorId BIGINT,
PRIMARY KEY (favorId),
FOREIGN KEY (posterId) REFERENCES User (userId),
FOREIGN KEY (acceptorId) REFERENCES User (userId)
);
我的控制器(UserController.java 和 FavorController.java)看起来像:
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(
value="/api/users",
method=RequestMethod.GET,
produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Collection<User>> getUsers() {
Collection<User> users = userService.findAll();
return new ResponseEntity<Collection<User>>(users, HttpStatus.OK);
}
@RequestMapping(
value="/api/users",
method=RequestMethod.POST,
consumes=MediaType.APPLICATION_JSON_VALUE,
produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<User> createUser(
@RequestBody User user) {
User savedUser = userService.create(user);
return new ResponseEntity<User>(savedUser, HttpStatus.CREATED);
}
}
Favor.java
@RestController
public class FavorController {
@Autowired
private FavorService favorService;
@RequestMapping(//denotes this is where http requests should go
value="/api/favors",
method=RequestMethod.GET,
produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Collection<Favor>> getFavors() {//responseentity-> converts it into JSON and inserts it into HTTP response body
Collection<Favor> favors = favorService.findAll();
return new ResponseEntity<Collection<Favor>>(favors, HttpStatus.OK);//status code of 200
}
@RequestMapping(
value="/api/favors/{id}",
method=RequestMethod.GET,
produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Favor> getFavor(@PathVariable("id") Long id) {
Favor favor = favorService.findOne(id);
if (favor == null)
return new ResponseEntity<Favor>(HttpStatus.NOT_FOUND);//status code of 404
return new ResponseEntity<Favor>(favor, HttpStatus.OK);
}
@RequestMapping(
value="/api/favors",
method=RequestMethod.POST,
consumes=MediaType.APPLICATION_JSON_VALUE,
produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Favor> createFavor(
@RequestBody Favor favor) {
Favor savedFavor = favorService.create(favor);
return new ResponseEntity<Favor>(savedFavor, HttpStatus.CREATED); //status code of 201
}
}
当我运行 springboot 应用程序并发出 POST 请求以添加 Favor 时,我在命令提示符(服务正在运行的位置)中得到以下内容。我说不出这是什么。有人可以帮帮我吗?
2015-08-09 00:40:42.127 INFO 10092 --- [nio-8080-exec-1] o.a.c.c.C.
[Tomcat].[lo
calhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2015-08-09 00:40:42.127 INFO 10092 --- [nio-8080-exec-1] o.s.web.servlet.Dispat
cherServlet : FrameworkServlet 'dispatcherServlet': initialization starte
d
2015-08-09 00:40:42.161 INFO 10092 --- [nio-8080-exec-1] o.s.web.servlet.Dispat
cherServlet : FrameworkServlet 'dispatcherServlet': initialization comple
ted in 33 ms
2015-08-09 00:40:42.424 WARN 10092 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.Sq
lExceptionHelper : SQL Error: -10, SQLState: 23502
2015-08-09 00:40:42.425 ERROR 10092 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.Sq
lExceptionHelper : integrity constraint violation: NOT NULL check constraint;
SYS_CT_10105 table: FAVOR column: FAVORNAME
2015-08-09 00:40:42.438 ERROR 10092 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dis
patcherServlet] : Servlet.service() for servlet [dispatcherServlet] in contex
t with path [] threw exception [Request processing failed; nested exception is o
rg.springframework.dao.DataIntegrityViolationException: could not execute statem
ent; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.C
onstraintViolationException: could not execute statement] with root cause
org.hsqldb.HsqlException: integrity constraint violation: NOT NULL check constra
int; SYS_CT_10105 table: FAVOR column: FAVORNAME
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.Table.enforceRowConstraints(Unknown Source)
at org.hsqldb.Table.insertSingleRow(Unknown Source)
at org.hsqldb.StatementDML.insertRowSet(Unknown Source)
at org.hsqldb.StatementInsert.getResult(Unknown Source)
at org.hsqldb.StatementDMQL.execute(Unknown Source)
at org.hsqldb.Session.executeCompiledStatement(Unknown Source)
at org.hsqldb.Session.execute(Unknown Source)
at org.hsqldb.jdbc.JDBCPreparedStatement.fetchResult(Unknown Source)
at org.hsqldb.jdbc.JDBCPreparedStatement.executeUpdate(Unknown Source)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(
ResultSetReturnImpl.java:208)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAn
dExtract(IdentityGenerator.java:96)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(Abstr
actReturningDelegate.java:58)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(Abstrac
tEntityPersister.java:3032)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(Abstrac
tEntityPersister.java:3558)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(Enti
tyIdentityInsertAction.java:98)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:492)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(Ac
tionQueue.java:197)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java
:181)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:216)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertActio
n(AbstractSaveEventListener.java:334)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrR
eplicate(AbstractSaveEventListener.java:289)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(Ab
stractSaveEventListener.java:195)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGenera
tedId(AbstractSaveEventListener.java:126)
at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWit
hGeneratedId(JpaPersistEventListener.java:84)
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTran
sient(DefaultPersistEventListener.java:206)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(De
faultPersistEventListener.java:149)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(De
faultPersistEventListener.java:75)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:811)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntit
yManagerImpl.java:1181)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEnti
tyManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:344)
at com.sun.proxy.$Proxy75.persist(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityMa
nagerInvocationHandler.invoke(SharedEntityManagerCreator.java:291)
at com.sun.proxy.$Proxy75.persist(Unknown Source)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.s
ave(SimpleJpaRepository.java:433)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.data.repository.core.support.RepositoryFactorySup
port$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.jav
a:436)
at org.springframework.data.repository.core.support.RepositoryFactorySup
port$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:421)
at org.springframework.data.repository.core.support.RepositoryFactorySup
port$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:393)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(
ReflectiveMethodInvocation.java:179)
at org.springframework.data.repository.core.support.RepositoryFactorySup
port$DefaultMethodInvokingMethodInterceptor.invoke(RepositoryFactorySupport.java
:506)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(
ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.
proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.
invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.in
voke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(
ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterc
eptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(
ReflectiveMethodInvocation.java:179)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPos
tProcessor$CrudMethodMetadataPopulatingMethodIntercceptor.invoke(CrudMethodMetad
ataPostProcessor.java:122)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(
ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invok
e(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(
ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynami
cAopProxy.java:207)
at com.sun.proxy.$Proxy77.save(Unknown Source)
at favorite.ws.service.FavorServiceBean.create(FavorServiceBean.java:34)
at favorite.ws.web.api.FavorController.createFavor(FavorController.java:
52)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvok
e(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeF
orRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocabl
eHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingH
andlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingH
andlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapt
er.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(Dispatch
erServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(Dispatche
rServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(Frame
workServlet.java:967)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServ
let.java:869)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkSer
vlet.java:843)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Appl
icationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationF
ilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52
)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Appl
icationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationF
ilterChain.java:206)
at favorite.ws.filters.SimpleCORSFilter.doFilter(SimpleCORSFilter.java:2
2)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Appl
icationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationF
ilterChain.java:206)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInterna
l(HiddenHttpMethodFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerR
equestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Appl
icationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationF
ilterChain.java:206)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterIntern
al(CharacterEncodingFilter.java:85)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerR
equestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Appl
icationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationF
ilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperV
alve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextV
alve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(Authentica
torBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.j
ava:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.j
ava:79)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineVal
ve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.jav
a:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp
11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(
AbstractProtocol.java:668)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpo
int.java:1521)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoin
t.java:1478)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.
java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor
.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskTh
read.java:61)
at java.lang.Thread.run(Thread.java:745)
在我的 Sencha Touch 前端: FavorsModel.js
Ext.define('FavorITe.model.FavorsModel', {
extend: 'Ext.data.Model',
requires: [
'Ext.DateExtras'
],
config: {
idProperty: 'favorId',
identifier: 'sequential',
fields: [
{ name: 'favorId', type: 'int' },
{ name: 'favorName', type: 'string' },
{ name: 'favorDesc', type: 'string' },
{ name: 'datePosted', type: 'date' },
{ name: 'compensation', type: 'string' },
{ name: 'dateExpiring', type: 'date' }
],
validations: [
{ type: 'presence', field: 'favorName', message: 'Favor\'s missing a name!' },
{ type: 'presence', field: 'favorDesc', message: 'Mind explaining the favor a little more?' },
{ type: 'presence', field: 'dateExpiring' }
],
},
checkDates: function (errors) {
if (this.get('datePosted') > this.get('dateExpiring')) {
errors.add(Ext.create('Ext.data.Error', {
field : 'dateExpiring',
message: 'Expiry date can\'t be before today\'s date!'
}));
}
},
validate: function () {
var errors = this.callParent(arguments);
this.checkDates(errors);
console.log(errors);
return errors;
}
});
我发出 AJAX 请求的控制器:
Ext.define('FavorITe.controller.RequestFavorForm', {
extend: 'Ext.app.Controller',
config: {
refs: {
cancelFavorButton: 'button[action=cancelFavor]',
submitFavorButton: 'button[action=submitFavor]',
requestFavorForm: 'requestFavorForm'
},
control: {
cancelFavorButton: {
tap: 'cancelRequestFavorForm'
},
submitFavorButton: {
tap: 'submitRequestFavorForm'
}
}
},
cancelRequestFavorForm: function() {
Ext.getCmp('start').animateActiveItem(0, {type: 'flip'});
},
submitRequestFavorForm: function() {
var requestFavorForm = this.getRequestFavorForm();
var currentFavor = requestFavorForm.getRecord();
var newValues = requestFavorForm.getValues();
currentFavor.set('favorName', newValues.favorName);
currentFavor.set('favorDesc', newValues.favorDesc);
currentFavor.set('compensation', newValues.compensation);
currentFavor.set('dateExpiring', newValues.dateExpiring);
currentFavor.set('datePosted', new Date());
var errors = currentFavor.validate();
if (!errors.isValid()) {
errors.each(function(item, index, length) {
Ext.Msg.alert('Wait!', errors.getByField(item.getField())[0].getMessage(), Ext.emptyFn);
});
currentFavor.reject();
return;
}
var allFavorsStore = Ext.getStore('AllFavorsStore');
console.log(currentFavor);
Ext.Ajax.request({
url: 'http://localhost:8080/api/favors',
method: 'POST',
jsonData: currentFavor,
success: function() {
console.log("success");
},
failure: function() {
console.log("wooops");
}
});
allFavorsStore.sync();
Ext.getCmp('start').animateActiveItem(0, {type: 'slide', direction: 'up'});
},
//called when the Application is launched, remove if not needed
launch: function(app) {
}
});
【问题讨论】:
-
您是如何发送请求的?我们能看到吗?您可能没有设置必须填充的字段。
-
@ACV:更新了我的帖子。请看。
-
您需要检查您的
-
@ACV:在我的 AJAX 请求中,我将 jsonData 设置为 currentFavor.data 而不是 currentFavor,并在成功函数中放入 allFavorsStore.add(currentFavor),现在 UI 似乎更新得很好。我也不再在服务器端收到那些讨厌的 hsqldb 错误。但是,如果我向我的服务器发出 Postman GET 请求,我仍然看不到那里保存的任何内容。你知道问题可能是什么吗?
-
您希望在执行 GET 请求时保存什么? GET 用于获取数据,而不是保存到数据库。
标签: sql spring database-schema hsqldb