Mybatis-Java
mybatis使用
创建mapper映射
1、导入依赖
mybatis,mysql-connector-java,Log4j:
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency><!--mysql驱动包--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
2、配置mybatis.xml
dtd约束
找到api中,mybatis配置示例,复制约束条件
导入properties
启动log4j日志
实体类别名
连接数据库环境管理
连接数据库环境
事务管理
数据源
参数
mapper映射
3-1、mapper文件与接口名称相同
注意:
1、约束
2、mapper标签,注意namespace
4、创建mapper映射接口
1、普通
普通接口
mapper映射文件,文件名与接口相同
2、使用注解
@select("sql ")
调用mapper映射
//1、加载配置文件 Resources.getResourceAsStream("mybatis.xml"); //2.SqlsessionFactory对象 new sqlSessionFactoryBuilder().build(is ) //3、获取session对象 factory.getSession(); //4、对数据库操作两种 //1、获取mapper映射 session.selectList("com.bjsxt.mapper.StudentMapper.selAll",) //2、使用接口代理 //5、提交事务 session.commit(); //6、释放资源
调用Mybatis
5.1直接调用
//1.加载Mybatis.xml,转换为io流对象--Resourse InputStream is = Resources.getResourceAsStream("mybatis.xml"); //2.构建者模式:使用SqlSessionFactoryBuilder对象,构建SqlSessionFactory工厂对象 SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is); //3.使用工厂对象构建SqlSession对象 SqlSession session = factory.openSession(); //4.使用session对象执行相关方法(crud) // List<Student> list = session.selectList("com.bjsxt.mapper.StudentMapper.selAll"); List<Student> list = session.selectList("com.bjsxt.mapper.StuMapper.selAll"); //session.select("com.bjsxt.mapper.StudentMapper.selAll");//第一个参数指定调用的方法,后面指定参数 //5.提交事务 session.commit(); //6.关闭session对象 session.close();