Database Tables
post
tag
ref_post_tag
post and tag has a Many-to-Many relationship
Entities
Post
@Entity
@Table(name = "post")
public class Post implements Serializable{
private static final long serialVersionUID = 1783734013146305964L;
public enum Status {
DRAFT, REMOVED, LIVE;
}
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private String id;
@Column(name = "title")
private String title;
@Column(name = "create_time")
private LocalDateTime createTime;
@Column(name = "update_time")
private LocalDateTime updateTime;
@Column(name = "content")
private String content;
@Column(name = "status")
@Enumerated(EnumType.STRING)
private Status status;
@ManyToMany
@JoinTable(
name = "ref_post_tag",
joinColumns = @JoinColumn(name="post_id",referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name="tag_id", referencedColumnName = "id"))
private List<Tag> tagList;
...
}
Tag
@Entity
@Table(name="tag")
public class Tag implements Serializable{
private static final long serialVersionUID = -7015657012681544984L;
@Id
@Column(name="id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(name="name")
private String name;
@Column(name="description")
private String description;
@ManyToMany(mappedBy = "tagList")
private List<Post> postList;
public Integer getId() {
return id;
}
...
}
Tag Repo
public interface TagRepo extends CrudRepository<Tag, Integer>{
}
service implementation
@Service
public class TagServiceImpl implements TagService{
@Autowired
private TagRepo tagRepo;
@Override
public void addTag(Tag tag) {
tagRepo.save(tag);
}
@Override
public Tag getTag(Integer id) {
Tag tag = tagRepo.findOne(id);
return tag;
}
@Override
public List<Tag> findAllTags() {
return CollectionUtil.toArrayList(tagRepo.findAll());
}
}
sample test (Updated)
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestContextConfiguration.class)
@Transactional
public abstract class ServiceTest {
}
public class TagServiceTest extends ServiceTest{
@Autowired
private TagService tagService;
@Autowired
private TagRepo tagRepo;
@Test
@Transactional
public void addTag() throws Exception {
Tag tag = new Tag();
tag.setName("new tag");
tag.setDescription("this is a new tag");
tagService.addTag(tag);
Tag tagCreated = tagRepo.findOne(tag.getId());
assertNotNull(tagCreated);
assertEquals(tagCreated.getName(), tag.getName());
}
@Test
public void getTag() throws Exception {
Tag tag = tagService.getTag(1); // tag "java" has an ID of "1"
assertNotNull(tag);
assertEquals(tag.getName(), "java");
assertEquals(143,tag.getPostList().size()); // 143 posts under tag "java"
}
}
Question
The sample test case passes. It means that the postList in fetched Tag is also eagerly fetched and filled.
Is Spring data repository's methods eagerly fetching by default?
If yes, what is the best way to change this to lazy fetching?