语法

时间:2016-07-24 00:40:49

标签: spring hibernate spring-data spring-data-jpa jpql

我有一个用户实体:

@Entity
@Table
class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @Column
    private Integer value;

    @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "user")
    private UserDetails userDetails = new UserDetails(this);

    // getters, setters

}

UserDetails实体:

@Entity
@Table(name = "user_details")
class UserDetails {

    @GenericGenerator(name = "generator", strategy = "foreign",
         parameters = @Parameter(name = "property", value = "user"))
    @Id
    @GeneratedValue(generator = "generator")
    @Column(name = "user_id", unique = true, nullable = false)
    private Integer id;

    @Column
    private String name;

    @OneToOne
    @PrimaryKeyJoinColumn
    private User user;

    public UserDetails(User user) {
        setUser(user);
    }

    //getters, setters

}

我有一个UserRepository

public interface UserRepository extends JpaRepository<User, Integer> {

    @Transactional
    @Modifying
    @Query("update User set value = ?2 where userDetails.name = ?1")
    Integer addValue(String name, int value);

}

方法addValue给出下一个错误:

  

引起:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:   您的SQL语法有错误;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   接近'set value = 1000,其中name ='John''在第1行

我试图将名称从UserDetails移动到User并且它有效,但我必须将它保存在UserDetails中。错误在哪里?

1 个答案:

答案 0 :(得分:0)

您正在使用子映射父实体,因此只需将映射更改为子级到父级。

从用户中删除mappedBy并将其添加到UserDetails中, 所以修改后的映射如下所示, 即。

@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
private UserDetails userDetails = new UserDetails(this);

@OneToOne(mappedBy = "userDetails")
@PrimaryKeyJoinColumn
private User user;