| I had a hard time to make my JUnit test working. Here are the code snippets. The first is my superclass:
@MappedSuperclass
abstract class IdentifiedEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
...
}
Then there are two descendeants:
@Entity
@Table(name = "\"user\"")
@AttributeOverride(name = "id", column = @Column(name = "user_id"))
public class User extends IdentifiedEntity {
...
}
and
@Entity
@Table(name = "meal")
@AttributeOverride(name = "id", column = @Column(name = "meal_id"))
public class Meal extends IdentifiedEntity {
@ManyToOne(optional = false)
@JoinColumn(name = "user_id")
private final User user;
...
@Override
public String toString() {
return getClass().getSimpleName() + '#' + getId() + "U#" + user.getId()
+ ':' + desc + '@' + when + '×' + calories;
}
}
Here is an excerpt of the script, creating the DB in PostgreSQL:
create table "user" (
user_id serial primary key,
...
);
create table meal (
meal_id serial primary key,
user_id int not null references "user"(user_id),
...
);
And finally the test case^
@ContextConfiguration("classpath:/spring/spring-app.xml")
@Sql("classpath:/db/refill.sql")
@RunWith(SpringRunner.class)
@Transactional(REQUIRED)
public class JpaMealRepositoryImplTest {
@Test
public void updateWithValidMeal() throws Exception {
meal.setId(ID_MEAL_ADMINS);
repo.update(meal);
}
}
The repo is
@Repository
public final class JpaMealRepositoryImpl implements MealRepository {
@Override
public void update(Meal meal) throws NotFoundException {
log.info("update({})", meal);
Preconditions.checkArgument(!meal.isNew(), "new");
Meal m = em.find(Meal.class, meal.getId());
log.debug("m={}", m);
if (m == null || m.getUser().getId() != meal.getUser().getId()) {
throw new NotFoundException("mealId=" + meal.getId() + "; userId=" + meal.getUser().getId());
}
m.setWhen(meal.getWhen());
m.setDesc(meal.getDesc());
m.setCalories(meal.getCalories());
}
}
Now here is the log:
The question is: Why 190216.877 D main/JpaMealRepositoryImpl - m=null? If I run this query in Postgres, replacing the ? with the meal_id (which is 4 as seen in the log), then I get a row. Just a single row as I wanted. Why em.find(...) returns null? I fill the DB with the refill.sql script on start of each test-class:
@Sql("classpath:/db/refill.sql")
Here is the qwery I issue in psql:
select
meal0_.meal_id as id1_0_0_,
meal0_.calories as calories2_0_0_,
meal0_."desc" as desc3_0_0_,
meal0_.user_id as user_id5_0_0_,
meal0_."when" as when4_0_0_,
user1_.user_id as id1_1_1_,
user1_.admin as admin2_1_1_,
user1_.calories_per_day_limit as calories3_1_1_,
user1_.email as email4_1_1_,
user1_.enabled as enabled5_1_1_,
user1_.name as name6_1_1_,
user1_.password as password7_1_1_,
user1_.registered_at as register8_1_1_
from
meal meal0_
inner join
"user" user1_
on meal0_.user_id=user1_.user_id
where
meal0_.meal_id=4;
The result is
|