我使用带有MySQL后端的maven,jersey和jaxRS在Java中创建应用程序。 我有一个用户模型,服务和资源。对于create account方法,它为帐户ID返回-1。这设置为自动增量,所以我不知道它为什么会这样发布。
这是我的模特 Account.java
@Entity
@Table
@XmlRootElement
public class Account implements Serializable{
@Id
private int accountNo;
private int cId;
private int balance;
private int sortCode;
public Account(){
this.accountNo = -1;
this.cId = -1;
this.balance = -1;
}
public Account(int accountNo, int cId, int balance, int sortCode) {
this.accountNo = accountNo;
this.cId = cId;
this.balance = balance;
this.sortCode = sortCode;
}
public int getAccountNo() {
return accountNo;
}
public void setAccountNo(int accountNo) {
this.accountNo = accountNo;
}
public int getcId() {
return cId;
}
public void setcId(int cId) {
this.cId = cId;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
public int getSortCode() {
return sortCode;
}
public void setSortCode(int sortCode) {
this.sortCode = sortCode;
}
这是服务方法
public Account createAccount(Account account) {
Account acc = pm.getEntityManager().find(Account.class, account.getAccountNo());
if (acc == null) {
pm.startTransaction();
pm.persist(account);
pm.commit();
pm.closeTransaction();
}
return account;
}
资源
@POST
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Account addAccount(Account account){
return accounts.createAccount(account);
}
Scehma
CREATE TABLE Banking.Account (
accountNo int(11) NOT NULL AUTO_INCREMENT,
cId int(11) NOT NULL,
balance int(11) NOT NULL,
sortCode int(11) NOT NULL,
PRIMARY KEY (accountNo),
KEY cId (cId),
KEY sortCode (sortCode),
CONSTRAINT account_ibfk_1
FOREIGN KEY (cId) REFERENCES Banking.CUSTOMER(custId)
) ENGINE=InnoDB AUTO_INCREMENT=816410 DEFAULT CHARSET=utf8;
当我通过邮差发布请求创建帐户时,所有内容都会创建,但会返回id为-1。
任何帮助?