Mybatis 增删改查+模糊查询
package com.ijuy.dao;
import com.ijuy.pojo.User;
import com.ijuy.util.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class DaoTest {
@Test
//查询全部
public void test1(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
for (User user: userList) {
System.out.println(user);
}
sqlSession.close();
}
@Test
//查询
public void test2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
sqlSession.close();
}
@Test
//增加
public void test3(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int res1 = mapper.addUser(new User(5, "神乐七奈", "123456"));
int res2 = mapper.addUser(new User(6, "qwer", "qwer"));
if(res1>0&&res2>0){
System.out.println(mapper.getUserById(5));
System.out.println(mapper.getUserById(6));
}
//提交事务
sqlSession.commit();
sqlSession.close();
}
@Test
//改动
public void test4(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
System.out.println("将"+mapper.getUserById(6)+"改为");
int res = mapper.UpDateUser(new User(6, "神乐mea", "123456"));
if(res>0){
System.out.println(mapper.getUserById(6));
}
sqlSession.commit();
sqlSession.close();
}
@Test
//删除
public void test5(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int id =6;
int res = mapper.DeleteUser(id);
if(res>0){
System.out.println(id+"号删除成功");
System.out.println(id+"号内容:"+mapper.getUserById(id));
}
sqlSession.commit();
sqlSession.close();
}
}
@Test
//模糊查询
public void test6(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserLike("神乐%");
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}