V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
Ununennium
V2EX  ›  问与答

请教一个简单的 Java 问题

  •  
  •   Ununennium · May 18, 2022 · 1624 views
    This topic created in 1444 days ago, the information mentioned may be changed or developed.

    今天在把一个项目的数据库,从 oracle 切换到 postgres 时, 遇到了问题

    UserLogic.java
    
    User user = getUserAFromXXX();
    user.setUpdateTime( new Date() );
    UserDao.update( user );
    

    执行到 update()时,报错如下:

    错误: 语法错误 在 "(" 或附近的
    
        update
            (
                select
                    *          
                from
                    USER
                where
                    TYPE=1      
            ) 
        set
           UPDATETIME = NOW()
        where 
           TYPE=1
    

    看了一下,User 分为 2 种形式,UserA 和 UserB 。

    两者在数据库中,对应着同一张表,都为 USER 表。

    唯一的不同仅在于 A 的 type = 1 ,B 的 type = 2 。

    当需要使用 type = 1 的数据时,则取 UserA 的 entity ,反之亦然。

    UserA.hbm.xml:
    
     <class 
        name="userA" 
        table="USER"
        lazy="true"
     >
        <subselect>
            select * 
            from USER
            where TYPE=1
        </subselect>
    ……(下略)……
    
    UserB.hbm.xml:
    
     <class 
        name="userB" 
        table="USER"
        lazy="true"
     >
        <subselect>
            select * 
            from USER
            where TYPE=2
        </subselect>
    ……(下略)……
    
    

    回到最开始的提问,原本 SQL 是:

        update
           USER
        set
           UPDATETIME = NOW()
        where 
           TYPE=1
    

    因为现在这种写法,变成了:

        update
            (
                select
                    *          
                from
                    USER
                where
                    TYPE=1      
            ) 
        set
           UPDATETIME = NOW()
        where 
           TYPE=1
    

    以前的数据库是 oracle 的,这种写法倒是也能更新进去。现在数据库换成了 Postgres ,直接报语法错误了。

    看了下 hibernate 的官方文档,<subselect>应该是只读,不能用于更新,不知道为什么原来的程序员这么写。

    Chapter 5. Basic O/R Mapping

    不知道怎么改了,还望各位大佬不吝赐教,小的感激不尽。

    2 replies    2022-05-18 22:22:59 +08:00
    itechify
        1
    itechify  
    PRO
       May 18, 2022 via Android   ❤️ 1
    hibernate 太久没用了,会不会是没有更换方言呀
    Ununennium
        2
    Ununennium  
    OP
       May 18, 2022 via Android
    @oneisall8955 非常你的回复。
    确认过了跟方言没有关系,是 subselect 的原因。
    最后我改用原生 SQL 提交了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   925 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 23:22 · PVG 07:22 · LAX 16:22 · JFK 19:22
    ♥ Do have faith in what you're doing.