springboot mybatis建两张表,分别是学生信息表和学生成绩表,两个表中的学生id和姓名相同,完成增删改查
时间: 2023-05-21 21:03:22 浏览: 147
好的,这是一个非常常见的需求,我可以为您提供一些代码示例:
首先,我们需要定义两个实体类,一个是学生信息类,一个是学生成绩类,它们之间是一对一的关系:
```java
public class Student {
private Integer id;
private String name;
// 其他属性和 getter/setter 方法省略
}
public class Score {
private Integer id;
private Integer studentId;
private Integer score;
// 其他属性和 getter/setter 方法省略
}
```
然后,我们需要定义两个 Mapper 接口,分别对应学生信息表和学生成绩表:
```java
public interface StudentMapper {
int insert(Student student);
int deleteById(Integer id);
int update(Student student);
Student selectById(Integer id);
List<Student> selectAll();
}
public interface ScoreMapper {
int insert(Score score);
int deleteById(Integer id);
int update(Score score);
Score selectById(Integer id);
List<Score> selectAll();
}
```
接下来,我们需要编写两个 Mapper 的 XML 文件,分别对应学生信息表和学生成绩表的 SQL 语句:
```xml
<!-- StudentMapper.xml -->
<mapper namespace="com.example.mapper.StudentMapper">
<insert id="insert" parameterType="com.example.entity.Student">
INSERT INTO student (id, name) VALUES (#{id}, #{name})
</insert>
<delete id="deleteById" parameterType="int">
DELETE FROM student WHERE id = #{id}
</delete>
<update id="update" parameterType="com.example.entity.Student">
UPDATE student SET name = #{name} WHERE id = #{id}
</update>
<select id="selectById" parameterType="int" resultType="com.example.entity.Student">
SELECT * FROM student WHERE id = #{id}
</select>
<select id="selectAll" resultType="com.example.entity.Student">
SELECT * FROM student
</select>
</mapper>
<!-- ScoreMapper.xml -->
<mapper namespace="com.example.mapper.ScoreMapper">
<insert id="insert" parameterType="com.example.entity.Score">
INSERT INTO score (id, student_id, score) VALUES (#{id}, #{studentId}, #{score})
</insert>
<delete id="deleteById" parameterType="int">
DELETE FROM score WHERE id = #{id}
</delete>
<update id="update" parameterType="com.example.entity.Score">
UPDATE score SET student_id = #{studentId}, score = #{score} WHERE id = #{id}
</update>
<select id="selectById" parameterType="int" resultType="com.example.entity.Score">
SELECT * FROM score WHERE id = #{id}
</select>
<select id="selectAll" resultType="com.example.entity.Score">
SELECT * FROM score
</select>
</mapper>
```
最后,我们需要在 Spring Boot 中配置 MyBatis,让它自动扫描 Mapper 接口和 XML 文件:
```java
@SpringBootApplication
@MapperScan("com.example.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
这样,我们就完成了学生信息表和学生成绩表的增删改查操作。当然,具体的业务逻辑还需要根据实际需求进行调整。
阅读全文