我有两张桌子: 客户和地址:
客户表:
CREATE TABLE `customer` (
`customer_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`user_name` varchar(45) NOT NULL,
`password` varchar(45) NOT NULL,
`encrypt_key` varchar(200) NOT NULL,
`first_name` varchar(45) NOT NULL,
`last_name` varchar(45) NOT NULL,
`email` varchar(50) DEFAULT NULL,
`active` tinyint(1) NOT NULL DEFAULT '1',
`last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`self_description` varchar(2000) NOT NULL,
PRIMARY KEY (`customer_id`),
KEY `idx_last_name` (`last_name`),
) ENGINE=InnoDB AUTO_INCREMENT=101 DEFAULT CHARSET=utf8;
地址表:
CREATE TABLE `address` (
`account_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`customer_id` smallint(5) unsigned NOT NULL,
`address_type` varchar(15) NOT NULL, -- Office, Branch-1, Branch-2,
`door_num` varchar(50) NOT NULL,
`landmark` varchar(150) DEFAULT NULL,
`street` varchar(50) DEFAULT NULL,
`area_name` varchar(25) NOT NULL,
`district` varchar(25) NOT NULL,
`city` varchar(25) NOT NULL,
`postal_code` varchar(10) DEFAULT NULL,
`phone1` varchar(20) NOT NULL,
`phone2` varchar(20),
`last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`account_id`),
KEY `idx_fk_city` (`city`)
) ENGINE=InnoDB AUTO_INCREMENT=201 DEFAULT CHARSET=utf8;
在Customer.java中
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "customer_id", nullable = false)
private List<Address> addresses;
在Address.java中 关于客户,请注意我正在使用单一指令。
在CustomerDaoImpl.java
中public boolean updateEntity(Customer customer) {
session = sessionFactory.openSession();
tx = session.beginTransaction();
session.saveOrUpdate(customer);
tx.commit();
session.close();
return false;
}
问题是:
我正在进行更新,每次都在创建新用户。 但我必须更新客户及其childes地址和主题对象。
我的要求机构:
{
"customerId": 102,
"addresses": [
{
"accountId": 203,
"addressType": "main office",
"areaName": "area3",
"city": "city3",
"district": "district3",
"doorNum": "89",
"landmark": "landmark3",
"phone1": "646432365465",
"phone2": "4534542355675",
"postalCode": "453245",
"street": "street3"
}
],
"active": 1,
"email": "bbb@gmail.com",
"encryptKey": "wwwwwfsad",
"firstName": "ccc",
"lastName": "ddd",
"password": "user2",
"selfDescription": "user2",
"userName": "user2",
"theme": {
"themeId": 402,
"description": "theme2",
"name": "theme2",
"categoryId": 301
}
}
请指导我必须做的所有改变。
答案 0 :(得分:0)
如果要更新数据库中的记录:首先必须从数据库检索记录到持久性上下文,然后更新其列值。我认为你正在尝试直接更新数据库记录,这是错误的。它只是创建具有不同id的新对象并将其保存在数据库中。
Customer retrievedCustomer = session.get(customer);
make you changes on retrievedCustomer...
session.update(retrievedCustomer);