Hibernate,OneToMany关系和不需要的更新

时间:2016-04-19 23:32:25

标签: java spring hibernate

我正在开发一个带有以下实体的spring-hibernate java应用程序(已删除不必要的代码行以便更轻松地阅读代码):

@Entity
public class UserAccount extends IdentityEntity {

    ...

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "user_account_id", nullable = false)
    protected List<UserDevice> devices = new ArrayList<UserDevice>();

    ...    

}

@Entity
public class UserDevice extends IdentityEntity {

    ...

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_account_id", nullable = false, insertable=false, updatable=false)
    protected UserAccount userAccount;

    ...

}

生成的表格是:

user and device tables

我写了这样的junit测试(删除了不必要的代码行,以便更容易阅读代码):

@Test
@Transactional
public void testMainScenario()
{
    UserAccount user=userAccountCreate("dummy");
    userAccountSaveOrUpdate(user);

    UserDevice device=userDeviceRepository.createEntity();

    device.setUserAccount(user);
    user.getDevices().add(device);

    userDeviceRepository.saveOrUpdate(device);

    List<UserDevice> lista = userDeviceRepository.list();
    logger.info(lista.toString());
}

当我运行此测试时,会生成并执行以下查询:

INFO  p6spy - SQL: values next value for hibernate_sequence
INFO  p6spy - SQL: insert into USER_ACCOUNT (CREATION_TIME, UPDATE_TIME, UID, EMAIL, EMAIL_VERIFIED, ENABLED, NAME, PASSWORD, USERNAME, ID) values ('20-apr-16', '20-apr-16', '8387a3ae-7023-4a40-a4c6-242851d19b12', 'dummy@dummy.org', 0, 0, NULL, 'e4b20227-a946-421e-8e33-c90346c60d2e', 'dummy', 1)
INFO  p6spy - SQL: values next value for hibernate_sequence
INFO  p6spy - SQL: insert into USER_DEVICE (CREATION_TIME, UPDATE_TIME, UID, ACCESS_TOKEN, DESCRIPTION, NAME, user_account_id, ID) values ('20-apr-16', '20-apr-16', 'c549cd4c-32dc-4ace-8b63-6f7c7a8fa454', NULL, NULL, NULL, 1, 2)
INFO  p6spy - SQL: update USER_DEVICE set user_account_id=1 where ID=2

问题是:如何在设备INSERT SQL之后避免USER_DEVICE表的最后一次UPDATE?这不是必需的。

0 个答案:

没有答案