第一个Mybatis程序

Posted Rzk

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第一个Mybatis程序相关的知识,希望对你有一定的参考价值。

maven依赖

      <!--导入依赖-->
      <dependencies>
          <!--导入mysql驱动-->
          <dependency>
              <groupId>mysql</groupId>
              <artifactId>mysql-connector-java</artifactId>
              <version>5.1.47</version>
          </dependency>
          <!--导入mybatis驱动-->
          <dependency>
              <groupId>org.mybatis</groupId>
              <artifactId>mybatis</artifactId>
              <version>3.5.2</version>
          </dependency>
          <!--junit-->
          <dependency>
              <groupId>junit</groupId>
              <artifactId>junit</artifactId>
              <version>4.12</version>
          </dependency>
      </dependencies>

编写一个mybatis.xml配置文件

  <?xml version="1.0" encoding="UTF-8" ?>
  <!DOCTYPE configuration
          PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
          "http://mybatis.org/dtd/mybatis-3-config.dtd">

  <!--configguration核心配置文件-->

  <configuration>
      <!--导入外部配置文件-->
      <properties resource="db.properties"/>

      <!--导入日志功能-->
      <settings>
          <setting name="logImpl" value="STDOUT_LOGGING"/>
      </settings>

      <!--起別名-->
      <typeAliases>
          <typeAlias type="com.rzk.pojo.User" alias="User"/>
      </typeAliases>

      <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>
      <!--每一个Mapper.xml 都需要在Mybatis核心配置文件中注册-->
      <mappers>
          <mapper resource="com/rzk/mapper/UserMapper.xml"/>
      </mappers>
  </configuration>

db.properties文件

  driver=com.mysql.jdbc.Driver
  url=jdbc:mysql://localhost:3306/数据库名?userSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF8
  username=root
  password=123456

写一个工具类

  public class MybatisUtils {
      private static SqlSessionFactory sqlSessionFactory;
      static{
          try {
              String resources="mybatis-config.xml";
              InputStream inputStream = Resources.getResourceAsStream(resources);
              sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
          } catch (IOException e) {
              e.printStackTrace();
          }
      }

      public static SqlSession getSqlSessionFactory() {
          return sqlSessionFactory.openSession();
      }
  }

编写一个实体类

  DROP TABLE IF EXISTS `user`;
  CREATE TABLE `user` (
    `id` int(20) auto_increment,
    `name` varchar(30) DEFAULT NULL,
    `pwd` varchar(30) DEFAULT NULL,
    PRIMARY KEY (`id`)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

  INSERT INTO `user` VALUES (\'1\', \'李倩\', \'123123\');
  INSERT INTO `user` VALUES (\'2\', \'张三\', \'123456\');
  INSERT INTO `user` VALUES (\'3\', \'李四\', \'123456\');
  INSERT INTO `user` VALUES (\'4\', \'赵柳\', \'1234556\');
  INSERT INTO `user` VALUES (\'6\', \'libai\', \'123456\');      
  INSERT INTO `user` VALUES (\'7\', \'lisi\', \'123123\');
  INSERT INTO `user` VALUES (\'8\', \'聊吧\', \'123123\');

写一个UserDao接口

  public interface UserMapper  {
      //查询用户
      List<User> getUserList();
      //根据ID查询用户
      User getUserById(@Param("userId") int id);
      //insert 一个用户
      int addUser(User user);
      //修改用户
      int updateUser(User user);
      //删除用户
      int deleteUser(@Param("userId") int id);
  }

在resources编写对应的mapper文件

  <?xml version="1.0" encoding="UTF-8" ?>
   <!DOCTYPE mapper
          PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
          "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  <!--namespace绑定一个对应的Dao/Mapper接口-->
  <mapper namespace="com.rzk.mapper.UserMapper">

      <select id="getUserList" resultType="com.rzk.pojo.User">
          select * from user
      </select>
        
       <!--根据id查询单个用户-->
       <select id="getUserById" parameterType="int" resultType="com.rzk.pojo.User">
           select * from user where id = #{userId}
       </select>

       <!--插入-->
       <insert id="addUser" parameterType="User">
           insert into user(id,name,pwd) values(#{id},#{name},#{pwd})
       </insert>

       <!--修改-->
       <insert id="updateUser" parameterType="User">
              update user set name=#{name},pwd=#{pwd} where id=#{id}
       </insert>

       <!--删除-->
       <delete id="deleteUser" parameterType="int">
             delete from user where id = #{userId}
       </delete>
  </mapper>
  • 插入时主键自增

  • useGeneratedKeys="true" keyProperty="id" keyColumn="id"

         <!--插入-->
         <insert id="addUser" parameterType="User"
         useGeneratedKeys="true" keyProperty="id" keyColumn="id">
             insert into user(name,pwd) values(#{name},#{pwd})
         </insert>
    

日志功能

  log4j.rootLogger=DEBUG,console,file
  #控制台输出的相关设置
  log4j.appender.console = org.apache.log4j.ConsoleAppender
  log4j.appender.console.Target = System.out
  log4j.appender.console.Threshold=DEBUG
  log4j.appender.console.layout = org.apache.log4j.PatternLayout
  #log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
  log4j.appender.console.layout.ConversionPattern=%5p [%t] - %m%n
  #文件输出的相关设置
  log4j.appender.file = org.apache.log4j.RollingFileAppender
  log4j.appender.file.File=./log/rzk.log
  log4j.appender.file.MaxFileSize=10mb
  log4j.appender.file.Threshold=DEBUG
  log4j.appender.file.layout=org.apache.log4j.PatternLayout
  log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
  #日志输出级别
  log4j.logger.org.mybatis=DEBUG
  log4j.logger.java.sql=DEBUG
  log4j.logger.java.sql.Statement=DEBUG
  log4j.logger.java.sql.ResultSet=DEBUG
  log4j.logger.java.sql.PreparedStatement=DEBUG

测试

      @Test
      public void test(){
          SqlSession sqlSession = MybatisUtils.getSqlSession();
          UserMapper mapper = sqlSession.getMapper(UserMapper.class);
          List<User> userList = mapper.getUserList();
          for (User user : userList) {
              System.out.println(user);
          }
      }

总结

  • id :就是对于的namespace中的方法名

  • resultType : sql语句执行的返回值

  • parameterType :参数类型

  • 增删改需要提交事务

  • 如果想让mybatis自动提交事务,可在根据类openSession 开启自动提交

     public static SqlSession getSqlSession(){
            return sqlSessionFactory.openSession(true);
     }

以上是关于第一个Mybatis程序的主要内容,如果未能解决你的问题,请参考以下文章

第一个Mybatis程序

第一个Mybatis程序

JAVA学习笔记036-第一个简单的Mybatis程序(代码经验证)

Mybatis框架第二篇

跟着老杜学MyBatis+第2天+MyBatis入门程序

跟着老杜学MyBatis+第2天+MyBatis入门程序