1.配置druid数据源
application.yml的配置
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource #配置当前要使用的数据源的操作类型
driver-class-name: com.mysql.jdbc.Driver #配置mysql的驱动程序类
url: jdbc:mysql://localhost:3306/mldn?serverTimezone=UTC #数据库连接地址
username: root #数据库用户名
password: admin #数据库连接密码
dbcp2: #进行数据库连接池的配置
min-idle: 5 #数据库连接池的最小维持连接数
initial-size: 5 #初始化提供的连接数
max-total: 5 #最大的连接数
max-wait-millis: 200 #等待连接获取的最大超时时间
如果用Junit进行单元测试,如果测试的时候使用java.sql中的DataSource类,需要添加Mybatis依赖
Junit测试类测试Druid是否连接成功的方法:
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class TestDataSource {
@Resource
private DataSource dataSource;
@Test
public void testConnection() throws SQLException {
System.out.println(this.dataSource.getConnection());
}
}
2.配置MyBatis
mybatis:
config-location: classpath:mybatis/mybatis.cfg.xml #mybatis配置文件所在路径
type-aliases-package: com.imooc.vo #定义所有操作类的别名所在包
mapper-locations: #所有的mapper映射文件
- classpath:mybatis/mapper/**/*.xml
3.新建mybatis目录,新建mybatis.cfg.xml文件
<?xml version="1.0" encoding="UTF-8" ?>4.在mybatis目录下新建mapper目录,在mapper目录下新建dept.xml文件
<?xml version="1.0" encoding="UTF-8" ?> <select id="findAll" resultType="Dept">
SELECT deptno,dname FROM dept;
</select>
该文件直接操作数据库
5.建立数据模型类,和数据表一一对应,实现Serializable接口
@SuppressWarnings(“serial”)
public class Dept implements Serializable {
private Long deptno;
private String dname;
public Long getDeptno() {
return deptno;
}
public void setDeptno(Long deptno) {
this.deptno = deptno;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
@Override
public String toString() {
return "Dept [deptno=" + deptno + ", dname=" + dname + "]";
}
}
6.建立dao类,新建数据库操作接口,和mapper中的xml文件的sql语句对应
@Mapper
public interface IDeptDAO {
public List<Dept> findAll();
}
注意,一定要加上@Mapper注解
7.开始编写业务逻辑代码,新建Service接口
public interface IDeptService {
public List list();
}
8.实现Service接口
@Service
public class DeptServiceImpl implements IDeptService {
@Resource
private IDeptDAO deptDAO;
@Override
public List<Dept> list() {
// TODO Auto-generated method stub
return this.deptDAO.findAll();
}
}
注意:不要忘记@service注解
9.使用Junit单元测试
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class TestDeptService {
@Resource
private IDeptService deptService;
@Test
public void testConnection() throws SQLException {
System.out.println(this.deptService.list());
}
}
整个项目的结构图