引入Mybatis和数据库连接相关的依赖:
org.mybatis.spring.boot mybatis-spring-boot-starter2.2.0 org.springframework.boot spring-boot-starter-jdbcmysql mysql-connector-java8.0.25
application.properties配置文件加上数据库的配置:
spring.datasource.username=root spring.datasource.password=1234567 spring.datasource.url=jdbc:mysql://localhost:3306/myproject spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
使用的数据源驱动是默认的jdbc驱动,可以查看数据源是HikariDataSource,查看数据源类型的代码:
@Autowired
private DataSource dataSource;
@Test
void contextLoads() {
System.out.println(dataSource.getClass());
}
SpringBoot的自动装配使得dataSource可以自动注入。
还可以配置阿里的Druid数据源:
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
添加maven依赖:
com.alibaba druid1.2.8
该数据源具有查看SQL执行的统计情况的功能,在继承了WebMvcConfigure的自定义配置类MyConfig中添加只用了@Bean注解的方法statViewServlet():
@Bean
public ServletRegistrationBean statViewServlet() {
ServletRegistrationBean bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
HashMap map = new HashMap<>();
map.put("loginUsername", "admin");
map.put("loginPassword", "123456");
map.put("allow", "");
bean.setInitParameters(map);
return bean;
}
该方法中设置了登录用户和密码,设置了allow的属性值为空,表明不设拦截限制,然后在页面输入/druid请求即可访问登录页:
登录之后:
编写EmployeeMapper:
@Mapper
@Repository
public interface EmployeeMapper {
List getAllEmployee();
Employee getEmployeeById(int id);
void addEmployee(Employee employee);
void updateEmployee(Employee employee);
void deleteEmployee(int id);
}
一定要加上@Mapper和@Repository注解,@Mapper使得能够被SpringBoot识别为mapper类,@Repository使得能够注入到Spring容器中。另外还需配置MyBatis的别名包和mapper路径路径:
mybatis.type-aliases-package=com.example.pojo mybatis.mapper-locations=classpath:mapper/*.xml
然后再resources目录下新建mapper目录,在其中写EmployeeMapper.xml文件:
这里只写查询和添加的实现,因为更新和删除比较简单。查询的时候,因为Employee对象持有Department属性,而数据库的字段为dep_id,所以需要使用resultMap做个转化。查询的时候是两表一起查询,查询出所有字段并起好别名,再在resultMap中做映射转化,注意使用association标签做复杂对象的转化,如果是集合,则使用collection。在添加employee时,传入department.id即可。



