使用IDEA创建
项目创建
选择Spring Initialzr,Java版本勾选default,点击next
填写自己的项目名称,选择自己的jdk版本
根据自己的项目选择依赖(可以不选择,在后面的pom文件自己添加合适的starter)
选择文件位置
项目目录结构
基础配置
配置自定义数据源
创建config包之后,新建自定义的数据源的类
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DruidDataSource dataSource(){
return new DruidDataSource();
}
设置application.yml文件
server:
port: 8080
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
url: jdbc:mysql://localhost:3306/java?serverTimezone=UTC
type: com.alibaba.druid.pool.DruidDataSource
# 数据源其他配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
#配置dao包里的接口的mybatis映射的mapper文件
mybatis:
mapper-locations: classpath:mybatis/*.xml
编写一个简单的hello
创建实体类student.java
@Data//lombok的注释,可以不用写get、set、构造方法等
public class Student {
private Integer id;
private String name;
private String sex;
private Integer age;
private float weight;
private float height;
}
编写dao层
//mapper注释表明是dao接口,
//可以不用但需要在启动类上加上@MapperScan(value = "com.li.myproject.dao")(推荐)
//@Mapper
public interface StudentDao {
public List<Student> selectAllStudent();
}
编写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.li.myproject.dao.StudentDao">
<select id="selectAllStudent" resultType="com.li.myproject.entity.Student">
select * from student
</select>
</mapper>
编写server层
server接口
public interface StudentServer {
public List<Student> selectAllStudent();
}
接口实现类
@Service
public class StudentServerImpl implements StudentServer {
@Autowired
StudentDao studentDao;
@Override
public List<Student> selectAllStudent() {
return studentDao.selectAllStudent();
}
}
编写controller
@Controller
public class HelloController {
@Autowired
StudentServerImpl studentServer;
@RequestMapping(value = "/hello")
@ResponseBody
public List<Student> hello(){
return studentServer.selectAllStudent();
}
}
主启动类
@SpringBootApplication
//mapper与mapperScan最好不要同时出现
@MapperScan(value = "com.li.myproject.dao")
public class MyprojectApplication {
public static void main(String[] args) {
SpringApplication.run(MyprojectApplication.class, args);
}
}