Day14 (2) CRUD operation of Mybatis (original Dao development method)

One, entity classes and tables

User class

src\main\java\cn\cyl\bean\User.java

public class User {
    
    
    private int id;
    private String username;
    private Date birthday;
    private int sex;
    private String address;
    //省略get set toString方法
    }

User table

Insert picture description here

2. User fuzzy query

1. The first fuzzy query configuration method

(1) Configure
src\main\resources\UserMapper.xml in the user's mapping configuration file

<select id="findByUserName" parameterType="String" resultType="cn.cyl.bean.User">
    select * from user where username like #{keyword}
</select>

(2) Add the test method of fuzzy query

@Test
public void selectTest01(){
    
    
    //创建SqlSession对象
    SqlSession sqlSession = MySessionUtils.getSession();
    //执行SqlSession对象执行查询
    //查询结果为集合,参1:namespace.id 参2:关键字
    List<User> list = sqlSession.selectList("cn.cyl.bean.User.findByUserName", "张%");
    //打印结果
    for (User user:list){
    
    
        System.out.println(user);
    }
    //关闭资源
    sqlSession.close();
}

(3) Console output

Insert picture description here
(4) Summary: We did not add% in the configuration file as the condition of the fuzzy query, so when passing in the string argument, we need to give the identifier% of the fuzzy query. The #{keyword} in the configuration file is just a placeholder, so the SQL statement is displayed as "?".
(5) Note:

  • selectList can query one or more records.
  • selectOne queries one record, if you use selectOne to query multiple records, an exception is thrown:

2. Another configuration method of fuzzy query

(1) Configure
src\main\resources\UserMapper.xml in the user's mapping configuration file

<select id="findByUserName2" parameterType="string" resultType="cn.cyl.bean.User">
    select * from user where username like '${value}%'
</select>

We changed the original #{} placeholder above to ${value}.
Note that if the fuzzy query is used, the wording of ${value} is fixed and cannot be written as other names-
(2) Add the test method of fuzzy query

@Test
public void selectTest02(){
    
    
    //创建SqlSession对象
    SqlSession sqlSession = MySessionUtils.getSession();
    //执行SqlSession对象执行查询
    //查询结果为集合,参1:namespace.id 参2:关键字
    List<User> list = sqlSession.selectList("cn.cyl.bean.User.findByUserName2", "张");
    //打印结果
    for (User user:list){
    
    
        System.out.println(user);
    }
    sqlSession.close();
}

(3) Console output
Insert picture description here
(4) Summary: It can be found that we do not need to add the fuzzy query matching symbol% ​​in the program code. The effect of these two methods is the same, but the executed statements are different .

3. The difference between #{} and ${}

  • #{} represents a placeholder symbol. The
    preparedStatement can be used to set the value in the placeholder through #{}, and the java type and jdbc type conversion are automatically performed. #{} can effectively prevent sql injection. #{}Can receive simple type values ​​or pojo attribute values. If parameterType transmits a single simple type value, #{} brackets can be value or other names.
  • ${} means splicing sql strings.
    Through ${}, the content passed in parameterType can be spliced ​​in SQL without jdbc type conversion. ${} can receive simple type values ​​or pojo attribute values. If parameterType transmits a single simple type value, ${} can only be value in parentheses.

Three, insert data

(1) Configure
src\main\resources\UserMapper.xml in the user's mapping configuration file

<!--parameterType:传入User对象; #{username}等价于user.getName()-->
<insert id="saveUser" parameterType="cn.cyl.bean.User">
    insert into user values(null,#{username},#{birthday},#{sex},#{address});
</insert>

detail:

  • The parameterType attribute:
    represents the type of the parameter, because what we want to pass in is an object of a class, so the type is the full name of the class .
  • The #{} character is used in the sql statement:
    it represents a placeholder, which is equivalent to what the original jdbc part learned?, which is used to replace the actual data when the statement is executed.
    The specific data is determined by the content in #{}.
  • #{} How to write the content:
    Since the parameter of our save method is a User object, here we need to write the attribute name in the User object.
    It uses ognl expressions.
  • ognl expression:
    It is an expression language provided by apache, its full name is: Object Graphic Navigation Language, which obtains data according to a certain grammatical format.
    The syntax format is to use #{
    object.object } 's way #{user.username} It will first find the user object, then find the username attribute in the user object, and call the getUsername() method to get the value out. But we specify the entity class name on the parameterType attribute, so you can omit user. and write username directly.

