mybatis配置-------
JDBC-------- jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/?characterEncoding=UTF-8 jdbc.username= jdbc.password=
Mybatis------------ public class Mybatis { private static SqlSessionFactory factory=null; static{ String config="mybatis-config.xml"; InputStream in= null; try { in = Resources.getResourceAsStream(config); factory= new SqlSessionFactoryBuilder().build(in); } catch (IOException e) { e.printStackTrace(); } } public static SqlSession getsqlSeesion(){ SqlSession sqlSession=null; if (factory!=null) { sqlSession= factory.openSession();/*非自动提交事务*/ } return sqlSession; } }
测试类 @Test//添加用户 public void TestinsertStudent(){ try { //加载mybatis配置文件 InputStream is= Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder(); //获取SqlSessionFactory SqlSessionFactory factory=builder.build(is); //会话连接 SqlSession sqlSession = factory.openSession(); //获取接口的实现类对象 StudenDao studenDao=sqlSession.getMapper(StudenDao.class); //测试studentDao中的方法 int i=studenDao.insertStudent(new Student(0,"10005","李四","男",21)); System.out.println("添加成功"); sqlSession.commit(); } catch (IOException e) { e.printStackTrace(); } } @Test//删除用户 public void TestDeleStudent(){ SqlSession sqlSession = Mybatis.getsqlSeesion(); StudenDao mapper = sqlSession.getMapper(StudenDao.class); int i = mapper.DeleStudent(1001); if (i>0){ System.out.printf("删除成功"); } sqlSession.commit(); sqlSession.close(); } @Test//更新用户 public void TestupdateStudent(){ SqlSession sqlSession = Mybatis.getsqlSeesion(); StudenDao mapper = sqlSession.getMapper(StudenDao.class); int i = mapper.updateStudent(new Student(0,"10005","李四","男",20)); if (i>0){ System.out.printf("修改成功"); } sqlSession.commit(); sqlSession.close(); } @Test//查询用户 public void TestListStudent(){ SqlSession sqlSession = Mybatis.getsqlSeesion(); StudenDao mapper = sqlSession.getMapper(StudenDao.class); Liststudents = mapper.ListStudent(); for (Student student1 : students) { System.out.println(student1); } sqlSession.close(); } @Test//分页查询 public void TestListstudents(){ SqlSession sqlSession = Mybatis.getsqlSeesion(); StudenDao mapper = sqlSession.getMapper(StudenDao.class); PageHelper.startPage(1,3); List students = mapper.ListStudents(); PageInfo pageInfo =new PageInfo (students); List list = pageInfo.getList(); for (Student student1 : list) { System.out.println(student1); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)