链接数据库mysql50:进行mysql50的增删查改
1.首先创建Mybatis,配置相关的环境
2.进入界面,打开pom,xml(mysql50mybatis),导入相关的代码块
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.2</version>
</dependency>
3.新建resources(设置成resources root),将原有的databases.properties和mybatis-config.xml包带入resources包中
4.将databases中的url修改为
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://192.168.153.149:3306/mysql50
user=root
password=root
5.在resours中创建ni.zb.mysql文件夹,在src-main-nj.zb.kb22中创造dao(创建mysql数据库中四张表的接口)和pojo(创建mysql数据库中的4张表)的包 ;在test文件中创建nj.zb.kb22(四张表测试)
6.在resources中创建四个相关的xml表
7.在mybatis中创建四个相关的mapper resource
<mappers>
<mapper resource="nj/zb/mysql/StudentDao.xml"/>
<mapper resource="nj/zb/mysql/TeacherDao.xml"/>
<mapper resource="nj/zb/mysql/ScoreDao.xml"/>
<mapper resource="nj/zb/mysql/CourseDao.xml"/>
</mappers>
8.进行StudentTest的增删查改
9.在IStudentDao接口中创建四个增删改查的命令:
public List<Student> getAllStudent();
public Integer save(Student student);
public Integer update(Student student);
public Integer delete(Integer id );
10.在StudentDao.xml中输出:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="nj.zb.kb22.dao.IStudentDao">
<select id="getAllStudent" resultType="Student">
select s_id, s_name, s_birth, s_sex from Student
</select>
<insert id="save">
insert into student(s_id,s_name,s_birth,s_sex)
values (#{s_id},#{s_name},now(),#{s_sex})
</insert>
<update id="update">
update student set s_name=#{s_name} where s_id=#{s_id}
</update>
<delete id="delete">
delete from student where s_id=#{s_id}
</delete>
</mapper>
11.在test中输出:public class StudentTest {
SqlSessionFactory sqlSessionFactory = null;
SqlSession sqlSession = null;
IStudentDao studentDao = null;
@Before
public void setUP() {
System.out.println("hello before");
InputStream inputStream = StudentTest.class.getClassLoader()
.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder builder = new S