简体   繁体   中英

How to work with column in many-to-many table in Spring Data Jpa?

I have entities User and Event. There is three tables in my database: 'users', 'events' and 'users_events' to save many-to-many relations between users and events. When user subscripts to an event, time of subscription should be saved. I added new column 'subscription_date' to the table 'users_events'. How should I write and read this column using Spring Data JPA and Hibernate as ORM?I tried to define new method in UserRepository with native SQL query, but it doesn't work.

@Modifying
@Query(
 value = "UPDATE users_events SET subscribed_date = :date " +
       "WHERE event_id = :event_id AND subscribed_user_id = :user_id",
 nativeQuery = true)
    public void saveSubscribedDate(
            @Param("user_id") int user_id,
            @Param("event_id") int event_id,
            @Param("date") LocalDateTime date);
}




You have to create three entity classes for it.

  1. User
  2. Event
  3. UsersEvents

Try something like this:

@Entity
class User {
   ...
   @ManyToMany(manpedby="event")
   Collection<Event> events;
   ...
}

@Entity
class Event {
    ...
    @ManyToMant(mappedby="user")
    Collection<User> user;
    ...
}

@Entity
class UsersEvents {
   private User user;
   private Event event;
   private Date date;
   ...
}

And respective three repository.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM