mybatis配置
pom.xml导入依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
jdbc依赖引用
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
1)配置dao层位置
2)编写dao类,repository注入容器
@Repository
public interface UserDao {
3)配置xml层所在位置
mybatis:
mapper-locations: classpath:mapper/*Mapper.xml
4)配置别名
mybatis:
mapper-locations: classpath:mapper/*Mapper.xml
type-aliases-package: com.cris.domain
5)固定dtd语句,mapper空间别名为对应dao的类路径
<?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.cris.dao.AdminDao" >
6)若希望测试运行时输出sql信息,则需要进行日志的相关配置,以下两种方式
mybatis:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
logging:
level:
com.seamax.bdsearch.dao: DEBUG
7)jdbc配置定义
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/student_forum?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
8)事物管理
使用@transactional注解,注意必须用于public上,可以使用在接口但不推荐,使用在接口上需要配置
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void addTopic(Topic topic){
}
9)mapper.xml
select,id为借口对应id,parameterType为接受参数对象类型,resultType为输出对象类型,resultType可填写resulMap节点的id值
注意,resultMap中association的子属性为javaType,而collection的子属性为ofType
<select id="adminSignIn" parameterType="admin" resultType="admin">
select * from table_admin where name = #{name} and password = #{password}
</select>
<resultMap id="topicsOfTab" type="topic">
<id property="id" column="id"></id>
<result property="title" column="title"></result>
<association property="user" javaType="user">
<id property="id" column="uid"></id>
<result property="avatar" column="avatar"></result>
<result property="username" column="username"></result>
</association>
</resultMap>