如何使用springboot中的CrudRepository基于inverseColumn数据检索数据?

时间:2017-06-11 17:22:56

标签: spring hibernate spring-boot crud spring-rest

我有两个表,即用户和事件。当新用户注册时,将填写用户表。以后的同一用户可以创建日历事件。因此将填充事件表,users_events将根据用户继续映射事件。 我想根据登录的userId找到所有事件。所以这里是查询,它应该基于它返回数据。 select * from eventid in events(从users_event中选择eventId,其中id_user = x)。这是我的用户和事件实体类。

User.java

    @Entity
    @Table(name = "users")
    public class User {

@Id
@GenericGenerator(name = "generator", strategy = "increment")
@GeneratedValue(generator = "generator")
@Column(name = "id", nullable = false)
private Long id;

@Column(name = "first_name", nullable = false)
private String firstName;

@Column(name = "family_name", nullable = false)
private String familyName;

@Column(name = "e_mail", nullable = false)
private String email;

@Column(name = "phone", nullable = false)
private String phone;

@Column(name = "language", nullable = false)
private String language;

@Column(name = "id_picture")
private String pictureId;

@Column(name = "login", nullable = false)
private String login;

@Column(name = "password", nullable = false)
private String password;

@Column(name = "birth_date")
private Date birthDate;

@Column(name = "enabled")
private Boolean enabled;
   //getter and setter

Event.java

    @Entity
    @Table(name = "events")
    public class Event {
@Id
@GenericGenerator(name = "generator", strategy = "increment")
@GeneratedValue(generator = "generator")
@Column(name = "eventId", nullable = false)
private Long eventId;

@Column(name = "title", nullable = false)
private String title;

@Column(name = "description", nullable = true)
private String description;

@Column(name = "startAt", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date startAt;

@Column(name = "endAt", nullable = true)
@Temporal(TemporalType.TIMESTAMP)
private Date endAt;

@Column(name = "isFullDay", nullable = false)
private Boolean isFullDay;

@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "users_event", joinColumns = { @JoinColumn(name = "id_event", referencedColumnName = "eventId") }, inverseJoinColumns = { @JoinColumn(name = "id_user", table = "users", referencedColumnName = "id") })
private Set<User> user = new HashSet<User>();
/getter and setter

EventRepo.java

   public interface EventRepo extends CrudRepository<Event, Long> {
Event findByUser(Set<User> user);
    }

我正在尝试实现一些东西,它可以给我输出这个查询。 select * from eventid in events(从users_event中选择eventId,其中id_user = x) 这是我的实现。请输入一下?

       @RequestMapping(value = "/events", method = RequestMethod.GET)
public @ResponseBody List<Event> getEvents() {
    logger.debug("get event list");
    User x=new User();
    x.setId(1);
    Set<User> user= new HashSet();
    user.add(x);
    return (List<Event>) eventRepo.findByUser(user);
}

1 个答案:

答案 0 :(得分:0)

只需将以下方法添加到ERR_CONNECTION_REFUSED

即可
EventRepo

将控制器修改为:

List<Event> findAllByUserId(Long userId);