本文共 9143 字,大约阅读时间需要 30 分钟。
Mybatis相关配置、 常用API、sqlMapConfig详解、 mapping详解、mybatis注解
jdbc的原始方法(未经封装)实现查询数据库表记录
public static void main(String[] args) { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { // 加载数据库驱动 Class.forName("com.mysql.jdbc.Driver"); // 通过驱动管理类获取数据库链接 connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8", "root", "123"); // 定义sql语句 ?表示占位符 String sql = "select * from user where username = ?"; // 获取预处理statement preparedStatement = connection.prepareStatement(sql); // 设置参数,第一个参数为sql语句中参数的序号(从1开始),第二个参数为设置的参数值 preparedStatement.setString(1, "admin"); // 向数据库发出sql执行查询,查询出结果集 resultSet = preparedStatement.executeQuery(); // 遍历查询结果集 while (resultSet.next()) { System.out.println(resultSet.getString("id") + " " + resultSet.getString("username")); } } catch (Exception e) { e.printStackTrace(); } finally { // 释放资源 if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }}
2 导入 log4j 的配置文件(参考 MyBatis 的官网手册–>日志)
3 创建 MyBatis 的全局配置文件(参考 MyBatis 的官网手册)
mybatis-config.xml4 创建 Mybatis 的 sql 映射文件
EmployeeMapper.xml5 测试
public class MyBatisTest { public SqlSessionFactory getSqlSessionFactory() throws IOException { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); return new SqlSessionFactoryBuilder().build(inputStream); } @Test public void test() throws IOException { SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession session = sqlSessionFactory.openSession(); try { Employee employee = session.selectOne( //select0ne方法用于执行查询查询返回的结果只有-条记录的sq1语句 //第一个参数是你要执行的sq1语句(Mapper配置文件 名称空间.id) //第二个参数,是你要执行的sq1语句的对应参数值 "com.atguigu.mybatis.EmployeeMapper.getEmpById", 1); System.out.println(employee);//实现查询操作 } finally { session.close(); } }@Test public void test01() throws IOException { // 1、获取sqlSessionFactory对象 SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); // 2、获取sqlSession对象 SqlSession session = sqlSessionFactory.openSession(); try { // 3、获取接口的实现类对象 //会为接口自动的创建一个代理对象,代理对象去执行增删改查方法 EmployeeMapper mapper = session.getMapper(EmployeeMapper.class); Employee employee = mapper.getEmpById(1); System.out.println(mapper.getClass()); System.out.println(employee); } finally { session.close(); } }
public interface EmployeeMapper { public Employee getEmployeeById(Integer id );}
1 Mapper 接口与 Mapper 映射文件的绑定 在 Mppper 映射文件中的标签中的 namespace
中必须指定 Mapper 接口 的全类名 2 Mapper 映射文件中的增删改查标签的 id 必须指定成 Mapper 接口中的方法名
@Testpublic void test() throws Exception{ String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder() .build(inputStream); SqlSession session = sqlSessionFactory.openSession();try { //Mapper接口:获取Mapper接口的 代理实现类对象 EmployeeMapper mapper = session.getMapper(EmployeeMapper.class); Employee employee = mapper.getEmployeeById(1); System.out.println(employee);} finally { session.close(); }}
在Eclipse中引入XML的dtd约束文件,方便编写XML的时候有提示
configuration 配置
properties 属性 settings 设置 typeAliases 类型命名 typeHandlers 类型处理器 objectFactory 对象工厂 plugins 插件 environments 环境 environment 环境变量 transactionManager 事务管理器 dataSource 数据源 databaseIdProvider 数据库厂商标识 mappers 映射器
properties 属性
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis_1129 jdbc.username=root jdbc.password=123
properties: 引入外部的属性文件
resource: 从类路径下引入属性文件 url: 引入网络路径或者是磁盘路径下的属性文件< properties resource=“db.properties” > < /properties>
3)在 environment 元素的 dataSource 元素中为其动态设置
settings 设置:改变 MyBatis 的运行时行为
4 typeAliases 别名处理
自动映射
开启自动驼峰命名规则映射功能, mapUnderscoreToCamelCase=true。自定义resultMap
什么叫延迟加载? 什么时候使用什么时候加载。 延迟加载要解决什么问题呢? 内存的使用问题。使用延迟加载来提升查询的效率, 只需要在全局的Settings 中进行如下的配置:< setting name="lazyLoadingEnabled" value="true"/> < setting name="aggressiveLazyLoading" value="false"/>
3.对象延迟加载的应用场景?
当一个对象占用的内存比较大,而且使用频率比较少。 如:int array = new int[4096] 连接池对象是否适合延迟加载? 个人认为:不适合。 因为在需要使用的时候才去创建连接池,创建对象,分配内存等操作,性能慢,用户访问资源时慢,体验不好。• 官方文档地址
http://www.mybatis.org/generator/ • 官方工程地址 https://github.com/mybatis/generator/releases
逆向工程的使用
@Testpublic void testSelect() throws Exception { SqlSessionFactory ssf = getSqlSessionFactory(); SqlSession session = ssf.openSession();try { EmployeeMapper mapper = session.getMapper(EmployeeMapper.class); Listemps = mapper.selectAll(); for (Employee employee : emps) { System.out.println(employee); }} finally { session.close(); }}@Testpublic void testSelect2() throws Exception { SqlSessionFactory ssf = getSqlSessionFactory(); SqlSession session = ssf.openSession();try { EmployeeMapper mapper = session.getMapper(EmployeeMapper.class); //条件查询: 名字中带有'张' 并且 email中'j' 或者 did = 2 EmployeeExample example = new EmployeeExample(); Criteria criteria = example.createCriteria(); criteria.andLastNameLike("%张%"); criteria.andEmailLike("%j%"); //or Criteria criteriaOr = example.createCriteria(); criteriaOr.andDIdEqualTo(2); example.or(criteriaOr); List emps = mapper.selectByExample(example); for (Employee employee : emps) { System.out.println(employee); }} finally { session.close(); }}
//column(数据表属性) jdbcType(表属性的类型)property(实体类属性) user_id,user_name, register_time, image_path user_name = #{userName}, register_time = #{registerTime}, image_path = #{imagePath}, insert into user user_name, register_time, image_path, #{userName}, #{registerTime}, #{imagePath}, delete from user user_id = #{userId} update user user_id = #{userId}
转载地址:http://uvxab.baihongyu.com/