作者表 CREATE TABLE `author` ( `author_id` int NOT NULL AUTO_INCREMENT, `author_username` varchar(32) NOT NULL COMMENT '作者名称', `author_password` varchar(32) DEFAULT NULL COMMENT '密码', `author_email` varchar(32) DEFAULT NULL COMMENT '邮箱', PRIMARY KEY (`author_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 博客表 CREATE TABLE `blog` ( `blog_id` int NOT NULL AUTO_INCREMENT COMMENT '博客id', `blog_title` varchar(32) DEFAULT NULL COMMENT '博客标题', `blog_author_id` int DEFAULT NULL COMMENT '博客作者id', PRIMARY KEY (`blog_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 1.分析两张表之间的关系 作者-博客 ,博客-作者 2.使用Mybatis框架,完成一对多和一对一的关系映射查询代码,Mapper接口的Java类,以及数据库连接、Mybatis配置文件等一系列项目必备的代码
时间: 2024-01-25 20:04:57 浏览: 123
1. 作者表和博客表之间是一对多的关系,一个作者可以有多篇博客,而一篇博客只能属于一个作者。因此,在博客表中需要有一个外键 `blog_author_id`,指向作者表中的 `author_id`。
2. 一对多关系映射查询代码:
Author.java
```
public class Author {
private int authorId;
private String authorUsername;
private String authorPassword;
private String authorEmail;
private List<Blog> blogs;
// getters and setters
}
```
Blog.java
```
public class Blog {
private int blogId;
private String blogTitle;
private Author author;
// getters and setters
}
```
AuthorMapper.java
```
public interface AuthorMapper {
Author selectAuthorById(int authorId);
}
```
BlogMapper.java
```
public interface BlogMapper {
List<Blog> selectBlogsByAuthorId(int authorId);
}
```
author.xml
```
<mapper namespace="com.example.mapper.AuthorMapper">
<resultMap id="authorMap" type="Author">
<id property="authorId" column="author_id"/>
<result property="authorUsername" column="author_username"/>
<result property="authorPassword" column="author_password"/>
<result property="authorEmail" column="author_email"/>
<collection property="blogs" ofType="Blog">
<id property="blogId" column="blog_id"/>
<result property="blogTitle" column="blog_title"/>
</collection>
</resultMap>
<select id="selectAuthorById" resultMap="authorMap">
SELECT * FROM author WHERE author_id=#{authorId}
</select>
</mapper>
```
blog.xml
```
<mapper namespace="com.example.mapper.BlogMapper">
<resultMap id="blogMap" type="Blog">
<id property="blogId" column="blog_id"/>
<result property="blogTitle" column="blog_title"/>
<association property="author" javaType="Author">
<id property="authorId" column="author_id"/>
<result property="authorUsername" column="author_username"/>
<result property="authorPassword" column="author_password"/>
<result property="authorEmail" column="author_email"/>
</association>
</resultMap>
<select id="selectBlogsByAuthorId" resultMap="blogMap">
SELECT * FROM blog WHERE blog_author_id=#{authorId}
</select>
</mapper>
```
其中,`author.xml` 和 `blog.xml` 都需要在 Mybatis 的配置文件中引入。
数据库连接、Mybatis配置文件等代码可以参考 Mybatis 官方文档。
阅读全文