首先肯定是创建一个项目,前面的都一样,加入的依赖不太一样:
加入这两个,创建就可以。
创建一个application.yml,这里添加的数据库是我学习Mybatis使用的数据库,你们也可以自行创建。
spring:
datasource:
username: root
password: 148729
url: jdbc:mysql://localhost:3306/mybatistest?userUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.jdbc.Driver
@SpringBootTest
class JdbcApplicationTests {
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
// 默认数据源
System.out.println(dataSource.getClass());
}
}
结果为:com.zaxxer.hikari.HikariDataSource
@SpringBootTest
class JdbcApplicationTests {
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
}
这时候可能遇到时区错误,可以在url中增加serverTimezone=UTC: url: jdbc:mysql://localhost:3306/mybatistest?serverTimezone=UTC&userUnicode=true&characterEncoding=utf-8
我们希望测试数据库操作,传出的是一个字符串,JSON对象即可,所以需要使用**@RestController**
(如果你创建项目的时候,加入了web依赖,可以不用添加)
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
@RestController
public class JDBCController {
@Autowired
JdbcTemplate jdbcTemplate;
//查询数据库信息
@RequestMapping("/userlist")
public List<Map<String,Object>> userList(){
String sql = "select * from user";
List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
return maps;
}
}
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.2.3version>
dependency>
#druid配置
#配置初始化大小/最小/最大
initialSize: 5
minIdle: 5
maxActive: 20
#获取连接等待超时时间
maxWait: 60000
#间隔多久进行一次检测,检测需要关闭的空闲连接
timeBetweenEvictionRunsMillis: 60000
#一个连接在池中最小生存的时间
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
#打开PSCache,并指定每个连接上PSCache的大小。oracle设为true,mysql设为false。分库分表较多推荐设置为false
poolPreparedStatements: false
maxPoolPreparedStatementPerConnectionSize: 20
#监控统计拦截的filters,stat:监控统计;log4j:日志记录;wall:防御sql注入;如果启用log4j记得添加依赖
filters: stat,wall,log4j
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource DruidDataSource(){
return new DruidDataSource();
}
}
//后台监控功能:web.xml
// 因为SpringBoot 内置了servlet容器,所以没有web.xml 替代方法:ServletRegistrationBean
@Bean
public ServletRegistrationBean a(){
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
// 后台需要有人登录,账号密码配置
HashMap<String, String> initParameters = new HashMap<>();
//增加配置 登录key 是固定的 loginUsername loginPassword
initParameters.put("loginUsername","admin");
initParameters.put("loginPassword","123456");
//允许谁可以访问
initParameters.put("allow","");
//禁止谁能访问 initParameters.put("用户名","地址");
bean.setInitParameters(initParameters); //设置初始化参数
return bean;
}
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
//可以过滤的请求
HashMap<String, String> initParameters = new HashMap<>();
initParameters.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(initParameters);
return bean;
}
这里我新创建的一个新的SpringBoot项目,这次导入web和上面sql中的那两个依赖。
该依赖不是SpringBoot官方,是专门用来整合Mybatis的。
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>2.1.3version>
dependency>
spring.datasource.username=root
spring.datasource.password=148729
spring.datasource.url=jdbc:mysql://localhost:3306/mybatistest?serverTime=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
public class User {
private Integer id;
private String name;
private String pwd;
// toString()方法
// Get/Set方法
// 有参/无参方法
}
在SpringBoot中,mapper包下只创建Mapper接口即可
// 这个注解表示了这是一个mybatis的mapper 类:Dao
@Mapper
@Repository //注入到Spring容器中
public interface UserMapper {
List<User> queryUserList();
User queryUserById(int id);
int addUser(User user);
int updateUser(User user);
int deleteUser(int id);
}
创建路径为:resources/mybatis/mapper
<mapper namespace="com.zc.mapper.UserMapper">
<select id="queryUserList" resultType="User">
select * from user;
select>
<select id="queryUserById" resultType="User" parameterType="int">
select * from user where id=#{id}
select>
<insert id="addUser" parameterType="User">
insert into user(id,name,pwd) values (#{id},#{name},#{pwd})
insert>
<delete id="deleteUser" parameterType="int">
delete from user where id = #{id}
delete>
<update id="updateUser" parameterType="User">
update user set name = #{name},pwd=#{pwd} where id = #{id}
update>
mapper>
如果想要上面语句中的User生效的话,需要进行起别名:
# 整合mybatis
#起别名
mybatis.type-aliases-package=com.zc.pojo
#注册classpath:mybatis/mapper路径下的所有mapper.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@RequestMapping("/queryUserList")
public List<User> queryUserList(){
List<User> users = userMapper.queryUserList();
for (User user : users) {
System.out.println(user);
}
return users;
}
}
直接开启启动器,进入网页即可
个人博客为: MoYu’s HomePage MoYu’s Gitee Blog