Mybatis CRUD (addition, deletion, modification and inspection) and process problems (continuous update)

Addition, deletion and modification of Mybatis

Prerequisite: Configure Mybatis file

  1. increase
  2. Inquire
  3. Update
  4. delete
  5. Fuzzy query
  6. Package condition query
  7. Aggregate function query
  8. Chinese garbled characters written to the database

increase

1. Fill in the method in the dao interface class:

    //2.保存账户
    void saveUser(User user);

2. Complete the required query statement (sql), query condition (parameterType), and query return type (resultType) in the xml file (mapping file) corresponding to the dao interface class under the Resources directory.

    <resultMap id="userMap" type="huang.domain.User">
        <id property="id" column="id"></id>
        <result property="username" column="username"></result>
        <result property="birthday" column="birthday"></result>
        <result property="sex" column="sex"></result>
        <result property="address" column="address"></result>
    </resultMap>
    <!-- 上面是自定义的结果值返回对应列表 -->
    <insert id="saveUser" parameterType="huang.domain.User">
        <selectKey keyProperty="id" keyColumn="id" order="AFTER" resultType="Integer">
            select last_insert_id();
        </selectKey>
        insert into usertable(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address});
    </insert>

Note: One of the SQL queries is:

select LAST_INSERT_ID();

The purpose of this query is to query the latest ID inserted recently, in order to achieve this operation in mybaits, use the selectKey tag, point to the id in the class through kerPorperty, point to the id in the table through keyColum, and then through the order surface when the method is executed , Through the resultType, the result of the query is encapsulated in the Id pointed to by keyProperty in User.
Note: The purpose of the resultMap that appears is to resolve the inconsistency between the column names in the table and the variable names in the java entity class. The id tag points to the primary key in the table. The rest use the result tag. Column name, and then in the query, point to the id of the resultMap tag through the resultMap attribute. The second solution is to directly alias all the variable names of the java entity class in the SQL query statement. The alias corresponds to the variable name, which is faster, but the first method is more efficient
. 3. Test the method:

    @Test
    public void testSaveUser() throws IOException {
        //1。创建user,完成user赋值
        User user = new User();
        user.setUsername("xxx");
        Date date = new Date(2000-1-24);
        user.setBirthday(date);
        user.setAddress("湖南省");
        user.setSex("男");
        //7.执行方法
        System.out.println("保存操作之前"+user);
        mapper.saveUser(user);
        System.out.println("保存操作之后"+user);

    }
      @Before
    public void init() throws IOException {
        //2.获取配置信息,
        in = Resources.getResourceAsStream("mybatisConfig.xml");
        //3.读取配置信息,创建构造者
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        //4.通过构造者创建工厂
        SqlSessionFactory factory = builder.build(in);
        //5.通过工厂获取session对象
        session = factory.openSession();
        //6.通过session对象获取mapper映射对象
        mapper = session.getMapper(IUserDao.class);
    }
    @After
    public void destory() throws IOException {
        session.commit();//如果不commit事务,则表中不会有数据
        //8。释放资源
        in.close();
        session.close();
    }

Query the
write method in the 1.dao interface class:

    //1。查询所有
//    @Select("select * from usertable")
    List<User> findAll();
        //5.通过id查询
    User findById(Integer id);

2. Write mapper in the xml file under the mapping path as follows:

<mapper namespace="huang.dao.IUserDao">
    <resultMap id="userMap" type="huang.domain.User">
        <id property="id" column="id"></id>
        <result property="username" column="username"></result>
        <result property="birthday" column="birthday"></result>
        <result property="sex" column="sex"></result>
        <result property="address" column="address"></result>
    </resultMap>
<!-- 查询所有部分-->
    <select id="findAll" resultMap="userMap">
        select * from usertable
    </select>
    <!--根据id查询-->
    <select id="findById" parameterType="java.lang.Integer" resultMap="userMap">
        select * from usertable where id = #{uid}
    </select>

3. Write test class (remove init method and destroy method):

    public void testFindAll() throws IOException {

        List<User> all = mapper.findAll();
        for (User user : all) {
            System.out.println(user);
        }
    }
    @Test
    public void testFindById(){
        User user = mapper.findById(8);
        System.out.println(user);
    }

Update
1.dao layer interface class write method:

	    //3.修改账号
    void updateUser(User user);

2. Fill in the implementation part in the mapping file


    <update id="updateUser" parameterType="huang.domain.User">
        update usertable set username=#{username},address=#{address},sex=#{sex} where id =#{id};
    </update>

3. Fill in the test class (remove the initialization method and end method)

	    @Test
    public void testUpdateUser(){
        User user = new User();
        user.setUsername("xxx");
        user.setAddress("xxx");
        user.setSex("女");
        user.setId(8);
        mapper.updateUser(user);
    }

Delete the
fill method in the 1.dao interface class:

    //4.删除账户
    void deleteUser(Integer userId);

2. Fill in the implementation part in the mapping file:

  <delete id="deleteUser" parameterType="java.lang.Integer">
        delete from usertable where id=#{uid};
    </delete>

3. Test part:

    @Test
    public void testDeleteUser(){
        mapper.deleteUser(11);
    }

The
method of filling in the fuzzy query 1.dao interface class:

    //6.模糊查询含“川”的地址
    List<User> findAddress(String address);

2. The implementation method in the mapping file:

    <select id="findAddress" parameterType="java.lang.String" resultType="huang.domain.User">
        select address from usertable where address like #{address}
    </select>

3. When using, the "%" sign is best not to be used in the mapping file, but to add a percent sign to the parameter when calling the method; for example:

    @Test
    public void testFindAddress(){
        List<User> users = mapper.findAddress("%川%");
        for (User user : users) {
            System.out.println(user);
        }
    }

Encapsulate query conditions for query
1. Create query condition class:

public class QueryVo {
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

2. Fill in the method in the dao interface class:

    //8,根据查询条件类传递参数进行查询
    List<User> findByQueryVo(QueryVo vo);

3. Implementation method in the mapping file:

    <select id="findByQueryVo" parameterType="huang.domain.QueryVo" resultType="huang.domain.User">
        select * from usertable where address like #{user.address}
    </select>

Using the OGNL expression, the class filled out in parameType, in # {}, you can directly use its internal member variables. The essence of encapsulating query conditions is to store multiple query conditions as member variables in a class, and then pass Obtain the required conditions by the OGNL expression in # {}
OGNL expression
4. Test part:

    @Test
    public void findByQueryVo(){
        QueryVo queryVo = new QueryVo();
        User user = new User();
        user.setAddress("%川%");
        queryVo.setUser(user);
        List<User> users = mapper.findByQueryVo(queryVo);
        for (User user1 : users) {
            System.out.println(user1);
        }
    }

Use of aggregate functions
1.dao interface class filling method:

    //7.聚合函数,查询所有用户的个数
    int countUser();

2. Implemented in the mapping file:

    <select id="countUser" resultType="java.lang.Integer">
        select count(id) from usertable
    </select>

3. Test part:

    @Test
    public void testCountUser(){
        int countUser = mapper.countUser();
        System.out.println(countUser);
    }

Garbled problem
Problem: problem
Solved: In the main configuration file of mybatis, set the url, add at the end:

?useUnicode=true&amp;characterEncoding=UTF-8

The whole is as follows:

 <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=UTF-8"/>

Since the encoding method used is not set, garbled characters will appear, just specify the encoding

Published 12 original articles · Likes0 · Visits 139

Guess you like

Origin blog.csdn.net/weixin_44065691/article/details/105375143