Mybatis 依赖官网:https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starterhttps://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter
pom.xml插入依赖:
三、application.yml 数据库连接操作编写(SQL Server)org.mybatis.spring.boot mybatis-spring-boot-starter2.2.2 org.springframework.boot spring-boot-starter-weborg.mybatis.spring.boot mybatis-spring-boot-starter2.2.2 com.microsoft.sqlserver mssql-jdbcruntime org.springframework.boot spring-boot-starter-testtest org.springframework.boot spring-boot-devtoolsruntime true org.projectlombok lombok
application.yml
spring:
datasource:
driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
url: jdbc:sqlserver://127.0.0.1:1433;DatabaseName=Sports
username: sa
password: 123
四、进行连接数据库测试
@SpringBootTest
class Springboot06MybatisApplicationTests {
@Autowired
DataSource dataSource;
@Test
void contextLoads() {
System.out.println(dataSource.getClass());
try {
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
五、建立实体类 User
User.java类
package com.example.Entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private String userId;
private String userName;
private String password;
private String jurisdiction;
}
六、建立UserMapper接口
UserMapper.java 接口
package com.example.Mapper;
import com.example.Entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface UserMapper {
List queryUserList();
User queryUserById(int id);
int addUser(User user);
int updateUser(User user);
int delUser(int id);
}
七、 建立UserMapper.xml
在之前需要整合MyBatis:
#整合mybatis
mybatis:
type-aliases-package: com.example.Entity
mapper-locations: classpath:/mybatis/mapper
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/queryUserList")
public List queryUserList() {
List users = userMapper.queryUserList();
return users;
}
@GetMapping("/queryUserById")
public String queryUserById() {
userMapper.queryUserById(1);
return "queryUserById-OK";
}
@GetMapping("/addUser")
public String addUser() {
userMapper.addUser(new User("1","1","1","1"));
return "addUser-OK";
}
@GetMapping("/updateUser")
public String updateUser() {
userMapper.updateUser(new User("1","1","123","123"));
return "updateUser-OK";
}
@GetMapping("/delUser")
public String delUser() {
userMapper.delUser(1);
return "delUser-OK";
}
}



