1.1 SqlSessionFactory:用于创建SqlSession的工厂类
1.2 SqlSession : Mybatis的核心组件,用于想数据库执行SQL
1.3 配置文件: XML配置文件,对Mybatis的底层行为做出详细的配置
1.4 Mapper接口:就是DAO接口,在Mybatis中习惯性的称为Mapper
1.5Mapper映射器:用于编写SQL,并将SQL和实体类映射的主键,采用XML,注解均可实现.
2.1 导入pom包依赖:
1. 访问mvnrepository.com搜索MySQL,复制依赖加进pom
2.搜索要整合的框架,在mvnrepository.com中搜索mybatis-spring或者Mybatis-springboot
2.2 在application.xml文件中,配置数据库连接
在springboot官方手册中有相关配置的模板:
# DataSourceProperties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/jtadmin?characterEncoding=utf-8&useSSL=false&serverTimezone=Hongkong
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.maximum-pool-size=15
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.idle-timeout=30000
# MybatisProperties
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.pg.pgcommunit.entity
mybatis.configuration.useGeneratedKeys=true
mybatis.configuration.mapUnderscoreToCamelCase=true
如果不添加@Mapper注解这一层就没有交给容器来管理,后期容器扫描不到这一层
<?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="com.pg.pgcommunit.dao.UserMapper">
<select id="selectById" resultType="User">
select * from demo_user where id = #{id}
</select>
<insert id="insertUser" parameterType="User" keyProperty="id">
insert into demo_user(name,age,sex) value (#{name},#{age},#{sex})
</insert>
<update id="updateUser">
UPDATE demo_user SET name =#{name} WHERE id = #{id}
</update>
<delete id="deleteById">
delete from demo_user where id =#{id}
</delete>
</mapper>
< mapper namespace=“com.pg.pgcommunit.dao.UserMapper”>
namespace路径对应添加@Mapper注解的service层接口
< select id=“selectById” resultType=“User”>
注意添加返回值类型,类型一般为对应的dao层的属性类
< insert id=“insertUser” parameterType=“User” keyProperty=“id”>
插入方法多一个keyProperty id自增属性
@SpringBootTest
@ContextConfiguration(classes =PgCommunitApplication.class)
测试类需要加注解
大致代码如下:
@SpringBootTest
@ContextConfiguration(classes =PgCommunitApplication.class)
public class testCRUD {
@Autowired
private UserMapper userMapper;
@Test
public void testSelectById(){
User user = userMapper.selectById(1);
System.out.println(user);
}
@Test
public void testInsertUser(){
User user = new User();
user.setName("nihao");
user.setAge(55);
user.setSex("未知");
int i = userMapper.insertUser(user);
System.out.println(i);
}
@Test
public void testUpdateUser(){
User user = new User();
user.setId(241);
user.setName("你好");
int i = userMapper.updateUser(user);
System.out.println(i);
}
@Test
public void testDeleteById(){
User user = new User();
user.setId(242);
int i = userMapper.deleteById(user.getId());
System.out.println(i);
}
}
小白刚刚开始研究 如有不对的地方,欢迎大佬指出!