【问题标题】:Problem in understanding mapping in Java Spring boot在 Java Spring boot 中理解映射的问题
【发布时间】:2020-11-26 08:50:47
【问题描述】:

我刚刚开始使用 Spring Boot。 我有 3 个表 User、UserNotes 和 Notes。

  1. 用户(userID、EmailID)
  2. UserNotes(用户 ID、NotesID)
  3. 备注(notesID、标题、消息)

当我添加电子邮件时,必须自动生成 UserID。当我添加与用户对应的任何注释时,必须自动生成 UserNotes 表中的 Notes Id,并且必须将其添加到 Notes 表中。
我在 MySQL 中通过将 User 表中的 userID 作为主键并将 UserNotes 中的 UserID 作为引用它的外键来完成此操作。类似地,UserNotes 中的 NotesID 作为主键,Notes 表中的 notesID 作为外键。

当我为此使用 MySQL 查询时,一切正常。但现在我想为此使用 Spring Data JPA。但是我在理解如何映射具有多个表的这些关系方面遇到了困难。我尝试过 OneToManyManyToOne 关系,但没有成功

MySQL Queries for the reference  
1) Create table User(userID int AUTO_INCREMENT, emailID varchar(40), PRIMARY KEY(userID));  
2) Create table UserNotes(userID int, NotesID int AUTO_INCREMENT, PRIMARY KEY(NotesID), Foreign key(UserID) references User(UserID) on DELETE CASCADE);  
3) Create table Notes(notesID int, title varchar(100), message varchar(500), Date date, PRIMARY KEY(notesID), FOREIGN KEY(notesID) references UserNotes(NotesID) on DELETE CASCADE);  

【问题讨论】:

  • 您应该阅读不同类型的实体关系,特别是多对多关系。连接表 UserNote 不会生成任何东西,因为这些是它包含的外键,它们必须首先在相应的表中创建。一般来说,我建议你读一本关于 sql 的书,因为你需要了解一些基础知识。

标签: java mysql spring spring-boot


【解决方案1】:

使用 Hibernate、JPA、Lombok 的未经测试的示例:

用户实体

@Entity
@Table(name = "USER")
@SequenceGenerator(name = "userSeqId", sequenceName = "user_seq_id", allocationSize = 1)
@NoArgsConstructor
@Setter
@Getter
public class User {

    @Id
    @GeneratedValue(generator = "userSeqId", strategy = GenerationType.AUTO)
    private Long id;

    @NotBlank
    @Column(name = "EMAIL", unique = true)
    private String email;
}

笔记实体

@Entity
@Table(name = "NOTES")
@SequenceGenerator(name = "notesSeqId", sequenceName = "notes_seq_id", allocationSize = 1)
@NoArgsConstructor
@Setter
@Getter
public class Notes {

    @Id
    @GeneratedValue(generator = "notesSeqId", strategy = GenerationType.AUTO)
    private Long id;

    @NotBlank
    @Column(name = "TITLE")
    private String title;

    @NotBlank
    @Column(name = "MESSAGE")
    private String message;
}

UserNotes 实体

@Entity
@Table(name = "USER_NOTES")
@NoArgsConstructor
@Setter
@Getter
public class UserNotes {

    @EmbeddedId
    private UserNotesKey id;

    @NotNull
    @ManyToOne
    @MapsId("USER_ID")
    @JoinColumn(name = "USER_ID")
    @OnDelete(action = OnDeleteAction.CASCADE)
    private User user;

    @NotNull
    @ManyToOne(cascade = CascadeType.PERSIST)
    @MapsId("NOTES_ID")
    @JoinColumn(name = "NOTES_ID")
    @OnDelete(action = OnDeleteAction.CASCADE)
    private Notes notes;
}

@Embeddable
@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
@EqualsAndHashCode
public class UserNotesKey implements Serializable {

    @Column(name = "USER_ID")
    private Long userId;

    @Column(name = "NOTES_ID")
    private Long notesId;
}

存储库

public interface UserRepository extends JpaRepository<User, Long> {

}

public interface NotesRepository extends JpaRepository<Notes, Long> {

}

public interface UserNotesRepository extends JpaRepository<UserNotes, UserNotesKey> {

    List<UserNotes> findByUser(User user);
}

测试服务

@Service
@Transactional
@RequiredArgsConstructor
public class TestService {

    private final UserRepository userRepository;
    private final UserNotesRepository userNotesRepository;

    public User saveUser(User user) {
        User newUser = new User();
        user.setEmail(user.getEmail());
        return userRepository.save(user);
    }

    public UserNotes saveNotes(User user, Notes notes) {
        UserNotes userNotes = new UserNotes();
        userNotes.setUser(user);
        userNotes.setNotes(notes);
        return userNotesRepository.save(userNotes);
    }

    public List<Notes> getNotes(User user) {
        return userNotesRepository.findByUser(user)
                .stream()
                .map(UserNotes::getNotes)
                .collect(Collectors.toList());
    }
}

【讨论】:

    猜你喜欢
    • 2016-02-17
    • 2020-06-26
    • 2018-06-01
    • 2011-01-18
    • 2021-06-28
    • 2018-07-03
    • 1970-01-01
    • 2017-06-12
    • 1970-01-01
    相关资源
    最近更新 更多