Mybatis basics (attached: a simple way to use Mybatis to add, delete, modify, and check)

Mybatis

1. Introduction

Mybatis is an excellent 持久层framework that supports ordinary SQL queries, stored procedures and advanced mapping . Mybatis eliminates almost all manual settings of jdbc code and parameters, as well as retrieval and packaging of result sets. Mybatis can use simple xml or annotations for configuration and original mapping. Map the pojo of the interface (plain old java objects, entity classes, ordinary java objects) to records in the database.

Persistence layer: The process of saving Java objects to the database is the semi-automated framework of the persistence layer dao layer mybatis, and SQL statements must be written

JDBC->dbutils->MyBatis->Hibernate

Two, mybatis quick start

Write a test example based on Mybatis (addition, deletion, modification, check):

  • step:
    • 1. Import the mybatis.jar package

      【mybatis】
      mybatis-3.1.1.jar
      【MYSQL 驱动包】
      mysql-connector-java-5.1.7-bin.jar
      
    • 2. Add mybatis configuration file mybatis-conf.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">
      <configuration>
      <environments default="development">
      <environment id="development">
      <transactionManager type="JDBC" />
      <dataSource type="POOLED">
      <property name="driver" value="com.mysql.jdbc.Driver" />
      <property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
      <property name="username" value="root" />
      <property name="password" value="root" />
      </dataSource>
      </environment>
      </environments>
      </configuration>
      
    • 3. Define the entity class corresponding to the table

      public class User {
          private int id;
          private String name;
          private int age;
      }
      
    • 4. Define the SQL mapping file UserMapper.xml for operating the user table

      <mapper namespace="dong">
          <!--
              resultType:实体类的全局路径
          -->
          <select id="getUser" parameterType="int" resultType="com.hong.entity.User">
               select * from users where id=#{id}
          </select>
      
          <insert id="insertUser" >
              insert into users(name,age) values(#{name},#{age})
          </insert>
      
          <delete id="deleteUser">
              delete from users where id=#{id}
          </delete>
      
          <update id="updateUser">
              update users set name=#{name } where id=#{id}
          </update>
      
    • 5. Register userMapper.xml in the mybatis-conf.xml file

      <mappers>
              <!--映射文件的路径-->
              <mapper resource="mapper/UserMapper"></mapper>
          </mappers>
      
    • 6. Write test code: execute the defined select statement

      //1. 读取配置文件
              Reader reader = Resources.getResourceAsReader("mybatis-config");
              //2. 构建Session工厂
              SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
              //3. 创建能执行映射文件中的sql的sqlSession
              SqlSession sqlSession = sqlSessionFactory.openSession();
              //4.执行sql
              //查询
              /*User user = sqlSession.selectOne("dong.getUser", 1);
              System.out.println(user);*/
              //新增
              /*int insert = sqlSession.insert("dong.insertUser", new User(4, "丁丁", 18));
              //事务提交
              sqlSession.commit();
              System.out.println("a!!!!!!!!!!");*/
              //删除
              /*int delete = sqlSession.delete("dong.deleteUser", 4);
              sqlSession.commit();
              System.out.println("a~~~~~~~~~~`");*/
              //修改
              int jhon = sqlSession.update("dong.updateUser", new User(2, "Jhon", 11));
              sqlSession.commit();
              System.out.println("a~~~~~~~~~~~~~~``");
      

Three, operate the crud of the user table

3.1 Implementation of XML

  1. Define the SQL mapping xml file:
<insert id="insertUser" parameterType="com.hong.entity.User">
insert into user(name, age) values(#{name}, #{age});
</insert>
<delete id="deleteUser" parameterType="int">
delete from user where id=#{id}
</delete>
<update id="updateUser" parameterType="com.hong.entity.User">
update user set name=#{name},age=#{age} where id=#{id}
</update>
<select id="getOneUser" parameterType="int" resultType="com.hong.entity.User">
select * from user where id=#{id}
</select>
<select id="getAllUser" resultType="com.hong.entity.User">
select * from user
</select>
  1. Register this mapping file in mybatis-config.xml
<mappers>
	<mapper resource="com/hong/mybatis_test/test1/UserMapper.xml"/>
</mappers>

Fourth, the actual development model

The interface is used in conjunction with the mapping file

1. Create an interface

public interface UserDao {
    /**
     * 查询所有的用户信息
     */
    public List<User> getAllUser();

    /**
     * 根据id查询用户信息
     */
    //@Param:表示把该参数的名称作为映射文件的参数名
    public Users getByNameAndAge(int id);
}

Write the method to be written in the interface

2. Create a mapping file

<?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必须和接口的全路径匹配-->
<mapper namespace="com.hong.dao.UserDao">

    <!--
		id 名称必须和接口中的方法名一致
		查询语句中的resultType必须写
	-->
    <select id="getAllUser"  resultType="com.hong.entity.User">
         select * from users
    </select>
    
    <select id="getByNameAndAge" resultType="com.hong.entity.User">
         select * from users where id=#{id}
    </select>
</mapper>

Guess you like

Origin blog.csdn.net/qq_54605990/article/details/115017460