有两张表,新闻表,新闻类别表,通过新闻类别ID关联,使用mybatis-plus写相关代码
时间: 2024-05-14 08:19:57 浏览: 17
假设新闻表为 `news`,包含字段 `id`、`title`、`content`、`category_id`,新闻类别表为 `category`,包含字段 `id`、`name`。
1. 新建实体类 `News` 和 `Category`,用于对应数据库中的表。
```java
@Data
public class News {
private Long id;
private String title;
private String content;
private Long categoryId;
// 省略getter/setter方法
}
@Data
public class Category {
private Long id;
private String name;
// 省略getter/setter方法
}
```
2. 新建 DAO 接口 `NewsMapper` 和 `CategoryMapper`,继承 `BaseMapper` 接口,使用 Mybatis-Plus 提供的方法进行数据库操作。
```java
public interface NewsMapper extends BaseMapper<News> {
}
public interface CategoryMapper extends BaseMapper<Category> {
}
```
3. 在 `News` 实体类中添加 `@TableName` 注解,设置对应的数据库表名。
```java
@Data
@TableName("news")
public class News {
private Long id;
private String title;
private String content;
@TableField("category_id")
private Long categoryId;
// 省略getter/setter方法
}
```
4. 使用 Mybatis-Plus 实现关联查询。
```java
@Service
public class NewsService {
@Autowired
private NewsMapper newsMapper;
@Autowired
private CategoryMapper categoryMapper;
public List<News> getNewsWithCategory() {
List<News> newsList = newsMapper.selectList(null);
for (News news : newsList) {
Category category = categoryMapper.selectById(news.getCategoryId());
news.setCategory(category);
}
return newsList;
}
}
```
在 `NewsService` 中通过 `newsMapper.selectList(null)` 获取所有新闻数据,然后通过 `categoryMapper.selectById(news.getCategoryId())` 获取对应的新闻类别数据,并将其设置到 `News` 实体类中,最后返回包含类别信息的新闻列表。