programing

복합 키로 엔티티를 저장하려고 할 때 SQLSyntaxErrorException

codeshow 2023. 8. 20. 12:58
반응형

복합 키로 엔티티를 저장하려고 할 때 SQLSyntaxErrorException

이것들은 나의 수업입니다.

사용자 활동

@Entity
@Data
@IdClass(UserActivityId.class)
public class UserActivity {

    @ManyToOne
    private User user;

    @Id
    @Column(name = "user_id", insertable = false, updatable = false)
    private Long userId;

    @ManyToOne
    private Stream stream;

    @Id
    @Column(name = "stream_id", insertable = false, updatable = false)
    private Long streamId;

    @Id
    private String userIp;

    //...8 more fields

}

사용자 활동이드

@Data
public class UserActivityId implements Serializable {
    private Long userId;
    private Long streamId;
    private String userIp;

    //constructors
}

개울.

@Entity
@Data
public class Stream {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @OneToMany(mappedBy = "stream")
    private List<UserActivity> UserActivities = new ArrayList<>();

}

사용자

public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    protected long id;
}

사용자 활동 저장소

public interface UserActivityRepository extends JpaRepository<UserActivity, UserActivityId>  
}

하지만 제가 이런 존재를 구하려고 할 때:

var stream = streamRepository.findById(activity.getStreamId);
var user = userRespository.findById(activity.getUserId);
activity.setStream(stream);
activity.setUser(user);
userActivityRepository.save(activity);

나는 다음과 같은 예외를 얻습니다.

java.sql.SQLSyntaxErrorException: (conn=1058) Could not set parameter at position 12 (values was 1)
Query - conn:1058(M)  - "insert into user_activity (a, b, c, d, e, f, g, h, user_id, stream_id, user_ip) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"

이상한 것은 내가 단지 11개의 필드를 가지고 있고 최대 절전 모드가 12번째 매개 변수를 설정하려고 하기 때문입니다. 나는 데이터베이스를 다시 생성하려고 시도했고 문제가 지속되었지만 복합 키를 제거하면 작동합니다.

정의insertable=false, updatable=false를 통해 엔티티에서 필드를 두 번 이상 매핑해야 할 때 유용합니다.OneToOne또는ManyToOne지도 제작

이 문제를 해결하려면 제거해야 할 것 같습니다.insertable=false, updatable=false에서Column주석

자세한 내용은 http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Primary_Keys_through_OneToOne_Relationships 을 참조하십시오.

그래서 저는 마침내 문제가 무엇인지 알게 되었고, 저는 배치해야 했습니다.@id외부 키 대신 관계 참조(스트림, 사용자) 위에, 또한 추가해야 했습니다.@MapsId그들에게

 @ManyToOne
    @Id
    @MapsId
    private User user;

    
    @Column(name = "user_id", insertable = false, updatable = false)
    private Long userId;

    @ManyToOne
    @Id
    @MapsId
    private Stream stream;

    
    @Column(name = "stream_id", insertable = false, updatable = false)
    private Long streamId;

    @Id
    private String userIp;

언급URL : https://stackoverflow.com/questions/63563132/sqlsyntaxerrorexception-when-trying-to-save-entity-with-composite-key

반응형