(2) Add the test method of inserting data

@Test
public void insertTest02(){
    
    
    //创建SqlSession对象
    SqlSession sqlSession = MySessionUtils.getSession();
    //创建实体对象
    User user = new User();
    user.setUsername("jack");
    user.setSex(1);
    user.setBirthday(new Date());
    user.setAddress("大鸡腿");
    //执行SqlSession对象执行插入
    sqlSession.insert("cn.cyl.bean.User.saveUser",user);
    //插入数据操作需要提交事务
    sqlSession.commit();
    //释放资源
    sqlSession.close();
}

(3) Console output
Insert picture description here
Insert picture description here

Four, modify user

(1) Configure
src\main\resources\UserMapper.xml in the user's mapping configuration file

<update id="updateUser" parameterType="cn.cyl.bean.User">
    update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}
</update>

(2) Add and modify user test methods

@Test
public void updateTest03(){
    
    
    //创建SqlSession对象
    SqlSession sqlSession = MySessionUtils.getSession();
    //创建实体对象
    User user = new User();
    user.setId(28);
    user.setUsername("rose");
    user.setSex(0);
    user.setBirthday(new Date());
    user.setAddress("大闸蟹");
    //执行SqlSession对象执行更新
    sqlSession.update("cn.cyl.bean.User.updateUser",user);
    //更新数据操作需要提交事务
    sqlSession.commit();
    //释放资源
    sqlSession.close();
}

(3) Console output
Insert picture description here
Insert picture description here

Five, delete users

(1) Configure
src\main\resources\UserMapper.xml in the user's mapping configuration file

<delete id="deleteById" parameterType="int">
      delete from user where id = #{id}
</delete>

(2) Test method for adding and deleting users

@Test
public void deleteTest04(){
    
    
    //创建SqlSession对象
    SqlSession sqlSession = MySessionUtils.getSession();
    //执行SqlSession对象执行删除
    //执行删除 参1:namespace.id的格式    参2:参数值
    sqlSession.delete("cn.cyl.bean.User.deleteById",104);
    //删除数据操作需要提交事务
    sqlSession.commit();
    //释放资源
    sqlSession.close();
}

(3) Console output
Insert picture description here
Insert picture description here

6. Comparison of Mybatis and JDBC programming

  1. Frequent database connection creation and release cause waste of system resources and affect system performance. If you use a database connection pool, you can solve this problem.
    Solution: Configure the data connection pool in SqlMapConfig.xml and use the connection pool to manage database links.
  2. Sql statement written in the code makes the code difficult to maintain, and the actual application of sql may change greatly, and sql changes need to change the java code.
    Solution: Separate the Sql statement configuration from the java code in the XXXXmapper.xml file.
  3. Passing parameters to the SQL statement is troublesome, because the where condition of the SQL statement is not necessarily, it may be more or less, and the placeholders need to correspond to the parameters one by one.
    Solution: Mybatis automatically maps the java object to the sql statement, and defines the type of input parameter through the parameterType in the statement.
  4. It is troublesome to parse the result set. SQL changes lead to changes in the parsing code, and it needs to be traversed before parsing. It is more convenient if the database records can be encapsulated into pojo object parsing.
    Solution: Mybatis automatically maps the sql execution result to the java object, and defines the type of the output result through the resultType in the statement.

Guess you like

Origin blog.csdn.net/qq_43639081/article/details/108814591