I need to find a sensor by its ID and its user ID, which it belongs to.
Repository:
@Query("SELECT * from sensors LEFT JOIN users_sensors us on sensors.sensor_id = us.sensor_id " +
"WHERE sensors.sensor_id = :sensorId AND us.user_id = :userId")
Optional<Sensor> findBySensorIdAndUsersId(@Param("sensorId") Long sensorId, @Param("userId") String userId);
Populated data before calling a method:
INSERT INTO users (id) VALUES('user1');
INSERT INTO sensors (fk_sensor_type) VALUES(0);
INSERT INTO users_sensors (user_id, sensor_id) VALUES('user1', 1);
Sensor class contains:
@Id
@Column(name = "sensor_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long sensorId;
private int sensorType;
@ManyToMany(mappedBy = "sensors")
private List<User> users = new ArrayList<>();
User class:
@Entity
@Table(name = "users")
public class User {
@Id
@NotBlank
@Column(name = "id")
private String id;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(
name = "users_sensors",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "sensor_id")
)
final List<Sensor> sensors = new ArrayList<>();
// Constructors
// Getters and setters
}
users_sensors scheme:
create table users_sensors
(
id bigint primary key not null generated by default as identity,
user_id text not null,
sensor_id bigint not null,
foreign key (sensor_id) references sensors (sensor_id)
match simple on update no action on delete no action,
foreign key (user_id) references users (id)
match simple on update no action on delete no action
);
Method:
private static final Sensor sensor = new Sensor();
public void shouldReturnUserSensor() {
String userId = "user1";
// user is PRESENT
Optional<User> user = userRepository.findById(userId);
// inserts & returns 2
sensor.setUsers(List.of(user.get()));
sensor.setSensorType(0);
Long newSensorId = sensorRepository.save(sensor).getSensorId();
// expected sensor is NULL
Optional<Sensor> expectedSensor = sensorRepository.findBySensorIdAndUsersId(newSensorId, userId);
}
My expectedSensor is NULL and not found. When I run exact query provided above in the post under Repository
in Query Console, it returns correct values, but in the app it does not. How to solve this issue?