Mybatis的使用(2)

1 :模糊查询

#{}占位符和¥{}的区别

#{}占位符:传参大部分用#{}传参,它的底层是PreparedStatement对象,是安全的数据库访问,它能够防止sql注入

1.1:如果parmeterType是简单类型(8种基本类型+String),则#{}里面随便写名字

1.2:如果parmeterType是实体类的类型,则#{}里只能是类中成员变量的名称,且区分大小写。

 

¥{}:字符串拼接或字符串替换

1.3:如果parmeterType是简单类型(8种基本类型+String),则${}里面随便写名字

1.4:如果parmeterType是实体类的类型,则${}里只能是类中成员变量的名称,且区分大小写。

注意:基本上不用${},都用#{}即可。

根据名字模糊查询:

<select id="getByName" parameterType="string" resultType="User">
select id,name,pwd from mybatis.user where name like ‘%${name}%’
</select>

优化模糊查询:

<select id="getByName" parameterType="string" resultType="User">
select id,name,pwd from mybatis.user where name like concat('%',#{name},'%')
</select>

设置控制台日志输出的步骤:

在mybatis.xml文件中配置:

<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

根据名字和密码模糊查询:

List<User> getByNameandpwd(
@Param("key")
String columnkey,
@Param("value")
String columnvalue);
<select id="getByNameandpwd"  resultType="User">
select id,name,pwd from mybatis.user where ${key} like concat('%',#{value},'%')
</select>

@parm:因为在写sql语句的时候,有些字段名不在mysql表中,所以要用注解来表示要传入的值

${}的唯一用法:字符串替换

 

2:返回主键值

<insert id="addUser" parameterType="com.ztb.pojo.User">
<selectKey keyProperty="id" resultType="int" order="AFTER">
select last_insert_id()
</selectKey>
insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd})
</insert>
keyProperty:返回的主键值
resultType:主键的返回值类型
order:在插入语句执行前,还是执行后返回主键的值

3:UUID:全球唯一一个由字母和数字组成的字符串

UUID uuid = UUID.randomUUID();
System.out.println(uuid.toString().replace("-",""));

 

posted @ 2022-07-30 21:18  Sunward阳  阅读(99)  评论(0)    收藏  举报