整合Mybatis
官方文档:http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
配置文件操作
1.导入依赖
pom.xml文件
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
2. 配置数据源(数据库连接信息)
application.properties文件
spring.datasource.username=root
spring.datasource.password=001129
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#mybatis配置文件中 ‘别名’ 属性
mybatis.type-aliases-package=com.it.pojo
#mybatis配置文件中 ‘mapper映射’ 属性
mybatis.mapper-locations=classpath:mapper/*.xml
#config‐location: classpath:mybatis/mybatis‐config.xml 指定全局配置文件的位置
3. 测试数据库是否连接成功
4. 编写实体类
public class User {
private Integer id;
private String name;
private String password;
有参&&无参构造
get&&set方法
toString方法
}
5. 创建Mapper接口
@Mapper //指定这是一个操作数据库的Mapper,也就是Mybatis的Mapper
@Repository
public interface UserMapper {
List<User> queryUserForList();
User queryUserById(@Param("id") Integer id);
int addUser(User user);
int updateUser(User user);
int deleteUser(@Param("id") Integer id);
}
6. 创建Mapper实现的xml
在resources下创建一个mapper包,mapper包下创建userMapper.xml
<?xml version="1.0" encoding="utf8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace命名空间 ===> 绑定一个对应的DAO/Mapper接口 -->
<mapper namespace="com.it.mapper.UserMapper">
<select id="queryUserForList" resultType="user">
select * from user;
</select>
<select id="queryUserById" resultType="user">
select * from user where `id` = #{id}
</select>
<insert id="addUser" parameterType="user">
insert into user (`id`,`name`,`password`) values(#{id},#{name},#{password})
</insert>
<update id="updateUser" parameterType="user">
update user set `name` = #{name} , `password` = #{password} where `id` = #{id}
</update>
<delete id="deleteUser" parameterType="int">
delete from user where `id` = #{id}
</delete>
</mapper>
7. 创建Controller类来测试
测试数据操作是否正常
@RestController
public class UserController {
@Autowired
UserMapper userMapper;
@GetMapping("/queryUserById")
public User queryUserById(){
return userMapper.queryUserById(1);
}
@GetMapping("/addUser")
public String addUser(){
userMapper.addUser(new User(11,"abc","123455"));
return "添加成功";
}
@GetMapping("/deleteUser")
public String deleteUser(){
userMapper.deleteUser(8);
return "删除成功";
}
@GetMapping("/updateUser")
public String updateUser(){
userMapper.updateUser(new User(11,"axaxa","111111"));
return "修改成功";
}
}
8. 注意Maven资源导出问题***
如果在前几步操作正常的情况下出现报错,就在pom.xml配置文件的《build》标签下添加以下内容
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
9. 启动项目进行测试
上面操作数据库是通过配置文件来操作的
=========== 分割线 ==============
下面是通过注解来操作数据库
注解操作
1. 导入依赖
参考上方
2. 配置数据源
上方使用的是SpringBoot默认的数据源 我们这里练习一下Druid数据源
需要导入Druid依赖
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.22</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
配置数据源
spring:
datasource:
username: root
password: 001129
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf-8
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#Spring Boot 默认是不注入这些属性值的,需要自己绑定
#druid 数据源专有配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
3. 创建Druid配置类
创建Druid配置类,将起加入到spring中
@Configuration
public class DruidConfig {
//将自定义的数据源加入到ioc中,不再让springboot自动创建
//ConfigurationProperties 将配置文件中前缀为spring.datasource的属性
//注入到com.alibaba.druid.pool.DruidDataSource同名参数中
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource druidDataSource(){
return new DruidDataSource();
}
//配置Druid 监控管理后台的servlet
//需要使用内嵌servlet 因为容器没有web.xml配置文件
@Bean
public ServletRegistrationBean servletRegistrationBean(){
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean
(new StatViewServlet(),"/druid/*");
//这些参数可以在 com.alibaba.druid.support.http.StatViewServlet
//的父类 com.alibaba.druid.support.http.ResourceServlet 中刚找到
Map<String ,String> initParams = new HashMap<>();
//后台管理界面登录账号
initParams.put("loginUsername","admin");
//后台管理界面登录密码
initParams.put("loginPassword","123456");
//后台允许谁可以访问
//initParams.put("allow", "localhost"):表示只有本机可以访问
//initParams.put("allow", ""):为空或者为null时,表示允许所有访问
initParams.put("allow","");
//initParams.put("deny", "192.168.2.176");表示禁止此ip访问
//设置初始化参数
servletRegistrationBean.setInitParameters(initParams);
return servletRegistrationBean;
}
//配置 Druid 监控 之 web 监控的 filter
//WebStatFilter:用于配置Web和Druid数据源之间的管理关联监控统计
@Bean
public FilterRegistrationBean registrationBean(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String,String> initParams = new HashMap<>();
//排除这些请求的拦截
initParams.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
4. 测试Druid是否注入成功
访问 http://localhost:8080/druid/login.html查看
5. 创建实体类
public class User {
private Integer id;
private String name;
private String password;
有参&&无参构造
get&&set方法
toString方法
}
6. 创建Mapper接口
通过注解的方式操作数据库
@Mapper
public interface UserMapper {
@Select("select * from user")
List<User> queryUserForList();
@Select("select * from user where `id` = #{id}")
User queryUserById(@Param("id") Integer id);
@Options(useGeneratedKeys = true,keyProperty = "id")
@Insert("insert into user (`id`,`name`,`password`) values(#{id},#{name},#{password})")
int addUser(User user);
@Update("update user set `name`=#{name},`password`=#{password} where `id`=#{id}")
int updateUser(User user);
@Delete("delete from user where `id` = #{id}")
int deleteUser(@Param("id") Integer id);
}
7. 创建Controller来测试
@RestController
public class UserController {
@Autowired
UserMapper userMapper;
@GetMapping("/queryUserForList")
public List<User> queryUserForList(){
return userMapper.queryUserForList();
}
}
8. 【我们可以自定义mybatis配置规则】
@org.springframework.context.annotation.Configuration
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer(){
@Override
public void customize(Configuration configuration) {
//设置驼峰式命名规则
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
9【我们也可以配置包扫描】
使用MapperScan批量扫描所有的Mapper接口;
@MapperScan(value = "com.atguigu.springboot.mapper")
@SpringBootApplication
public class SpringBoot06DataMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBoot06DataMybatisApplication.class, args);
}
}