往期博客----> Mybatis的使用-操作数据库的学习和总结
public interface PersonMapper {
//定义一个查询所有消息的方法
List<Person> queryAll()
}
//1.这里使用接口的全限定名来当做命名空间
<mapper namespace="com.offcn.mapper.PersonMapper">
<select id="queryAll" resultMap="com.offcn.pojo.Person">
select * from person
select>
mapper>
@Test
public void m1() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = build.openSession();
//前三部没有任何改变,获取SqlSession对象
//使用代理模式获取接口对象,传入接口的类对象
PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
List<Person> people = mapper.queryAll();
people.forEach(a-> System.out.println(a));
sqlSession.commit();
sqlSession.close();
}
1.使用方法索引
void updatePerson(int id,String name);
arg0,arg1,arg2… | param1,param2.param3… |
---|
<update id="updatePerson">
update person set pname=#{arg1} where pid=#{agr0}
update>
<update id="updatePerson">
update person set pname=#{param2} where pid=#{param1}
update>
<update id="updatePerson">
update person set pname=#{arg1} where pid=#{param1}
update>
2.使用注解@Param
void updatePerson(@Param("pid") int pid,@Param("pname") String pname);
<update id="updatePerson">
update person set pname=#{name} where pid=#{id}
update>
3.使用引用类型对象
4.使用Map(强烈推荐)
void updatePerson(Map map);
<update id="updatePerson">
//这里直接使用Map集合中的键值名就可以了
update person set pname=#{pname} where pid=#{pid}
update>
@Test
public void testupdatePerson() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = build.openSession();
PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
Map map=new HashMap();
map.put("pid",9);
map.put("pname","程序逸");
mapper.updatePerson(map);
sqlSession.commit();
sqlSession.close();
}
select * from person where name like “%张%”
//模糊查询
List<Person> fuzzy(String name);
//第一种,直接使用双引号拼接,缺点:Oracle数据库除了取别名使用双引号,其余不允许使用
<select id="fuzzy">
select * from person where name like "%"#{name}"%";
select>
//第二种,使用${}来拼接,类似java中String的+操作,缺点:产生sql注入问题
<select id="fuzzy">
select * from person where name like '%${name}%';
select>
//第三种使用字符串拼接函数
select * from person where name like concat('%',#{name},'%')
// 缺点:0racle数据库concat函数不支持多次拼接
// 解决方案:
select * from person where name like concat(concat('%',#{name}),'%')
<sql>
id,name,adress
sql>
<select id="queryByName">
select <include refid="baseColumn"/> from person where pname like concat(concat('%',#{name}),'%')
select>
//1.标签的id属性类似唯一标识,type是指定的实体类
<resultMap id="queryAll" type="com.offcn.pojo.Person">
//2.id标签是设置主键映射关系,property为实体类中属性名,column是表中字段名
<id property="pid" column="pid">id>
//3.result是普通字段指定映射关系
<result property="pname" column="pname">result>
<result property="adress" column="adress">result>
resultMap>