新建实体类User类
package org.hx.springboot_mybatis_demo27.model;
public class User {
private Integer id;
private String name;
private String passwd;
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", passwd='" + passwd + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
}
新建UserMapper类
package org.hx.springboot_mybatis_demo27.mapper;
import org.apache.ibatis.annotations.*;
import org.hx.springboot_mybatis_demo27.model.User;
import javax.jws.soap.SOAPBinding;
import java.util.List;
public interface UserMapper {
@Select("select * from t1 where id=#{id}")
User getUserById(Integer id);
@Select("select * from t1")
List<User> getAllUsers();
@Insert("insert into t1 (name,passwd) values(#{name},#{passwd})")
@SelectKey(statement = "select last_insert_id()",keyProperty = "id",before = false,resultType = Integer.class)
Integer addUser(User user);
@Delete("delete from t1 where id=#{id}")
Integer deleteById(Integer id);
@Update("update t1 set name=#{name} where id=#{id}")
Integer updateById(String name,Integer id);
}
配置application.properties文件
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
在启动类上加扫描Mapper的注解
@MapperScan(basePackages = "org.hx.springboot_mybatis_demo27.mapper")
在测试类中进行测试
package org.hx.springboot_mybatis_demo27;
import org.hx.springboot_mybatis_demo27.mapper.UserMapper;
import org.hx.springboot_mybatis_demo27.model.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
class SpringbootMybatisDemo27ApplicationTests {
@Autowired
UserMapper userMapper;
@Test
void contextLoads() {
User user = userMapper.getUserById(113);
System.out.println(user);
List<User> users = userMapper.getAllUsers();
for (User u:users) {
System.out.println(u);
}
}
@Test
void Test(){
User user = new User();
user.setName("hx");
user.setPasswd("npu");
userMapper.addUser(user);
System.out.println(user.getId());
}
@Test
void Test1(){
userMapper.deleteById(115);
userMapper.updateById("hx_npu",114);
}
}