Mybatis项目实现完整过程
- 1. 前期准备
- 1.1 新建库建表
- 1. 2 新建maven项目
- 1.3 修改目录
- 1.4 在idea中添加数据库的可视化
- 2. 后期实现
- 2.1 修改pom.xml文件,添加依赖 和资源文件指定
- 2.2 添加jdbc.properties属性文件(数据库的配置)
- 2.3 添加SqlMapConfig.xml文件,MyBatis的核心配置文件
- 2.4 创建实体类Student,用来封装数据
- 2.5 添加完成学生表的增删改查的功能的StudentMapper.xml文件
- 3. 实现测试
- 3.1 创建测试类,进行功能测试
1. 前期准备
1.1 新建库建表
SQL文件
#创建数据库ssm
CREATE DATABASE ssm DEFAULT CHARSET utf8;
#使用(打开)ssm数据库
use ssm;
#创建表student
CREATE TABLE `student` (
`id` int(11) AUTO_INCREMENT primary key ,
`name` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into student(name,email,age) values('张三','zhangsan@126.com',22);
insert into student(name,email,age) values('李四','lisi@126.com',21);
insert into student(name,email,age) values('王五','wangwu@163.com',22);
insert into student(name,email,age) values('赵六','zhaoliun@qq.com',24);
select * from student;
1. 2 新建maven项目
关于Maven的配置请参考以下文章:
maven的下载以及安装idea中Maven的配置,项目的创建
新建maven模块
第二步:进入模块创建窗口
第四步:new Moudle
第五步:选择Maven
第六步:输入项目名,修改仓库地址等信息
1.3 修改目录
将项目目录补充完整
1.4 在idea中添加数据库的可视化
选择Mysql后执行以下操作
2. 后期实现
2.1 修改pom.xml文件,添加依赖 和资源文件指定
添加mybatis和mysql的依赖
<!--添加mybatis的依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
在build标签中添加资源文件的指定
<!--添加资源文件的指定-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
<resource>
<directory>src/test/java</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
2.2 添加jdbc.properties属性文件(数据库的配置)
复制时修改名称和密码
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf8
username=root
password=111111
2.3 添加SqlMapConfig.xml文件,MyBatis的核心配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--读取属性文件-->
<properties resource="jdbc.properties"></properties>
<!--设置日志,输出底层执行的代码-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<typeAliases>
<!--单个实体类别名注册-->
<!-- <typeAlias type="com.lcl.pojo.Student" alias="student"></typeAlias>-->
<!--批量注册
别名是类名的驼峰命名法,可以在StudentMapper中简化代码-->
<package name="com.lcl.pojo"></package>
</typeAliases>
<!--配置数据库的环境变量-->
<environments default="development">
<environment id="development">
<!--JDBC:事务提交给程序员处理
MANAGED:事务提交给容器处理-->
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!--注册mapper.xml文件-->
<mappers>
<!--resource:从resources中找指定的文件名称注册
url:使用绝对路径注册
class:动态代理方式下的注册-->
<mapper resource="StudentMapper.xml"></mapper>
</mappers>
</configuration>
2.4 创建实体类Student,用来封装数据
不用说,此项最简单直接生成即可,需要有属性的get和set方法,以及三个构造器:无参构造器,所有属性构造器,缺少主键的构造器,以及toString 方法【方便输出】
public class Student {
private Integer id;
private String name;
private String email;
private Integer age;
public Student() {
}
public Student(Integer id, String name, String email, Integer age) {
this.id = id;
this.name = name;
this.email = email;
this.age = age;
}
public Student(String name, String email, Integer age) {
this.name = name;
this.email = email;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", age=" + age +
'}';
}
}
2.5 添加完成学生表的增删改查的功能的StudentMapper.xml文件
实际上就是sql语句的编写,
<?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">
<!--是整个文件的大标签,用来开始和结束xml文件
namespace:属性用来指定命名空间(相当于包名),用来区分不同的mapper.xml文件中相同的id属性-->
<mapper namespace="lcl">
<!--完成查询全部学生的功能
List<Student> getAll();
resultType:指定查询返回的结果集类型,必须是泛型的类型
parameterType:如果有参数,通过它来指定参数的类型
-->
<select id="getAll" resultType="student" >
select id,name,email,age from student
</select>
<!--根据学生id查询学生信息
Student getById(int id) -->
<select id="getById" parameterType="int" resultType="student">
select id,name,email,age from student where id = #{id}
</select>
<!--按学生姓名模糊查询
List<Student> getByName(String name)-->
<select id="getByName" parameterType="string" resultType="student">
select id,name,email,age from student where name like '%${name}%'
</select>
<!--增加学生的操作
insert :不需要有返回值
private String name;
private String email;
private Integer age;-->
<insert id="insert" parameterType="student">
insert into student(name,email,age) values (#{name},#{email},#{age})
</insert>
<!--按主键删除学生
delete:不需要有任何的返回值-->
<delete id="delete" parameterType="int">
delete from student where id = #{id}
</delete>
<!--按主键修改学生
update-->
<update id="update" parameterType="student">
update student set name=#{name},email=#{email},age=#{age}
where id=#{id}
</update>
</mapper>
3. 实现测试
3.1 创建测试类,进行功能测试
测试项目的增删改查功能
采用注解的形式,完成刚开始的获取SqlSession对象,以及使用After完成最后关闭SqlSession对象的操作。
public class MyTest {T
SqlSession sqlSession;
@Before
public void openSqlSession() throws IOException {
//使用文件流读取核心配置文件
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//取出SqlSession对象
sqlSession = factory.openSession();
}
@After
public void closeSqlSession(){
//关闭SqlSession
sqlSession.close();
}
@Test
public void testGetAll() throws IOException {
//完成查询操作
List<Student> studentList = sqlSession.selectList("lcl.getAll");
studentList.forEach(student -> System.out.println(student));
}
@Test
public void testGetById() throws IOException {
//执行查询语句
Student stu = sqlSession.selectOne("lcl.getById", 1);
System.out.println(stu);
}
/*一下均可修改*/
@Test
public void testGetByName() throws IOException {
//读取配置文件
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//读取SqlSession对象
SqlSession sqlSession = factory.openSession();
//执行查询
List<Student> studentList = sqlSession.selectList("lcl.getByName","an");
studentList.forEach(student -> System.out.println(student));
//关闭资源
sqlSession.close();
}
@Test
public void testInsert() throws IOException {
int num = sqlSession.insert("lcl.insert",new Student("zhaoliu","zhaoliu@126.com",21));
//在执行增删改操作时,需要手动提交事务
sqlSession.commit();
System.out.println(num);
}
@Test
public void testDelete() throws IOException {
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//创建SqlSession对象
SqlSession sqlSession = factory.openSession();
//执行删除语句
int num = sqlSession.delete("lcl.delete",6);
System.out.println(num);
//提交事务并关闭资源
sqlSession.commit();
sqlSession.close();
}
@Test
public void testUpdate() throws IOException {
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//创建SqlSession对象
SqlSession sqlSession = factory.openSession();
//执行删除语句
int num = sqlSession.update("lcl.update",new Student(3,"王五","王五@126.com",22));
System.out.println(num);
//提交事务并关闭资源
sqlSession.commit();
sqlSession.close();
}
}