发表
的代码
的 ref_post_tag
帖子和标记具有多对多关系
@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;
...
}
@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;
}
...
}
public interface TagRepo extends CrudRepository<Tag, Integer>{
}
@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());
}
}
@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"
}
}
样本测试用例通过。这意味着提取标记中的 postList 也会被急切地获取和填充。
默认情况下,Spring数据存储库的方法是急切地提取吗? 如果是,将此更改为延迟提取的最佳方式是什么?