MyBatis 的代码仓库

MyBatis 代码仓库

完整的 MyBatis 教学,请跳转此链接“史上最友好的MyBatis 小白入门”

欢迎来到 MyBatis 的工具类-——代码仓库

文章目录

  • MyBatis 代码仓库
      • Maven 项目结构
      • 依赖配置
      • mybatis-config.xml
      • sql 映射文件
      • Mybatis 必备代码
      • 注意事项

Maven 项目结构

MyBatis 的代码仓库_第1张图片

依赖配置





  <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>5.1.34version>
  dependency>
  
  
  


  <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>3.5.5version>
  dependency>

mybatis-config.xml







DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <environments default="development">
    <environment id="development">
       <transactionManager type="JDBC"/>
       <dataSource type="POOLED">
      
      
      
        <property name="driver" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
      dataSource>
    environment>
  environments>
  <mappers>
        
        <package name="com.itheima.mapper"/>
  mappers>
configuration>

sql 映射文件


DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">


<mapper namespace="com.itheima.mapper.UserMapper">

    <resultMap id="brandResultMap" type="com.itheima.pojo.Brand">
        <result column="brand_name" property="brandName"/>
        <result column="company_name" property="companyName"/>
    resultMap>

    <select id="select" resultType="com.itheima.pojo.User">
       select * from tb_user where usename = #{usename} and password = #{password};

    select>

    <insert id="register" keyProperty="com.itheima.pojo.User">
        insert into tb_user(id,usename,password) values (null,#{usename},#{password});
    insert>
mapper>

Mybatis 必备代码

        //获取 sqlSessionFactory 对象,这三行所申请的资源不需要主动释放,每个方法写一遍即可
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //获取 sqlSession 对象用于执行 sql 语句
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //执行sql语句
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        List<Brand> brands = mapper.selectAll();
        //释放资源
        sqlSession.close();

注意事项

  1. tb_brand 表中 id 需要设置主键和自增长(auto_increment)
  2. mapper 接口和 mapper.xml 文件需要在同一目录
  3. mapper 接口和XML文件中方法名和id需要相同,否则无法定位
  4. 数据库和 Brand 的成员变量名,一定要反复核对,不要出现这样的低级错误

你可能感兴趣的:(代码仓库,mybatis,java,开发语言)