Mybatis基本使用
1、创建maven项目,导入mybatis依赖。
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.4.SNAPSHOOT</version> </dependency>
2、创建MybatisConfig.xml配置连接文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org/DTD Config 3.0" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!-- MyBatis的全局配置文件 --> <configuration > <!-- 1.配置环境,可配置多个环境(比如:develop开发、test测试) --> <environments default="develop"> <environment id="develop"> <!-- 1.1.配置事务管理方式:JDBC/MANAGED JDBC:将事务交给JDBC管理(推荐) MANAGED:自己管理事务 --> <transactionManager type="JDBC"></transactionManager> <!-- 1.2.配置数据源,即连接池 JNDI/POOLED/UNPOOLED JNDI:已过时 POOLED:使用连接池(推荐) UNPOOLED:不使用连接池 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/user-mode?characterEncoding=utf-8"/> <property name="username" value="root"/> <property name="password" value="1234qwer"/> </dataSource> </environment> </environments> <!-- 2.导入Mapper配置文件,如果mapper文件有多个,可以通过多个mapper标签导入--> <mappers> <mapper resource="mapper/UserMapper.xml"/> </mappers> </configuration>
3、创建User用户实体类
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Long id;
/**
* 名称
*/
private String name;
/**
* 邮箱
*/
private String email;
/**
* 手机号
*/
private String phoneNumber;
}
4、创建用户model接口
@Mapper public interface UserMapper { List<User> getPageUser(@Param("name") String name); void insertUser(User user); void updateUser(User user); void deletetUser(Long userId); }
5、创建映射文件UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.itmy.dao.UserMapper"> <resultMap id="userRmap" type="com.itmy.model.entity.User"> <result jdbcType="VARCHAR" javaType="java.lang.String" column="name" /> </resultMap> <select id="getPageUser" resultType="com.itmy.model.entity.User" parameterType="string"> select * from tb_user <where> <if test="name != null and '' != name"> name like CONCAT('%',#{name},'%'); </if> </where> </select> <insert id="insertUser" parameterType="com.itmy.model.entity.User"> INSERT INTO `tb_user` (`name`, `account`,`password`, `email`,phone_number,remark) VALUES (#{name}, #{account}, #{password}, #{email},#{phoneNumber},#{remark}); </insert> <update id="updateUser" parameterType="com.itmy.model.entity.User"> UPDATE tb_user <set> <if test="name != null and '' != name"> name = #{name}, </if> <if test="account != null and '' != account"> account = #{account}, </if> <if test="password != null and '' != password"> password = #{password}, </if> <if test="email != null and '' != email"> email = #{email}, </if> <if test="phoneNumber != null and '' != phoneNumber"> phone_number = #{phoneNumber}, </if> <if test="remark != null and '' != remark"> remark = #{remark}, </if> </set> where id = #{id} </update> <delete id="deletetUser" parameterType="java.lang.Long"> DELETE FROM tb_user WHERE id = #{userId} </delete> </mapper>
6、在测试类中编写测试文件MTest.java
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Test { InputStream inputStream; SqlSession sqlSession; @Before public void beforeSql() throws IOException { inputStream = Resources.getResourceAsStream("MybatisConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); sqlSession = sqlSessionFactory.openSession(); } @org.junit.Test public void querySql(){ UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List<User> pageUser = userMapper.getPageUser(null); for (int i = 0; i < pageUser.size(); i++) { System.out.println(pageUser.get(i)); } } @org.junit.Test public void insertSql(){ UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user=new User(); user.setAccount("aaaaa@qq.com"); user.setEmail("aaaaa@qq.com"); user.setName("掌声"); user.setPassword("SDWAR!@"); user.setPhoneNumber("12345"); user.setRemark("测试优化信息"); userMapper.insertUser(user); sqlSession.commit(); System.out.println(); } @org.junit.Test public void updateSql(){ UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user=new User(); user.setAccount("bbabbb@qq.com"); user.setEmail("bbbabb@qq.com"); user.setName("掌声bb"); user.setPassword("SDbbWAR!@"); user.setPhoneNumber("12345"); user.setRemark("测试优化b信息"); user.setId(5L); userMapper.updateUser(user); System.out.println(); sqlSession.commit(); } @org.junit.Test public void deleteSql(){ UserMapper userMapper = sqlSession.getMapper(UserMapper.class); userMapper.deletetUser(6L); System.out.println(); sqlSession.commit(); } @After public void afterSql() throws IOException { sqlSession.close(); inputStream.close(); } }