一、新建一个maven工程
二、在pom.xml 加入如下配置
三、在src/main/resoures新建application.properties 文件,加入如下配置
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=asdf123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
四、数据库中新建一张表
五、新建一个UserMapper文件
package com.batian.mapper;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
public interface UserMapper {
@Insert("insert into user values(#{id},#{username},#{age})")
public int insert(@Param("id") String id,@Param("username") String username,@Param("age") int age);
}
六、新建UserService及实现类UserServiceImpl
package com.batian.service;
public interface UserService {
public int insert(String id,String username,int age);
}
package com.batian.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.batian.mapper.UserMapper;
import com.batian.service.UserService;
@Service
@Transactional
public class UserServiceImpl implements UserService{
@Autowired
private UserMapper userMapper;
public int insert(String id,String username,int age){
return userMapper.insert(id, username, age);
}
}
七、新建一个UserController
package com.batian.controller;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.batian.mapper.UserMapper;
import com.batian.service.UserService;
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/insert")
public String insert(){
int result = userService.insert("1", "test", 18);
String msg = "插入成功";
if(result<=0){
msg = "插入失败";
}
return msg;
}
}
八、编写启动类
package com.batian;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.batian.mapper")
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
注:@MapperScan这个注解必须加上
九、启动类后,在浏览器中浏览
数据库中查看
此时整合说明我们已经成功整合mybatis