<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mapping.UserMapper">
<select id="getAll" resultType="com.bbg.entity.User">
select * from user;
</select>
<select id="selectById" parameterType="java.lang.String" resultType="com.bbg.entity.User">
select * from user where id = #{id}
</select>
<insert id="insertUser" parameterType="com.bbg.entity.User">
insert into user values(#{id}, #{name}, #{age}, #{mobileTel})
</insert>
<update id="updateUser" parameterType="com.bbg.entity.User">
update user set name = #{name}, age = #{age}, mobile_tel = #{mobileTel} where id = #{id}
</update>
<delete id="deleteUser" parameterType="java.lang.String">
delete from user where id = #{id}
</delete>
</mapper>
2、测试类
package com.bbg;
import com.bbg.entity.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
List<Object> objects = sqlSession.selectList("mapping.UserMapper.getAll");
for (Object object : objects) {
System.out.println(object.toString());
}
Object o = sqlSession.selectOne("mapping.UserMapper.selectById", "20210923001");
System.out.println(o);
User user1 = (User) o;
user1.setMobileTel("1888888888");
sqlSession.update("mapping.UserMapper.updateUser", user1);
o = sqlSession.selectOne("mapping.UserMapper.selectById", "20210923001");
System.out.println(o);
User user = new User();
user.setId("20210923002");
user.setAge(24);
user.setName("superhero");
user.setMobileTel("13235441205");
int insert = sqlSession.insert("mapping.UserMapper.insertUser", user);
if (insert > 0){
System.out.println("插入成功");
} else {
System.out.println("插入失败");
}
}
}