我有2个与ManyToMany关系相关的Hibernate对象Category和Article。在DB:category,article和cat_art表中。
我使用以下映射
类别:
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "cat_art", joinColumns = { @JoinColumn(name = "category_id") }, inverseJoinColumns = { @JoinColumn(name = "article_id") })
public List<Article> getArticles() {
return articles;
}
文章:
@ManyToMany(mappedBy = "articles", fetch = FetchType.LAZY)
public List<Category> getCategories() {
return categories;
}
测试代码:
article.setTitle("test");
article.setDescription("testtesttest");
Category cat = categoryService.getCategoryById(1L);
article.getCategories().add(cat);
cat.getArticles().add(article);
articleService.addArticle(article);
categoryService.addCategory(cat);
Hibernate:从category0_类别中选择category0_.id作为id1_3_0_,category0_.title作为title2_3_0_,其中category0_.id =?
Hibernate:选择articles0_.category_id为category1_3_0_,articles0_.article_id为article_2_2_0_,article1_.id为id1_1_1_,article1_.account_id为account_5_1_1_,article1_.description为descript2_1_1_,article1_.time为time3_1_1_,article1_.title为title4_1_1_ from cat_art articles0_ inner join article article1_ on articles0_.article_id = article1_.id where articles0_.category_id =?
Hibernate:插入文章(account_id,描述,时间,标题)值(?,?,?,?)
我的问题是当我向一个类别添加一篇文章时,没有记录被添加到关联表cat_art中。我在哪里做错了?感谢
服务层示例:
@Service("articleService")
@Repository
@Transactional
public class ArticleService {
private ArticleDAO articleDAO;
@Autowired
public ArticleService(ArticleDAO articleDAO) {
this.articleDAO = articleDAO;
}
@Transactional
public void addArticle(Article article) {
articleDAO.addArticle(article);
}
DAO示例:
public class ArticleDAOImpl extends HibernateDAO implements ArticleDAO {
@Autowired
public ArticleDAOImpl(SessionFactory sessionFactory) {
super(sessionFactory);
}
@Override
public void addArticle(Article article) {
getSession().save(article);
}
CategoryService和DAO类似
答案 0 :(得分:0)
错误位于spring-servlet.xml中的标记中 - 它被定义为使用所有Web控制器,存储库类等扫描根包。
更改它以仅使用网络控制器扫描包裹后,问题就消失了......我感谢大家的回答。抱歉我的英语不好。