1.条件查询
我们需要传入查询条件,假如我们希望传入用户名,返回用户信息。
xml:
<!--
与这个方法对应的接口会传入一个username,mybatis会将这个参数传入#{username}
-->
<select id="selectByUsername" resultType="User">
select * from accounting_ledger.user where username = #{username}
</select>
我们通过使用#{xxx}
或是${xxx}
来填入我们给定的属性,实际上Mybatis本质也是通过PreparedStatement
首先进行一次预编译,有效地防止SQL注入问题,但是如果使用${xxx}
就不再是通过预编译,而是直接传值,因此我们一般都使用#{xxx}
来进行操作。
接口:
public interface UserMapper {
List<User> selectByUsername(String username);
}
2.插入语句
xml:
<insert id="insertUser">
insert into accounting_ledger.user(username, password) VALUES (#{username},#{password})
</insert>
接口:
package Mybatis.Mapper;
import Mybatis.User;
import java.util.List;
public interface UserMapper {
List<User> selectUser();
List<User> selectByUsername(String username);
int insertUser(User user);
}
调用这个方法:
User user3=new User();
user3.setPassword("password");
user3.setUsername("lyj不做饭");
int i=testMapper.insertUser(user3);
System.out.println(i);
我们发现虽然xml语句中有两个接受的参数,但是我们在接口中可以直接传入user类,而不必把user分解为两个字段。所以显然mybatis为我们自动分解了。
由于我们并没有指定如何分解user类,而默认的分解方式是根据字段的名字对应的。也就是说我们要保证
VALUES (#{username},#{password})
和user类的字段名称