本文主要是介绍Mybatis 操作续集2(结合上文),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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 {@Autowiredprivate UserInfoMapper userInfoMapper;@Testvoid 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查查看有没有插入成功
没毛病
这篇关于Mybatis 操作续集2(结合上文)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!