Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

mapping - Spring Data JDBC One-To-Many with Custom Column Name

I'm using spring-boot-starter-data-jdbc 2.4.2. In my domain aggregate I need to map a List of Strings that is populated from a column in another table. It is a legacy database so I have no control over the table and column names and need to use custom names. I see there is an @MappedCollection annotation, but can't see how to use it in this scenario. Below is my class:

@Data
@Table("NMT_MOVIE_THEATRE")
public class MovieTheatre {

    @Id
    @Column("MOVIE_THEATRE_ID")
    private Long id;

    @Column("ZIP_CODE")
    private String zipCode;

    // this comes from table NMT_CURRENT_MOVIE, column CM_ID, joined by MOVIE_THEATRE_ID
    private List<String> currentMovieIds;
}

Using Spring Data JDBC, how can I create the one-to-many relation?

question from:https://stackoverflow.com/questions/65898476/spring-data-jdbc-one-to-many-with-custom-column-name

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Wrap your String in a little entity.

@Table("NMT_CURRENTMOVIE")
class MovieId {
    @Id
    @Column("CM_ID")
    final String id

    // add constructor, equals and hashCode here or generate using Lombok
}

Then use it in the MovieTheatre. Since you don't have a column for an index, the proper collection to use is a Set

// ...
class MovieTheatre {
    // ...
    @MappedCollection(idColumn="MOVIE_THEATRE_ID")
    Set<MovieId> currentMovieIds;
}

Note that equals and hashCode is important as well as the constructor taking all arguments used in those, since the entity is used in a Set.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...