java - Spring MVC : Handling data in an One to many relationship?

标签 java mysql spring spring-mvc

我正在使用 Spring MVC 实现一个 Web 应用程序。在我的应用程序中,我需要实现通知服务。这是通知的数据库表。

    CREATE TABLE `notification` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`),
  `message` varchar(100),
  `dateAndTime` time DEFAULT NULL,
  `read` tinyint(1) NOT NULL DEFAULT '0',
  `notificationType` int(11) DEFAULT NULL,
  `userId` bigint(20),
  FOREIGN KEY (`userId`) REFERENCES `application_user` (`id`)
);

这里的userId是发送通知的用户的ID。这可以是单个用户或多个用户。这取决于 notificationType 的值。这是我为此编写的域模式。

@Entity
@Table(name = "notification")
public class Notification {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;

private String message;

@DateTimeFormat(pattern = "yy-MM-dd-hh-mm")
private Date dateAndTime;

private boolean read;

public static enum NotificationType{
    SINGLE_USER, MULTIPLE_USER
}

//@OneToMany
//@JoinColumn(name="type")
//private User user;

ApplicationUser applicationUser;

private NotificationType notificationType = NotificationType.SINGLE_USER;
......

我不清楚如何在这里实现一对多关系。我希望mysql查询在上述条件下是准确的。请帮我解决这个问题。

编辑:

如果NotificationType = SINGLE_USER,我只需将通知发送给一个用户。如果NotificationType = MULTIPLE_USER,我需要向多个用户发送通知。

最佳答案

在表架构中,您定义多对一关系。

@ManyToOne
@JoinColumn(name="userId")
private User user;

If NotificationType = SINGLE_USER, I need to send the notification to only one user. If NotificationType = MULTIPLE_USER I need to send notification to several users.

在这种情况下,您应该创建另一个结构。

例如

CREATE USER (
    ...,
    notification_id,
    ...
)

class Notification {
    @OneToMany
    @JoinColumn(name="notification_id")
    private User user;
}

或者您可以创建新表,该表将仅保存 notification_id 和 user_id:

CREATE USER_NOTIFICATION (
    user_id,
    notification_id
)

然后

class Notification {
     @ManyToMany
     @JoinTable(
         name="USER_NOTIFICATION",
         joinColumns=@JoinColumn(name="USER_ID", referencedColumnName="ID"),
         inverseJoinColumns=@JoinColumn(name="NOTIFICATION_ID", 
         referencedColumnName="ID"))
  private List<User> users;
}

How do I connect this data with NotificationType?

通知表中有列类型。您如何发送通知 - 这是您的业务逻辑。您不需要为此对表结构进行任何操作。如果您愿意,您可以创建触发器,它将检查您在 USER_NOTIFICATION 中插入新的 (notification_id,user_id) 的逻辑。

关于java - Spring MVC : Handling data in an One to many relationship?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46293392/

相关文章:

java - ActiveMQ 重新交付策略和阻塞/非阻塞消费者设计

mysql - JPQL从多个表中获取数据

java - spring-data-neo4j 与 Autowired 冲突

java - spring RequestMapping 404 状态

javax.imageio.IIOException : I/O error writing PNG file 异常

java - GAE 数据存储上的键值数据?

Java:如何将字符串解析为不同的指定类

MySQL 错误 1045 (28000) : Access denied for user 'bill' @'localhost' (using password: YES)

php - 多个Where子句在php中导致 bool 错误

spring - 此处不允许注释