Mybatis 是一个持久层框架,用于简化数据库的操作,和Spring 没有任何关系,我们现在能使用它是因为 Spring Boot 把Mybatis 的依赖给引入进来了,在 pom.xml 里面
Mybatis 如何进行重命名?
看最后两行代码,这样就能重命名了
package com.example.mybatisdemo.mapper;
import com.example.mybatisdemo.model.UserInfo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface UserInfoMapper {
@Select("select * from userInfo")
List<UserInfo> selectAll();
@Select("select * from userInfo where id = #{id}")
UserInfo selectOne(Integer id);
@Select("select * from userInfo where id= #{userId}")
UserInfo selectOne2(@Param("userId")Integer id);
}
Mybatis 的增操作
package com.example.mybatisdemo.mapper;
import com.example.mybatisdemo.model.UserInfo;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface UserInfoMapper {
@Insert(" insert into userinfo(username,password,age,gender,phone) " +
"value(#{username},#{password},#{age},#{gender},#{phone})")
Integer insert(UserInfo userInfo);
}
依旧是右键,generate ,test,勾选,OK
package com.example.mybatisdemo.mapper;
import com.example.mybatisdemo.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
@Slf4j
@SpringBootTest
class UserInfoMapperTest {
@Autowired
private UserInfoMapper userInfoMapper;
@Test
void insert() {
UserInfo userInfo = new UserInfo();
userInfo.setUsername("zhaoliu");
userInfo.setPassword("123");
userInfo.setAge(45);
userInfo.setGender(0);
userInfo.setPhone("1775423");
Integer result = userInfoMapper.insert(userInfo);
log.info("insert 方法,执行结果:{}",result);
}
}
就能看到运行结果了
然后在Mysql查查看有没有插入成功
没毛病