下载idea,新建项目New Project-》SpringInitializr,点 next,更改Group 和Artifat,点next。 选择SQL 中的 mySQL、JDBC、MyBatis。如果有其他需要可以再选其他的选项。
在pom.xml 加入以下代码,监控数据库连接池
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.28</version> </dependency>
在resources目录下创建application.yml ;com.example.demo.entity 也可以写作com.example.demo.*.entity;星号代表任意包名
#默认使用配置 spring: profiles: active: dev #公共配置与profiles选择无关,entity 是实例包,mapperLocations指的路径是src/main/resources mybatis: typeAliasesPackage: com.example.demo.entity mapper-locations: mybatis/*.xml --- #开发配置 ,application是数据库名 ,?后面是配置 spring: profiles: dev datasource: url: jdbc:mysql://localhost:3306/application?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8 username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver # 使用druid数据源 type: com.alibaba.druid.pool.DruidDataSource
在application上加@MapperScan注释 com.example.demo.dao 是mapper,连接resources下写的操作数据库的xml文件,也可以写作 com.example.demo.*.dao ,星号代表任意包名
@SpringBootApplication @MapperScan("com.example.demo.dao") public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
最后在entity包中创建和数据库对应实例,注意:实例不能有符号,如下划线;实例中基础类使用包装类如Integer、Long
创建dao接口 记得添加@Mapper注释,用于操作对应的xml文件
@Mapper
public interface UserDao {
int insert(User user);
int update(User user);
User getById(String id);
List<User> getList(Map param);
}
创建service接口 ,并实现。service接口实现的类用 @Service("XXXService")注释,并且引入dao 用 @Resource注释
@Service("userService")
public class UserServiceImpl implements UserService {
@Resource
private UserDao userDao;
}
在src/main/resources 下创建Mapp文件,例如UserMapper.xml 用来配置数据库增删改查具体操作
<?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.UserDao">
#增删改查代码
</mapper>
创建Controller控制器,实现与外界交互@RestController和 @RequestMapping注释,代表其get、post路径为 http:localhost:8888/user/insert 和http:localhost:8888/user/getbyId。
访问过程为 controller-》service(被serviceIml实现)-》dao执行xml文件。然后再逐层返回内容
也可以直接controller=》dao执行xml文件
@RestController
@EnableAutoConfiguration
// 若不用以上两个,可以用@Controller代替,推荐用@Controller
//上面两个可以用网页测试获取的get数据
@RequestMapping("/user")
public class UserController {
@Autowired
UserService userService;
@PostMapping("insert")
@ResponseBody
int insert(@RequestBody User user) {
return userService.insert(user);
}
@GetMapping("getById")
User getById(@RequestParam String id){
return userService.getById(id);
}
}
如果运行时报错 Failed to start component [Connector[HTTP/1.1-8080]]
application.properties中重新指定一个端口号
server.port=8081