学生(学号,姓名,性别,出生日期,籍贯,民族,所在班级); 课程(课程号,课程名,学分,开课学期,课程介绍,选课人数); 选课(学号,课程号,成绩)。 基于MyBatis和Spring实现以下功能: 编写程序创建选课表并向其中添加3条记录;
时间: 2024-05-27 10:04:58 浏览: 88
```java
// 首先定义实体类
public class Student {
private String id;
private String name;
private String gender;
private Date birthday;
private String nativePlace;
private String nation;
private String className;
// 省略getter和setter方法
}
public class Course {
private String id;
private String name;
private int credit;
private String term;
private String introduction;
private int selectedNum;
// 省略getter和setter方法
}
public class Selection {
private String studentId;
private String courseId;
private int score;
// 省略getter和setter方法
}
// 然后定义Mapper接口
public interface StudentMapper {
void insert(Student student);
}
public interface CourseMapper {
void insert(Course course);
}
public interface SelectionMapper {
void insert(Selection selection);
}
// 接着在Spring配置文件中配置数据源和MyBatis的SqlSessionFactory
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath*:com/example/mapper/*.xml"/>
</bean>
// 最后在Mapper XML文件中编写SQL语句
<!-- StudentMapper.xml -->
<mapper namespace="com.example.mapper.StudentMapper">
<insert id="insert" parameterType="com.example.entity.Student">
insert into student(id, name, gender, birthday, native_place, nation, class_name)
values(#{id}, #{name}, #{gender}, #{birthday}, #{nativePlace}, #{nation}, #{className})
</insert>
</mapper>
<!-- CourseMapper.xml -->
<mapper namespace="com.example.mapper.CourseMapper">
<insert id="insert" parameterType="com.example.entity.Course">
insert into course(id, name, credit, term, introduction, selected_num)
values(#{id}, #{name}, #{credit}, #{term}, #{introduction}, #{selectedNum})
</insert>
</mapper>
<!-- SelectionMapper.xml -->
<mapper namespace="com.example.mapper.SelectionMapper">
<insert id="insert" parameterType="com.example.entity.Selection">
insert into selection(student_id, course_id, score)
values(#{studentId}, #{courseId}, #{score})
</insert>
</mapper>
```
--相关问题--:
1. 如何使用MyBatis进行分页查询?
2. Spring
阅读全文