第一步:新建项目
选择Spring Initializr 然后下一步
组一般就是你的包名之前那里
然后Java版本按照你现在的JDK版本来选
其他的可以根据要求来改
改完以后选择下一步
之后会让你选择你需要的内容
根据你的需要选择就可以
然后点完成就行了
第二步:导入maven依赖
建立以后,其实你的依赖基本上都有了,所以你需要什么就导入什么就好了。我现在需要一个pagehelper和druid。
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.1</version>
</dependency>
然后把application.properties这个文件改个名,改成application.yml,然后在里面写配置,需要的时候cv就行。
spring:
datasource:
username: root
password: li4918458
url: jdbc:mysql://localhost:3306/mybatistest?serverTimezone=Asia/Shanghai
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
mvc:
view:
suffix: .html
static-path-pattern: /**
mybatis:
mapper-locations: classpath:/mapper/*.xml
type-aliases-package: com.lyh.pojo
configuration:
map-underscore-to-camel-case: true
resources:
static-locations: classpath:/templates/,classpath:/static/
pagehelper:
helper-dialect: mysql
reasonable: true
support-methods-arguments: true
page-size-zero: true
params: count=coountSql
row-bounds-with-count: true
offset-as-page-num: true
之后去XXXApplication这个类里面把dao层注入一下。就这样。
@MapperScan({"com.example.demo.dao"})
然后就是写一个数据库以及实体类,让实体类跟mybatis映射上。
在Dedao.xml里面写这个mapper的namespace是跟你的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.example.demo.dao.Dedao">
</mapper>
下面来写一个查询测试一下:
pojo层:
@Data
public class De {
private int id;
private Department did;
private Employees eid;
}
controller层:
@Controller
public class DeController {
@Autowired
DeService deService;
@ResponseBody
@RequestMapping("sselect")
public List<De> Select(){
return deService.Select();
}
}
dao层:
@Repository
@Mapper
public interface Dedao {
public List<De> Select();
}
mapper里面:
<?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.example.demo.dao.Dedao">
<resultMap id="testMap" type="com.example.demo.pojo.De">
<id property="id" column="id"/>
<association property="did" javaType="com.example.demo.pojo.Department">
<id property="id" column="id"/>
<result property="dname" column="dname"/>
</association>
<association property="eid" javaType="com.example.demo.pojo.Employees">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="sex" column="sex"/>
</association>
</resultMap>
<select id="Select" resultMap="testMap">
select d2.id,d1.dname,e.name,e.sex
from department d1 left join de d2 on d1.id=d2.did
left join employees e on d2.eid = e.id
</select>
</mapper>
service层:
@Service
public class DeService {
@Autowired
Dedao dedao;
public List<De> Select(){
return dedao.Select();
}
}
启动程序执行代码:
看见预期的返回结果,证明成功