public interface UserMapper {
/*注解实现增删改查*/
@Select("select * from tb_user")
List<User> selectAll2();
@Insert("insert into tb_user values(null,#{username},#{password},#{gender},#{addr})")
void insert(User user);
@Update("update tb_user set username=#{username},password=#{password},gender=#{gender},addr=#{addr} where id=#{id}")
void updateUser(User user);
@Delete("delete from tb_user where id=#{id}")
void delete(int id);
}
import com.entity.Brand;
import com.entity.User;
import com.mapper.BrandMapper;
import com.mapper.UserMapper;
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 org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class TestUser {
/*注解实现增删改查*/
@Test
public void testSelectAll2() throws IOException {
//1. 加载mybatis的核心配置文件,获取 SqlSessionFactory
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2. 获取SqlSession对象,用它来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
//3. 执行sql
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> list = mapper.selectAll2();
System.out.println(list);
//4. 释放资源
sqlSession.close();
}
@Test
public void testInsert() throws IOException {
//1. 加载mybatis的核心配置文件,获取 SqlSessionFactory
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User(null,"王王","123","男","赣州");
mapper.insert(user);
sqlSession.close();
}
@Test
public void testUpdate() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User(4,"王维","123","男","赣州");
mapper.updateUser(user);
sqlSession.close();
}
@Test
public void testDelete() throws IOException {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.delete(4);
sqlSession.close();
}
}
标签:mapper,sqlSessionFactory,05,改查,UserMapper,sqlSession,user,Mybatis,import
From: https://www.cnblogs.com/oyww-2027/p/17716869.html